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 缓存管理器,管理 ...
随机推荐
- 【bug】vue同一组件使用
vue使用同一个组件渲染,进行切换过程中会存在数据保存的情况. 比如路由切换,进行渲染的页面来自同一个组件,这个时候,要在监听路由的时候,将数据重新初始化
- Java 基础 - instanceof关键字
instanceof 父类子类 结论: 子类 instanceof 父类 == true 父类 instanceof 子类 == false public class Test { public st ...
- ajax跨域获取网站json数据
由于自己的公司的项目需要调用视频地址 1:当为链接时:直接在播放器用数据库查找的地址 2:当为外部链接时:直接用window.location.href('数据库查找的地址') 3:当为H5链接时:使 ...
- 有道云笔记新功能发现——有道云笔记剪报,完美解决不开会员保存csdn博客到本地的问题。
怎么用 方法一:谷歌插件 方法二:http://note.youdao.com/web-clipper-chrome.html 添加到书签 功能: 能够把网页浏览的内容保存到有道云笔记 解决了自己的难 ...
- PAT甲级——A1117 Eddington Number【25】
British astronomer Eddington liked to ride a bike. It is said that in order to show off his skill, h ...
- Spring 泛型依赖注入(3)
BaseService<T>:有RoleService和UserService两的子类 BaseRepepositry<T>:有UserRepository和RoleRepos ...
- WPF drag过程中显示ToolTip.
原文:WPF drag过程中显示ToolTip. 在drag/drop过程中,我们在判断出over的元素上是否可以接受drag的东西之后,通常是通过鼠标的样式简单告诉用户这个元素不接受现在drag的内 ...
- mysql简单的操作
启动数据库服务 net start mysql 停止数据库服务 net stop mysql 退出数据库 exit 保存操作及结果 将在命令行窗口中 ...
- 【颓废篇】easyx--2048
整天待在机房是不是,一直保持学术的态度就比较的难啊~ 所以本蒟蒻就在学术之余学了些奇技淫巧,然后就写了一些奇奇怪怪的程序啊,比如让我们小组dalao们都颓得不亦乐乎的2048~~ 当然,2048的实现 ...
- 那些使用VSCode写Python踩过的坑(Anaconda配置)
1. 如何在vscode上配置的配置方法请务必一定要直接参考官方文档Getting Started with Python in VS Code,不要去看什么杂七杂八的blog,要么过时要么不准确要么 ...