pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.yml:
spring:
cache:
type: redis
redis:
database: 0
host: localhost
port: 6379
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
timeout: 0
建立cfg目录,在该目录下建立RedisConfig.java:
package com.wance.cfg;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.time.Duration;
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
// 自定义缓存key生成策略
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
StringBuffer sb = new StringBuffer();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
// 缓存管理器
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
setSerializer(template);// 设置序列化工具
template.afterPropertiesSet();
return template;
}
private void setSerializer(StringRedisTemplate template) {
@SuppressWarnings({ "rawtypes", "unchecked" })
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
}
}
实体类要实现序列化
:
业务类:
@Service
@Transactional
@CacheConfig(cacheNames = "animal") //配置缓冲命令空间
public class AnimalServiceImpl extends AbstractService<Animal> implements AnimalService {
@Override
@Cacheable
public List<Animal> findAll() {
return super.findAll();
}
@Override //值大于30放入缓存
@Cacheable(key="#p0",condition = "#p0>30") //缓存key的默认规则:“缓存空间名:长类名.方法名.入参”|
public Animal getById(Object id) {
return super.getById(id);
}
@Override
@CacheEvict(key="#p0") //删除第一个key为第一个入参的缓存
public int deleteById(Object id) {
return super.deleteById(id);
}
@Override
@CachePut(key="#p0.aid") //如果返回值不为空,则更新入参对象对于aid的缓冲值
public Animal updateAndRtn(Animal animal) {
if (super.update(animal)==1){
return super.getById(animal.getAid());
}
return null;
}
@Override
@CacheEvict(allEntries = true)// 清空缓存
public void clearCache() {
}
}
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Dur5Course2SpringmybatistApplication.class)
class Dur5Course2SpringmybatistApplicationTests {
@Autowired
private AnimalService animalService;
@Test
void contextLoads() {
System.out.println(animalService.findAll());
System.out.println(animalService.findAll());
}
@Test
public void testDelete(){
System.out.println(animalService.deleteById(1));
}
@Test
public void testCache(){
System.out.println(animalService.getById(62));
//System.out.println(animalService.deleteById(61));
System.out.println(animalService.getById(62));
}
@Test
public void testChacheUpdate(){
Animal animal=animalService.getById(62);
System.out.println("修改前:"+animal);
animal.setAname("新动物");
animal.setAge(100);
System.out.println("修改后:"+animalService.updateAndRtn(animal));
animalService.clearCache();//清空缓存
System.out.println("修改后的查询:"+animalService.getById(62));
}
}