Last active
August 14, 2019 03:41
-
-
Save Gueka/00268e3aee14ac8a7b1f7fe5a6115d0a to your computer and use it in GitHub Desktop.
How to configure a service using spring cache abstraction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Slf4j | |
@Service | |
@CacheConfig(cacheNames={"weather"}) | |
public class WeatherService { | |
public static final String WEATHER_API_URL = "https://api.openweathermap.org/data/2.5/weather?zip=%s,%s&appid=%s&units=metric"; | |
@Value("${weather.appid}") | |
String appid; | |
@Autowired | |
RestTemplate template; | |
@Cacheable | |
public Weather getByZip(String code, String country) { | |
String URL = String.format(WEATHER_API_URL, code, country, appid); | |
try{ | |
ResponseEntity<Weather> response = template.getForEntity( | |
URL, | |
Weather.class); | |
return response.getBody(); | |
}catch (RestClientException e){ | |
log.error("Unable to get whether information for code: " + code, e); | |
} | |
// If something happend return an empty weather object | |
return Weather.builder().build(); | |
} | |
@CacheEvict(allEntries = true, value = {"weather"}) | |
@Scheduled(fixedDelay = 1000 * 60 * 10) | |
public void reportCacheEvict() { | |
log.info("Flush Cache " + new Date()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment