springboot 2 集成 redis 缓存 序列化
springboot 缓存
为了实现是在数据中查询数据还是在缓存中查询数据,在application.yml 中将mybatis 对应的mapper 包日志设置为debug 。
- spring:
- datasource:
- username: root
- password: rootpassword
- url: jdbc:mysql://localhost:3306/springboot
- driver-class-name: com.mysql.jdbc.Driver
- debug: true
- logging:
- level:
- com:
- springbootmybatis:
- mapper: debug
然后在springboot的主类上添加 @EnableCaching 启动缓存。
然后在service 类中的方法上添加上缓存注解。
- @Cacheable(value = "user")
- public User selectUserById(Integer id) {
- User user = userMapper.selectUserById(id);
- return user;
- }
@Cacheable
默认的是将传入参数(id)作为缓存的 key ,方法的返回值作为 value 存入缓存中 。
在方法 selectUserById(Integer id ) 执行之前 先去根据 key 去缓存中查询是否有该 key 的数据,如果有,则直接在缓存中查询数据,然后返回,不再执行 selectUserById 方法,如果没有在缓存中查到该 key 的数据,才回去执行 selectUserById 方法。
@CachePut
- @CachePut(value = "user")
- public User updateUser(User user) {
- userMapper.updateUser(user);
- return user;
- }
默认的是将传入参数(id)作为缓存的 key ,@CachePut 在方法执行之后执行,将方法返回的结果写入缓存,
从缓存中查询到的仍然是旧的缓存数据,需要在 @CachePut(value = "user",key = "#result.id") 或者@CachePut(value = "user",key = "#user.id") 只要在 key 设置为 user 的 id ,然后根据id 去查询,就能从缓存中获取修改后的数据。
@CacheEvict
- @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。
- @Target({ElementType.METHOD, ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Inherited
- @Documented
- public @interface Caching {
- Cacheable[] cacheable() default {};
- CachePut[] put() default {};
- CacheEvict[] evict() default {};
- }
- @Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),
- @CacheEvict(value = "cache3", allEntries = true) })
- public List<User> selectUser() {
- List<User> users = userMapper.selectUser();
- return users;
- }
使用redis 缓存:
导入对应的jar:使用fastjson 来序列化value
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- </dependency>
- <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.2.47</version>
- </dependency>
在application.yml 添加配置:
- spring:
- redis:
- host: #redis 安装的IP,其他的可以不用配置,默认的就可以满足测试需要
在springboot 1 中配置redis
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.serializer.SerializerFeature;
- import org.springframework.cache.CacheManager;
- import org.springframework.cache.annotation.CachingConfigurerSupport;
- import org.springframework.cache.annotation.EnableCaching;
- import org.springframework.cache.interceptor.KeyGenerator;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.redis.cache.RedisCacheManager;
- 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.RedisSerializer;
- import org.springframework.data.redis.serializer.SerializationException;
- import java.lang.reflect.Method;
- import java.nio.charset.Charset;
- @EnableCaching
- @Configuration
- public class RedisConfig extends CachingConfigurerSupport {
- @Bean
- public KeyGenerator wiselyKeyGenerator() {
- return new KeyGenerator() {
- @Override
- public Object generate(Object target, Method method, Object... params) {
- StringBuilder sb = new StringBuilder();
- sb.append(target.getClass().getName());
- sb.append(method.getName());
- for (Object obj : params) {
- sb.append(obj.toString());
- }
- return sb.toString();
- }
- };
- }
- @Bean
- public CacheManager cacheManager(
- @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
- return new RedisCacheManager(redisTemplate);
- }
- @Bean
- public RedisTemplate<String, String> redisTemplate(
- RedisConnectionFactory factory) {
- StringRedisTemplate template = new StringRedisTemplate(factory);
- FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
- template.setValueSerializer(serializer);
- template.afterPropertiesSet();
- return template;
- }
- private static class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
- private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
- private Class<T> clazz;
- public FastJsonRedisSerializer(Class<T> clazz) {
- this.clazz = clazz;
- }
- @Override
- public byte[] serialize(T t) throws SerializationException {
- if (t == null) {
- return new byte[0];
- }
- return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
- }
- @Override
- public T deserialize(byte[] bytes) throws SerializationException {
- if (bytes == null || bytes.length <= 0) {
- return null;
- }
- String str = new String(bytes, DEFAULT_CHARSET);
- return (T) JSON.parseObject(str, clazz);
- }
- }
- }
然后在测试类上加上缓存的注解就可以在redis中查看已经序列化成json格式的数据。
在springboot2 中配置redis
其他的配置不用动,需要修改RedisConfig.java 因为springboot2 中new RedisCacheManager(redisTemplate);被遗弃了
- @Bean
- public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
- //初始化一个RedisCacheWriter
- RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
- //设置CacheManager的值序列化方式为 fastJsonRedisSerializer,但其实RedisCacheConfiguration默认使用StringRedisSerializer序列化key,
- ClassLoader loader = this.getClass().getClassLoader();
- FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(loader.getClass());
- RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer);
- RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
- RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
- return cacheManager;
- }
这样设置就可以正常使用了
springboot 2 集成 redis 缓存 序列化的更多相关文章
- 在springboot中使用redis缓存,将缓存序列化为json格式的数据
背景 在springboot中使用redis缓存结合spring缓存注解,当缓存成功后使用gui界面查看redis中的数据 原因 springboot缓存默认的序列化是jdk提供的 Serializa ...
- springboot集成redis缓存
1.pom.xml增加redis缓存起步依赖(spring-boot-starter-parent包含许多starter版本) <dependency> <groupId>or ...
- SpringBoot缓存管理(三) 自定义Redis缓存序列化机制
前言 在上一篇文章中,我们完成了SpringBoot整合Redis进行数据缓存管理的工作,但缓存管理的实体类数据使用的是JDK序列化方式(如下图所示),不便于使用可视化管理工具进行查看和管理. 接下来 ...
- 搞懂分布式技术14:Spring Boot使用注解集成Redis缓存
本文内容参考网络,侵删 本系列文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查看 https://github.com/h2pl/Java-Tutor ...
- 集成Redis缓存
一.简介 1.场景 由于首页数据变化不是很频繁,而且首页访问量相对较大,所以我们有必要把首页数据缓存到redis中,减少数据库压力和提高访问速度. 2.RedisTemplate Jedis是Redi ...
- Redis缓存 序列化对象存储乱码问题
使用Redis缓存对象会出现下图现象: 键值对都是乱码形式. 解决以上问题: 如果是xml配置的 我们直接注入官方给定的keySerializer,valueSerializer,hashKeySer ...
- SpringBoot整合集成redis
Redis安装:https://www.cnblogs.com/zwcry/p/9505949.html 1.pom.xml <project xmlns="http://maven. ...
- Spring Boot2(三):使用Spring Boot2集成Redis缓存
前言 前面一节总结了SpringBoot实现Mybatis的缓存机制,但是实际项目中很少用到Mybatis的二级缓存机制,反而用到比较多的是第三方缓存Redis. Redis是一个使用ANSI C编写 ...
- 完整SpringBoot Cache整合redis缓存(二)
缓存注解概念 名称 解释 Cache 缓存接口,定义缓存操作.实现有:RedisCache.EhCacheCache.ConcurrentMapCache等 CacheManager 缓存管理器,管理 ...
随机推荐
- exe4j 打包(多个jar打包)
一,自行下载exe4j 注册码: 用户名和公司名可随便填A-XVK258563F-1p4lv7mg7savA-XVK209982F-1y0i3h4ywx2h1A-XVK267351F-dpurrhny ...
- python中的OrderedDict
该类型存放顺序和添加顺序一致,比如逐个赋值,但和dict直接转化过去的顺序不一定一样. d1 = collections.OrderedDict() d1['b'] = 'B'd1['a'] = 'A ...
- 帆软报表PC端实施报表心得体会
1.报表制作完成后,预览时自动显示查询内容,在控件处设置: 2.求一列数据的最小值(除去0),并对最小值字体加粗标绿,需要对对应单元格设置条件属性,并插入公式:C6 = min(greparray(C ...
- Sqlite多线程相关整理
Sqlite多线程相关整理 Sqlite With MultiThreads 什么是线程安全? 当多个线程访问某个方法时,不管你通过怎样的调用方式.或者说这些线程如何交替地执行,我们在主程序中不需要去 ...
- ThinkPHP角色控制时的错误
1.Table 'think.think_user' doesn't exist 等的原因是因为'DB_PREFIX' => 'think_', // 数据库表前缀没有配置好,在使用角色控制时 ...
- XAMPP的安装及使用教程
https://blog.csdn.net/qq_36595013/article/details/80373597#3%E9%85%8D%E7%BD%AEapache
- csp-s模拟测试90
csp-s模拟测试90 考场发明$Spfa$祭. $T1$按照题意模拟,然后我就发现我死了.一气之下删掉了$priority$,拍了几下发现贼jb快而且还是对的就开心地交了.$T2$的差分状态定义很棒 ...
- VI/VIM 无法使用系统剪贴板(clipboard)
来自: http://www.bubuko.com/infodetail-469867.html vim 系统剪贴板 "+y 复制到系统剪切板 "+p 把系统粘贴板里的内容粘贴到v ...
- MybatisPlus联合分页查询
跟单表分页查询差不多 1.编写查询语句 public interface QuestionMapper extends BaseMapper<Question> { @Select(&qu ...
- 初识OpenCV-Python - 008: 形态转换
本节学习了图片的形态转换,即利用函数和图像的前景色和背景色去侵蚀或者扩张图像图形. import cv2import numpy as npfrom matplotlib import pyplot ...