Skip to content

Instantly share code, notes, and snippets.

@snicoll
Forked from anataliocs/CacheConfig.java
Last active February 17, 2018 17:48
Show Gist options
  • Save snicoll/7bf72686c98a7088e8ea to your computer and use it in GitHub Desktop.
Save snicoll/7bf72686c98a7088e8ea to your computer and use it in GitHub Desktop.
Guava cache with spring boot and clear cache method
import com.google.common.cache.CacheBuilder;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.guava.GuavaCache;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableCaching
public class CacheConfig {
public final static String CACHE_ONE = "cacheOne";
public final static String CACHE_TWO = "cacheTwo";
@Bean
public Cache cacheOne() {
return new GuavaCache(CACHE_ONE, CacheBuilder.newBuilder()
.expireAfterWrite(60, TimeUnit.MINUTES)
.build());
}
@Bean
public Cache cacheTwo() {
return new GuavaCache(CACHE_TWO, CacheBuilder.newBuilder()
.expireAfterWrite(60, TimeUnit.SECONDS)
.build());
}
}
//Used for manually clearing the cache
@Controller
@RequestMapping("/")
public class CacheController {
@CacheEvict(value = CacheConfig.CACHE_ONE, allEntries = true)
@RequestMapping(value = "/clearCache", method = RequestMethod.GET)
public ResponseEntity<String> clearCache() {
return new ResponseEntity<String>("Cache Cleared", HttpStatus.OK);
}
}
@Service
public class CachedService extends WebServiceGatewaySupport implements CachedService {
@Inject
private RestTemplate restTemplate;
@Cacheable(CacheConfig.CACHE_ONE)
public String getCached() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> reqEntity = new HttpEntity<>("url", headers);
ResponseEntity<String> response;
String url = "url";
response = restTemplate.exchange(
url,
HttpMethod.GET, reqEntity, String.class);
return response.getBody();
}
}
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
@moviewang
Copy link

very good

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment