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 缓存 序列化的更多相关文章

  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. Dubbo的服务请求失败怎么处理

    dubbo启动时默认有重试机制和超时机制. 超时机制的规则是如果在一定的时间内,provider没有返回,则认为本次调用失败, 重试机制在出现调用失败时,会再次调用.如果在配置的调用次数内都失败,则认 ...

  2. scala中Map集合的简单使用

    import scala.collection.mutable /** * Map集合的简单使用 */ object MapUse { def main(args: Array[String]): U ...

  3. Windows cd

    显示当前目录名或改变当前目录. CHDIR [/D] [drive:][path]CHDIR [..]CD [/D] [drive:][path]CD [..] ..   指定要改成父目录. 键入 C ...

  4. day24 模块

     Python之路,Day12 = Python基础12 模块 本质为py程序 分类: 内置模块 time time.time() ---> 当前时间的时间戳:浮点型 time.localtim ...

  5. (20)Oracle函数

    substr 截取字段 substr(字符串,截取开始位置,截取长度) substr(str,n,m) 第二,三参数可以省略, 第二个参数为负数时表示从倒数第n位开始向后截取m个 round(str, ...

  6. 引用第三方 chalk 模块

    第三方模块没有默认引用到我们的电脑中,我们要进行下载 chalk 这个包是为了使输出不再单调,添加文字背景什么的,改变字体颜色什么的, npm install chalk //只需要写文件包名,不需要 ...

  7. JS之缓冲动画

    原素材 main.html <!DOCTYPE html> <html lang="en"> <head> <link href=&quo ...

  8. 简单搭建dubbo

    为什么要用dubbo? 当网站规模达到了一定的量级的时候,普通的MVC框架已经不能满足我们的需求,于是分布式的服务框架和流动式的架构就凸显出来了.     单一应用架构 当网站流量很小时,只需一个应用 ...

  9. linux常用软连接使用ln -s

    [软连接]另外一种连接称之为符号连接(Symbolic Link),也叫软连接.软链接文件有类似于Windows的快捷方式.它实际上是一个特殊的文件.在符号连接中,文件实际上是一个文本文件,其中包含的 ...

  10. SecureCRT 64位 破解版和安装,以及解决乱码问题

    链接:https://pan.baidu.com/s/1q1DEmohK7ISNJ7UbJkN3jw 提取码:yea3 复制这段内容后打开百度网盘手机App,操作更方便哦 securecrt 破解版是 ...