简述
主要讲解Spring Cache Abstraction,Spring 3.1 支持对已有项目集成快速集成,4.1支持JSR-107,Spring Cache Abstraction 核心是基于Java方法的缓存,原理是将Java方法返回值缓存,下次执行如果有缓存就不再执行方法体,因此节省了CPU和IO资源来起到缓存作用,同样Spring Cache Abstraction 是抽象的或者说是规范,需要实现数据的存储,Spring 提供支持几个缓存实现:基于JDK ConcurrentMap缓存实现、, EhCache、Gemfire cache、 Caffeine、 Guava caches ,支持JSR-107,主要讲Spring Cache Abstraction,但在开始会先简述Spring Mvc 对HTTP 304缓存的支持和如何使用。
Spring HTTP 304 缓存
在每次执行完成后计算ETag,如果没有和客户端请求的If-None-Match相同,则返回304,不会返回数据,客户端拿到304将会从本地缓存读取。
非Spring Boot 配置
对于304 EATG缓存,这里讲解在servlet3.0之后配置,核心配置一个Filter即可:
public class MWebApplicationInitializer implements WebApplicationInitializer{
public void onStartup(ServletContext container) {
// ...
// HTTP 304 缓存
FilterRegistration.Dynamic filterRegistration = container.addFilter("etagFilter", new ShallowEtagHeaderFilter());
filterRegistration.addMappingForUrlPatterns(null, true, "/*");
}
}
Spring Boot 只需要配置ShallowEtagHeaderFilter bean 即可:
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
@Bean
public ShallowEtagHeaderFilter hallowEtagHeaderFilter() {
return new ShallowEtagHeaderFilter();
}
}
Spring Cache Abstraction
对于Spring Cache Abstraction开发这需要关心的是标识方法需要缓存和数据缓存存储和读取。
非Spring Boot 配置
- 配置cacheManager bean ,启用缓存 @EnableCaching
@Configuration
@EnableCaching
public class AppConfig {
@Bean
public SimpleCacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
ConcurrentMapCacheFactoryBean bean = new ConcurrentMapCacheFactoryBean();
bean.setName("defaults");
bean.afterPropertiesSet();
Cache defaultCache = bean.getObject();
bean.setName("caches");
bean.afterPropertiesSet();
Cache cachesCache = bean.getObject();
cacheManager.setCaches(Arrays.asList(defaultCache, cachesCache));
return cacheManager;
}
}
- 配置方法缓存
@RestController
@RequestMapping("/caches")
@CacheConfig(cacheNames = "caches")
public class CacheController {
@RequestMapping
@Cacheable
// @CacheResult(cacheName = "caches") // JSR-107 support
public Map find() {
System.err.println(this.getClass().getName() + ".find.in");
Map map = new HashMap();
map.put("id", 1);
map.put("age", 22);
map.put("sex", "女");
return map;
}
}
Spring Boot 配置
- 加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
- 开启缓存
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
- 配置方法缓存
@RestController
@RequestMapping("/caches")
@CacheConfig(cacheNames = "caches")
public class CacheController {
@RequestMapping
@Cacheable
// @CacheResult(cacheName = "caches") // JSR-107 support
public Map find() {
System.err.println(this.getClass().getName() + ".find.in");
Map map = new HashMap();
map.put("id", 1);
map.put("age", 22);
map.put("sex", "女");
return map;
}
}