Skip to content

Instantly share code, notes, and snippets.

@Gueka
Last active August 14, 2019 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gueka/00268e3aee14ac8a7b1f7fe5a6115d0a to your computer and use it in GitHub Desktop.
Save Gueka/00268e3aee14ac8a7b1f7fe5a6115d0a to your computer and use it in GitHub Desktop.
How to configure a service using spring cache abstraction
@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