Spring定义了org.springframework.cache.CacheManager和org.springframework.cache.Cache接口用来统一不
同的缓存技术。其中,CacheManager是Spring提供的各种缓存技术抽象接口,Cache接口包含缓存的各种操作(增
删改查,我们一般不会直接和此接口打交道)。
针对不同的缓存技术,是需要实现不同的CacheManager,Spring定义了如下表所示的CacheManager实现:
-
CacheManager 描述 SimpleCacheManager 使用简单的Collection来存储缓存,主要用来测试用途 ConcurrentMapCacheManager 使用ConcurrentMap来存储 NoOpCacheManager 仅测试用途,不会市级存储缓存 EhCacheCacheManager 使用EhCache作为缓存技术 GuavaCacheManager 使用Google Guava的GuavaCache作为缓存技术 HazelcastCacheManager 使用Hazelcast作为缓存技术 JCacheCacheManager 支持JCache(JSR-107)标准的实现作为缓存技术,如Apache Commons JCS RedisCacheManager 使用Redis作为缓存技术
Spring Boot的支持:
在Spring Boot中使用缓存时,CacheManager是自动配置的,只需要导入相关的缓存技术的依赖包,并在配置
类上使用@EnableCaching开启缓存技术支持即可。缓存配置如下:
spring.cache.type= #可选generic,ehcache,hazelcast,infinispan,jcache,redis,guava,simple, none
spring.cache.cache-names= #程序启动时创建缓存名称
spring.cache.ehcache.config= #ehcache配置文件地址
spring.cache.hazelcast.config= #hazelcast配置文件地址
spring.cache.infinispan.config= #infinispan配置文件地址
spring.cache.jcache.config= #jcache配置文件地址
spring.cache.jcache.provider= #当多个jcache实现在类路径中的时候,制定jcache实现
spring.cache.guava.spec= #guava spec
下面以Redis为例:
- 导入Redis依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
’
2. 启动缓存
@SpringBootApplication
@EnableCaching
public class SpringBoot181CacheEhcacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot181CacheEhcacheApplication.class, args);
}
}
’
3. 在接口上使用缓存
Domain:
@Entity
public class User implements Serializable{
private static final long serialVersionUID = -8971505764090290428L;
@Id
@GeneratedValue
private Integer id;
private String name;
private Date birthday;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
}
Repository:
@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long>{
@Cacheable(value="user",key="#p0")
User findByName(String name);
@SuppressWarnings("unchecked")
@CachePut(value="user",key="#p0.name")
User save(User user);
}
’
4. 测试缓存
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBoot181CacheEhcacheApplication.class)
public class SpringBoot181CacheEhcacheApplicationTests {
@Autowired
private RedisCacheManager cacheManager;
@Autowired
private CacheManager cacheManager1;
@Test
public void contextLoads() {
}
@Autowired
private UserRepository userRepository;
/*@Before
public void before() {
userRepository.save(new User("AAA", 10));
}*/
@Test
public void test() throws Exception {
System.out.println(cacheManager);
System.out.println(cacheManager1);
User u1 = userRepository.findByName("王传奇");
System.out.println("第一次查询:" + u1.getBirthday());
u1.setBirthday(new Date());
userRepository.save(u1);
User u2 = userRepository.findByName("王传奇");
System.out.println("第二次查询:" + u2.getBirthday());
}
}
通过测试:
(1)在保存user时(使用了@Cacheable),会将数据缓存到user中,查询该记录时,不会发出sql语句
(2)在第一次查询时发出sql语句,将查询结果缓存到user中,第二次查询时不会发出sql语句,而是从缓存中直接读取。
’
5. 切换EhCache缓存
(1)切换依赖包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
(2)配置ehcache.xml,只需要放在类路径下,Spring Boot会自动扫描
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<cache name="users"
maxEntriesLocalHeap="200"
timeToLiveSeconds="600">
</cache>
</ehcache>
’
6. 其他