1. application.properties中配置
spring.redis.host=localhost
2. 配置缓存相关(缓存管理器)
@Configuration
public class MyRedisConfig {
/**
* 缓存管理器
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//初始化一个RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
//设置CacheManager的值序列化方式为json序列化
RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
.fromSerializer(jsonSerializer);
RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(pair);
//设置默认超过期时间是30秒
defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
//初始化RedisCacheManager
return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
}
}
3. 声明使用缓存(在主类加@EnableCaching)
@SpringBootApplication
@EnableCaching
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}
4. 使用缓存(@CacheConfig,@Cacheable,@CachePut,@CacheEvict的使用)
@CacheConfig(cacheNames = "emp", cacheManager = "cacheManager")
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
/**
* 将方法的运行结果进行缓存,以后再要相同的数据,直接从缓存中获取,不需要调用方法
* CacheManager管理多个Cache组件,对缓存真正的CRUD在cache中
*
* cache几个属性
* cacheName/value: 指定缓存组件的名字
* key: 缓存数据使用的key,可以用它来指定。默认是方法参数的值
* keyGenerator:key生成器, 可以自己指定key生成器组件id .
* ps: key和keyGenerator二选一即可
* condition:指定符合条件下才缓存 condition = "#id > 3"
* unless:否定缓存,当unless指定条件为true,方法返回值就不会被缓存
* unless = "#result == null"
* sync:是否使用异步模式
*
* 运行流程
* Cacheable
* 1. 方法运行前,先去查询Cache(缓存组件),按照cacheName指定名字获取
* CacheManager先获取相应缓存,第一次获取缓存如果没有Cache组件,则会自动创建
* 2. 去Cahce中查询缓存内容,使用一个key
* 3. 没有查到缓存就调用目标方法
* 4. 将目标方法返回的结果,放进缓存中
*
* @param id
* @return
*/
@Cacheable()
public Employee getEmployee(Integer id) {
System.out.println("---> 查询" + id + "号员工");
return employeeMapper.getEmployee(id);
}
/**
* CachePut:既调用方法,又更新缓存数据
*
* @param employee
* @return
*/
@CachePut(key = "#employee.id")
public Employee updateEmployee(Employee employee) {
System.out.println("---> updateEmployee" + employee);
employeeMapper.updateEmp(employee);
return employee;
}
@CacheEvict(key = "#id")
public void deleteEmployee(Integer id) {
System.out.println("--->删除employee的id是:" + id);
}
}
ps: 1. 需要缓存的数据对象需要实现,Serializable接口,以便于json序列化存入redis
2. pom.xml引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>