1、CacheManager
Spring Boot默认集成CacheManager,如下包所示:
可以看出springboot自动配置了 JcacheCacheConfiguration、 EhCacheCacheConfiguration、HazelcastCacheConfiguration、GuavaCacheConfiguration、RedisCacheConfiguration、SimpleCacheConfiguration 等。
默认的CacheManager为ConcurrenMapCacheManager,Spring从Spring3.1开始基于java.util.concurrent.ConcurrentHashMap实现的缓存管理器。Spring Boot 默认使用 ConcurrentMapCacheManager作为缓存技术。新建一个springboot项目,直接使用cache相关注解来测试,效果如下:
2、整合encache
pom依赖引入
org.springframework.boot
spring-boot-starter-cache
net.sf.ehcache
ehcache
application文件配置
spring:
cache:
#ehcache配置文件路径
ehcache:
config: classpath:/ehcache/ehcache.xml
#指定缓存类型,可加可不加
#type: ehcache
encache.xml文件
/>
/>
启动类加上启用缓存注解
@EnableCachingpublic classSpringbootCacheApplication {public static voidmain(String[] args) {
SpringApplication.run(SpringbootCacheApplication.class, args);
}
}
代码中使用cache注解
@Servicepublic class UserServiceImpl implementsUserService {
@AutowiredprivateUserMapper userMapper;//使用ehcache配置的缓存名users_test
private final String USER_CACHE_NAME = "users_test";
@Overridepublic ListlistUser() {returnuserMapper.selectUserList();
}
@Override//@Cacheable(value = USER_CACHE_NAME, key = "#id")
@Cacheable(value = USER_CACHE_NAME, key = "'user' + #id")publicUser selectUserById(Integer id) {returnuserMapper.selectUserById(id);
}
@Override//@CacheEvict(value = USER_CACHE_NAME, key = "#id")
@CacheEvict(value = USER_CACHE_NAME, key = "'user_' + #id")public voiddelete(Integer id) {
userMapper.delete(id);
}
@Override//@CacheEvict(value = USER_CACHE_NAME, key = "#user.userId")
@CacheEvict(value = USER_CACHE_NAME, key = "'user' + #user.userId")//@CachePut(value = USER_CACHE_NAME, key = "'user' + #user.userId")//测试发现只将结果清除,key未清除,导致查询继续使用缓存但结果为空????
public voidupdate(User user) {
userMapper.update(user);
}
}
项目启动后查看CacheManager,如下图所示则表示整合ehcache成功