1.pom引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置redis的链接地址
如果是本地的话可以不配置(因为默认就配置了且端口是6379)
spring.redis.host=127.0.0.1
3.测试类写法
@Autowired
StringRedisTemplate stringRedisTemplate;//操作k-v都是字符串的
@Autowired
RedisTemplate redisTemplate;//k-v都是对象的
@Test
public void test1(){
//给redis保存一个数据
// stringRedisTemplate.opsForValue().append("mess","hello");
String mess = stringRedisTemplate.opsForValue().get("mess");
System.out.println(mess);
}
4.将对象保存成json格式的
- 传统的方式。利用jar包把对象转成json
- redis默认的序列化机制是用的jdk序列化器,可以自定义改成json序列化器
1>先自定义配置类-将employee这个对象设置默认序列化机制为json序列化器
@Configuration
public class MyRedisConfig {
@Bean
public RedisTemplate<Object, Employee> empRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Employee> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Employee> serializer=new Jackson2JsonRedisSerializer<Employee>(Employee.class);
template.setDefaultSerializer(serializer);
return template;
}
}
2>编写测试类<br />关键是用RedisTemplate<Object, Employee> employeeRedisTemplate;而不是之前的RedisTemplate redisTemplate;
@Autowired
RedisTemplate<Object, Employee> employeeRedisTemplate;
@Test
public void test1(){
//给redis保存一个数据
// stringRedisTemplate.opsForValue().append("mess","hello");
// String mess = stringRedisTemplate.opsForValue().get("mess");
// System.out.println(mess);
//给redis保存一个json对象
Employee employee= employeeDao.getEmpId(1);
employeeRedisTemplate.opsForValue().set("emp-01",employee);
}
效果如下:<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/22543923/1635067292759-d5d578e5-5599-42e7-ab68-6b38112d63cf.png#clientId=u2fb5e072-20bb-4&from=paste&height=215&id=u7acaec52&margin=%5Bobject%20Object%5D&name=image.png&originHeight=215&originWidth=654&originalType=binary&ratio=1&size=24440&status=done&style=none&taskId=u50222637-4ac2-4352-82d1-37d4d3937d6&width=654)
5.redis缓存
- 引入redis的starter之后,容器中保存的是RedisCacheManager;
- RedisCacheManager帮我们创建RedisCache作为缓存组件(通过操作redis缓存数据)
- 保存对象的时候默认是jdk序列化方法,这里想改成json序列化器
原理就是RedisCacheManager创建RedisCache的时候用的是RedisTemplate,重构下RedisCacheManager就行(这是针对springboot1.x版本-在SpringBoot1.x中,RedisCacheManager是可以使用RedisTemplate作为参数注入的)
然后在service层绑定一下选用哪个管理器就行@CacheConfig( cacheNames=” emp” , cacheManager =”employeeCacheManager” )
@Bean
public RedisTemplate<Object, Employee> empRedisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
template.setDefaultSerializer(ser);
return template;
}
@Bean
public RedisTemplate<Object, Department> deptRedisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Department> template = new RedisTemplate<Object, Department>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Department> ser = new Jackson2JsonRedisSerializer<Department>(Department.class);
template.setDefaultSerializer(ser);
return template;
}
//CacheManagerCustomizers可以来定制缓存的一些规则
@Primary //将某个缓存管理器作为默认的
@Bean
public RedisCacheManager employeeCacheManager(RedisTemplate<Object, Employee> empRedisTemplate){
RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
//key多了一个前缀
//使用前缀,默认会将CacheName作为key的前缀
cacheManager.setUsePrefix(true);
return cacheManager;
}
@Bean
public RedisCacheManager deptCacheManager(RedisTemplate<Object, Department> deptRedisTemplate){
RedisCacheManager cacheManager = new RedisCacheManager(deptRedisTemplate);
//key多了一个前缀
//使用前缀,默认会将CacheName作为key的前缀
cacheManager.setUsePrefix(true);
return cacheManager;
}
针对springboot2.x版本-有很大的不同,RedisCacheManager构造器已经无法再使用RedisTemplate进行构造
所以这边的写法是:RedisTemplate不需要重构,只需要重构CacheManager就OK了
@Configuration
public class MyRedisConfig {
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance , ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofDays(1))//设置过期时间
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
效果如下:
具体怎么写缓存注解的话,参考:https://www.yuque.co m/feiyiyangdebiancheng/kb/adove4
扩展:用编码的方式使用缓存: