springboot 缓存

为了实现是在数据中查询数据还是在缓存中查询数据,在application.yml 中将mybatis 对应的mapper 包日志设置为debug 。

  1. spring:
  2. datasource:
  3. username: root
  4. password: rootpassword
  5. url: jdbc:mysql://localhost:3306/springboot
  6. driver-class-name: com.mysql.jdbc.Driver
  7. debug: true
  8. logging:
  9. level:
  10. com:
  11. springbootmybatis:
  12. mapper: debug

然后在springboot的主类上添加 @EnableCaching 启动缓存。

然后在service 类中的方法上添加上缓存注解。

  1. @Cacheable(value = "user")
  2. public User selectUserById(Integer id) {
  3. User user = userMapper.selectUserById(id);
  4. return user;
  5. }

@Cacheable

​ 默认的是将传入参数(id)作为缓存的 key ,方法的返回值作为 value 存入缓存中 。

在方法 selectUserById(Integer id ) 执行之前 先去根据 key 去缓存中查询是否有该 key 的数据,如果有,则直接在缓存中查询数据,然后返回,不再执行 selectUserById 方法,如果没有在缓存中查到该 key 的数据,才回去执行 selectUserById 方法。

@CachePut

  1. @CachePut(value = "user")
  2. public User updateUser(User user) {
  3. userMapper.updateUser(user);
  4. return user;
  5. }

默认的是将传入参数(id)作为缓存的 key ,@CachePut 在方法执行之后执行,将方法返回的结果写入缓存,

从缓存中查询到的仍然是旧的缓存数据,需要在 @CachePut(value = "user",key = "#result.id") 或者@CachePut(value = "user",key = "#user.id") 只要在 key 设置为 user 的 id ,然后根据id 去查询,就能从缓存中获取修改后的数据。

@CacheEvict

  1. @CacheEvict(value = "user",key = "#id")

清除操作默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作 ,可以使用 beforeInvocation 改变删除缓存的时间,当将 beforeInvocation 设置为 true 时,会在执行方法之前删除缓存中指定的元素,不管方法执行是否存在异常,都会删除缓存。 删除指定 key 的缓存。allEntries 默认为 false ,当为 true 时,会忽略指定的 key ,删除所有缓存元素。不指定 key 时默认一方法的参数作为缓存的 key。

@Caching

@Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。

  1. @Target({ElementType.METHOD, ElementType.TYPE})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Inherited
  4. @Documented
  5. public @interface Caching {
  6. Cacheable[] cacheable() default {};
  7. CachePut[] put() default {};
  8. CacheEvict[] evict() default {};
  9. }
  1. @Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),
  2. @CacheEvict(value = "cache3", allEntries = true) })
  3. public List<User> selectUser() {
  4. List<User> users = userMapper.selectUser();
  5. return users;
  6. }

使用redis 缓存:

导入对应的jar:使用fastjson 来序列化value

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>fastjson</artifactId>
  9. <version>1.2.47</version>
  10. </dependency>

在application.yml 添加配置:

  1. spring:
  2. redis:
  3. host: #redis 安装的IP,其他的可以不用配置,默认的就可以满足测试需要

在springboot 1 中配置redis

  1. import com.alibaba.fastjson.JSON;
  2. import com.alibaba.fastjson.serializer.SerializerFeature;
  3. import org.springframework.cache.CacheManager;
  4. import org.springframework.cache.annotation.CachingConfigurerSupport;
  5. import org.springframework.cache.annotation.EnableCaching;
  6. import org.springframework.cache.interceptor.KeyGenerator;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.data.redis.cache.RedisCacheManager;
  10. import org.springframework.data.redis.connection.RedisConnectionFactory;
  11. import org.springframework.data.redis.core.RedisTemplate;
  12. import org.springframework.data.redis.core.StringRedisTemplate;
  13. import org.springframework.data.redis.serializer.RedisSerializer;
  14. import org.springframework.data.redis.serializer.SerializationException;
  15.  
  16. import java.lang.reflect.Method;
  17. import java.nio.charset.Charset;
  18.  
  19. @EnableCaching
  20. @Configuration
  21. public class RedisConfig extends CachingConfigurerSupport {
  22. @Bean
  23. public KeyGenerator wiselyKeyGenerator() {
  24. return new KeyGenerator() {
  25. @Override
  26. public Object generate(Object target, Method method, Object... params) {
  27. StringBuilder sb = new StringBuilder();
  28. sb.append(target.getClass().getName());
  29. sb.append(method.getName());
  30. for (Object obj : params) {
  31. sb.append(obj.toString());
  32. }
  33. return sb.toString();
  34. }
  35. };
  36. }
  37.  
  38. @Bean
  39. public CacheManager cacheManager(
  40. @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
  41. return new RedisCacheManager(redisTemplate);
  42. }
  43.  
  44. @Bean
  45. public RedisTemplate<String, String> redisTemplate(
  46. RedisConnectionFactory factory) {
  47. StringRedisTemplate template = new StringRedisTemplate(factory);
  48. FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
  49. template.setValueSerializer(serializer);
  50. template.afterPropertiesSet();
  51. return template;
  52. }
  53.  
  54. private static class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
  55. private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
  56. private Class<T> clazz;
  57. public FastJsonRedisSerializer(Class<T> clazz) {
  58. this.clazz = clazz;
  59. }
  60.  
  61. @Override
  62. public byte[] serialize(T t) throws SerializationException {
  63. if (t == null) {
  64. return new byte[0];
  65. }
  66. return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
  67. }
  68.  
  69. @Override
  70. public T deserialize(byte[] bytes) throws SerializationException {
  71. if (bytes == null || bytes.length <= 0) {
  72. return null;
  73. }
  74. String str = new String(bytes, DEFAULT_CHARSET);
  75. return (T) JSON.parseObject(str, clazz);
  76. }
  77. }
  78. }

