SpringBoot 整合Redis
缓存的作用:
简单来说,不用重复调用数据库,保证效率
将方法的运行结果进行缓存;以后再要相同的数据,直接从缓存中获取,不用调用方法,不用调用数据库;
原理:
1、自动配置类: CacheAutoConfiguration
2、缓存的配置类
org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
org.springframework.boot.autoconfigure.cache.GuavaCacheConfiguration
org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration【默认】
org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
3、哪个配置类默认生效:SimpleCacheConfiguration
4、给容器中注册了一个CacheManager:ConcurrentMapCacheManager
5、可以获取和创建ConcurrentMapCache类型的缓存组件;他的作用将数据保存在ConcurrentMap中;
缓存注解:
@Cacheable
主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
1、方法运行之前,先去查询Cache(缓存组件),按照cacheNames指定的名字获取;
* (CacheManager先获取相应的缓存),第一次获取缓存如果没有Cache组件会自动创建。
* 2、去Cache中查找缓存的内容,使用一个key,默认就是方法的参数;
* key是按照某种策略生成的;默认是使用keyGenerator生成的,默认使用SimpleKeyGenerator生成key;
* SimpleKeyGenerator生成key的默认策略;
* 如果没有参数;key=new SimpleKey();
* 如果有一个参数:key=参数的值
* 如果有多个参数:key=new SimpleKey(params);
* 3、没有查到缓存就调用目标方法;
* 4、将目标方法返回的结果,放进缓存中
@CacheEvict
清空缓存
@CachePut
保证方法被调用,又希望结果被缓存
先调用目标方法
将目标方法的结果缓存起来
@EnableCaching
开启基于注解的缓存
keyGenerator
缓存数据时key生成策略
serialize
缓存数据时value序列化策略
1 引入spring-boot-starter-data-redis模块
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2 配置redis连接地址
spring.redis.host=118.24.44.169
3 使用RestTemplate操作redis
- redisTemplate.opsForValue();//操作字符串
- redisTemplate.opsForHash();//操作hash
- redisTemplate.opsForList();//操作list
- redisTemplate.opsForSet();//操作set
- redisTemplate.opsForZSet();//操作有序set
4.配置缓存、CacheManagerCustomizers
@Cacheable(cacheNames = "dept",cacheManager = "deptCacheManager")
// public Department getDeptById(Integer id){
// System.out.println("查询部门"+id);
// Department department = departmentMapper.getDeptById(id);
// return department;
// }