1.pom引入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>

2.配置redis的链接地址

如果是本地的话可以不配置(因为默认就配置了且端口是6379)
spring.redis.host=127.0.0.1

3.测试类写法

  1. @Autowired
  2. StringRedisTemplate stringRedisTemplate;//操作k-v都是字符串的
  3. @Autowired
  4. RedisTemplate redisTemplate;//k-v都是对象的
  5. @Test
  6. public void test1(){
  7. //给redis保存一个数据
  8. // stringRedisTemplate.opsForValue().append("mess","hello");
  9. String mess = stringRedisTemplate.opsForValue().get("mess");
  10. System.out.println(mess);
  11. }

4.将对象保存成json格式的

  1. 传统的方式。利用jar包把对象转成json
  2. redis默认的序列化机制是用的jdk序列化器,可以自定义改成json序列化器

1>先自定义配置类-将employee这个对象设置默认序列化机制为json序列化器

  1. @Configuration
  2. public class MyRedisConfig {
  3. @Bean
  4. public RedisTemplate<Object, Employee> empRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
  5. RedisTemplate<Object, Employee> template = new RedisTemplate<>();
  6. template.setConnectionFactory(redisConnectionFactory);
  7. Jackson2JsonRedisSerializer<Employee> serializer=new Jackson2JsonRedisSerializer<Employee>(Employee.class);
  8. template.setDefaultSerializer(serializer);
  9. return template;
  10. }
  11. }
  1. 2>编写测试类<br />关键是用RedisTemplate<Object, Employee> employeeRedisTemplate;而不是之前的RedisTemplate redisTemplate;
  1. @Autowired
  2. RedisTemplate<Object, Employee> employeeRedisTemplate;
  3. @Test
  4. public void test1(){
  5. //给redis保存一个数据
  6. // stringRedisTemplate.opsForValue().append("mess","hello");
  7. // String mess = stringRedisTemplate.opsForValue().get("mess");
  8. // System.out.println(mess);
  9. //给redis保存一个json对象
  10. Employee employee= employeeDao.getEmpId(1);
  11. employeeRedisTemplate.opsForValue().set("emp-01",employee);
  12. }
  1. 效果如下:<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缓存

  1. 引入redis的starter之后,容器中保存的是RedisCacheManager;
  2. RedisCacheManager帮我们创建RedisCache作为缓存组件(通过操作redis缓存数据)
  3. 保存对象的时候默认是jdk序列化方法,这里想改成json序列化器

原理就是RedisCacheManager创建RedisCache的时候用的是RedisTemplate,重构下RedisCacheManager就行(这是针对springboot1.x版本-在SpringBoot1.x中,RedisCacheManager是可以使用RedisTemplate作为参数注入的)
然后在service层绑定一下选用哪个管理器就行@CacheConfig( cacheNames=” emp” , cacheManager =”employeeCacheManager” )

  1. @Bean
  2. public RedisTemplate<Object, Employee> empRedisTemplate(
  3. RedisConnectionFactory redisConnectionFactory)
  4. throws UnknownHostException {
  5. RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
  6. template.setConnectionFactory(redisConnectionFactory);
  7. Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
  8. template.setDefaultSerializer(ser);
  9. return template;
  10. }
  11. @Bean
  12. public RedisTemplate<Object, Department> deptRedisTemplate(
  13. RedisConnectionFactory redisConnectionFactory)
  14. throws UnknownHostException {
  15. RedisTemplate<Object, Department> template = new RedisTemplate<Object, Department>();
  16. template.setConnectionFactory(redisConnectionFactory);
  17. Jackson2JsonRedisSerializer<Department> ser = new Jackson2JsonRedisSerializer<Department>(Department.class);
  18. template.setDefaultSerializer(ser);
  19. return template;
  20. }
  21. //CacheManagerCustomizers可以来定制缓存的一些规则
  22. @Primary //将某个缓存管理器作为默认的
  23. @Bean
  24. public RedisCacheManager employeeCacheManager(RedisTemplate<Object, Employee> empRedisTemplate){
  25. RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
  26. //key多了一个前缀
  27. //使用前缀,默认会将CacheName作为key的前缀
  28. cacheManager.setUsePrefix(true);
  29. return cacheManager;
  30. }
  31. @Bean
  32. public RedisCacheManager deptCacheManager(RedisTemplate<Object, Department> deptRedisTemplate){
  33. RedisCacheManager cacheManager = new RedisCacheManager(deptRedisTemplate);
  34. //key多了一个前缀
  35. //使用前缀,默认会将CacheName作为key的前缀
  36. cacheManager.setUsePrefix(true);
  37. return cacheManager;
  38. }

针对springboot2.x版本-有很大的不同,RedisCacheManager构造器已经无法再使用RedisTemplate进行构造
所以这边的写法是:RedisTemplate不需要重构,只需要重构CacheManager就OK了

  1. @Configuration
  2. public class MyRedisConfig {
  3. @Bean
  4. public CacheManager cacheManager(RedisConnectionFactory factory) {
  5. RedisSerializer<String> redisSerializer = new StringRedisSerializer();
  6. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  7. //解决查询缓存转换异常的问题
  8. ObjectMapper objectMapper = new ObjectMapper();
  9. objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance , ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
  10. jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
  11. // 配置序列化(解决乱码的问题)
  12. RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
  13. .entryTtl(Duration.ofDays(1))//设置过期时间
  14. .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
  15. .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
  16. .disableCachingNullValues();
  17. RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
  18. .cacheDefaults(config)
  19. .build();
  20. return cacheManager;
  21. }
  22. }

效果如下:
image.png

具体怎么写缓存注解的话,参考:https://www.yuque.co m/feiyiyangdebiancheng/kb/adove4
扩展:用编码的方式使用缓存:
image.png