然后在测试类上加上缓存的注解就可以在redis中查看已经序列化成json格式的数据。

在springboot2 中配置redis

其他的配置不用动,需要修改RedisConfig.java 因为springboot2 中new RedisCacheManager(redisTemplate);被遗弃了

  1. @Bean
  2. public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
  3. //初始化一个RedisCacheWriter
  4. RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
  5. //设置CacheManager的值序列化方式为 fastJsonRedisSerializer,但其实RedisCacheConfiguration默认使用StringRedisSerializer序列化key,
  6. ClassLoader loader = this.getClass().getClassLoader();
  7.  
  8. FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(loader.getClass());
  9. RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer);
  10. RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
  11. RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
  12. return cacheManager;
  13. }

这样设置就可以正常使用了

springboot 2 集成 redis 缓存 序列化的更多相关文章

  1. 在springboot中使用redis缓存,将缓存序列化为json格式的数据

    背景 在springboot中使用redis缓存结合spring缓存注解,当缓存成功后使用gui界面查看redis中的数据 原因 springboot缓存默认的序列化是jdk提供的 Serializa ...

  2. springboot集成redis缓存

    1.pom.xml增加redis缓存起步依赖(spring-boot-starter-parent包含许多starter版本) <dependency> <groupId>or ...

  3. SpringBoot缓存管理(三) 自定义Redis缓存序列化机制

    前言 在上一篇文章中,我们完成了SpringBoot整合Redis进行数据缓存管理的工作,但缓存管理的实体类数据使用的是JDK序列化方式(如下图所示),不便于使用可视化管理工具进行查看和管理. 接下来 ...

  4. 搞懂分布式技术14:Spring Boot使用注解集成Redis缓存

    本文内容参考网络,侵删 本系列文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查看 https://github.com/h2pl/Java-Tutor ...

  5. 集成Redis缓存

    一.简介 1.场景 由于首页数据变化不是很频繁,而且首页访问量相对较大,所以我们有必要把首页数据缓存到redis中,减少数据库压力和提高访问速度. 2.RedisTemplate Jedis是Redi ...

  6. Redis缓存 序列化对象存储乱码问题

    使用Redis缓存对象会出现下图现象: 键值对都是乱码形式. 解决以上问题: 如果是xml配置的 我们直接注入官方给定的keySerializer,valueSerializer,hashKeySer ...

  7. SpringBoot整合集成redis

    Redis安装:https://www.cnblogs.com/zwcry/p/9505949.html 1.pom.xml <project xmlns="http://maven. ...

  8. Spring Boot2(三):使用Spring Boot2集成Redis缓存

    前言 前面一节总结了SpringBoot实现Mybatis的缓存机制,但是实际项目中很少用到Mybatis的二级缓存机制,反而用到比较多的是第三方缓存Redis. Redis是一个使用ANSI C编写 ...

  9. 完整SpringBoot Cache整合redis缓存(二)

    缓存注解概念 名称 解释 Cache 缓存接口,定义缓存操作.实现有:RedisCache.EhCacheCache.ConcurrentMapCache等 CacheManager 缓存管理器,管理 ...

随机推荐

  1. exe4j 打包(多个jar打包)

    一,自行下载exe4j 注册码: 用户名和公司名可随便填A-XVK258563F-1p4lv7mg7savA-XVK209982F-1y0i3h4ywx2h1A-XVK267351F-dpurrhny ...

  2. python中的OrderedDict

    该类型存放顺序和添加顺序一致,比如逐个赋值,但和dict直接转化过去的顺序不一定一样. d1 = collections.OrderedDict() d1['b'] = 'B'd1['a'] = 'A ...

  3. 帆软报表PC端实施报表心得体会

    1.报表制作完成后,预览时自动显示查询内容,在控件处设置: 2.求一列数据的最小值(除去0),并对最小值字体加粗标绿,需要对对应单元格设置条件属性,并插入公式:C6 = min(greparray(C ...

  4. Sqlite多线程相关整理

    Sqlite多线程相关整理 Sqlite With MultiThreads 什么是线程安全? 当多个线程访问某个方法时,不管你通过怎样的调用方式.或者说这些线程如何交替地执行,我们在主程序中不需要去 ...

  5. ThinkPHP角色控制时的错误

    1.Table 'think.think_user' doesn't exist  等的原因是因为'DB_PREFIX' => 'think_', // 数据库表前缀没有配置好,在使用角色控制时 ...

  6. XAMPP的安装及使用教程

    https://blog.csdn.net/qq_36595013/article/details/80373597#3%E9%85%8D%E7%BD%AEapache

  7. csp-s模拟测试90

    csp-s模拟测试90 考场发明$Spfa$祭. $T1$按照题意模拟,然后我就发现我死了.一气之下删掉了$priority$,拍了几下发现贼jb快而且还是对的就开心地交了.$T2$的差分状态定义很棒 ...

  8. VI/VIM 无法使用系统剪贴板(clipboard)

    来自: http://www.bubuko.com/infodetail-469867.html vim 系统剪贴板 "+y 复制到系统剪切板 "+p 把系统粘贴板里的内容粘贴到v ...

  9. MybatisPlus联合分页查询

    跟单表分页查询差不多 1.编写查询语句 public interface QuestionMapper extends BaseMapper<Question> { @Select(&qu ...

  10. 初识OpenCV-Python - 008: 形态转换

    本节学习了图片的形态转换,即利用函数和图像的前景色和背景色去侵蚀或者扩张图像图形. import cv2import numpy as npfrom matplotlib import pyplot ...