springboot 2 集成 redis 缓存 序列化

摘要:
为了实现是在数据中还是在缓存中查询数据,spring引导缓存将与mybatis对应的映射程序包日志设置为application.yml中的debug。spring:数据源:用户名:root密码:root密码url:jdbc:mysql://localhost:3306/springbootdriver-类名:com.my
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 2 集成 redis 缓存 序列化》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇[PHP] 算法-根据前序和中序遍历结果重建二叉树的PHP实现测试用例下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Linux 里Buffer和Cache的定义及使用

Buffer 和 Cache 的介绍 查看内存使用情况 # 注意不同版本的free输出可能会有所不同 $ free total used free shared buff/cache available Mem: 8169348 263524 68753...

11.Redis详解(十一)------ 过期删除策略和内存淘汰策略

在介绍这篇文章之前,我们先来看如下几个问题: ①、如何设置Redis键的过期时间? ②、设置完一个键的过期时间后,到了这个时间,这个键还能获取到么?假如获取不到那这个键还占据着内存吗? ③、如何设置Redis的内存大小?当内存满了之后,Redis有哪些内存淘汰策略?我们又该如何选择? 如果上面的几个问题你都懂,那么下面的内容你就不用看了;如果你不是很懂,那...

Docker 快速搭建主从 + 哨兵监控

安装 Redis 执行命令 我的官方群点击此处。 docker pull redis 部署方案 启动三台机器,6379 容器作为主节点,其余作为从节点 开始准备工作   目录结构 ├── conf │ ├── redis_6379.conf │ ├── redis_6380.conf │ ├── redis_6381.conf │ ├─...

Protobuf 语言指南(proto3)

Protobuf 语言指南(proto3)Protocol Buffer是Google的语言中立的,平台中立的,可扩展机制的,用于序列化结构化数据 - 对比XML,但更小,更快,更简单。您可以定义数据的结构化,然后可以使用特殊生成的源代码轻松地在各种数据流中使用各种语言编写和读取结构化数据。 定义消息类型 先来看一个非常简单的例子。假设你想定义一个“搜索...

浏览器缓存知识小结及应用

浏览器缓存,也就是客户端缓存,既是网页性能优化里面静态资源相关优化的一大利器,也是无数web开发人员在工作过程不可避免的一大问题,所以在产品开发的时候我们总是想办法避免缓存产生,而在产品发布之时又在想策略管理缓存提升网页的访问速度。了解浏览器的缓存命中原理,是开发web应用的基础,本文着眼于此,学习浏览器缓存的相关知识,总结缓存避免和缓存管理的方法,结合具...

redis教程--phpredis

phpredis是php的一个扩展 <?php //连接本地的 Redis 服务 $redis = new Redis(); $redis->connect('127.0.0.1', 6379); echo "Connection to server sucessfully。"; //查看服务是否运行 echo "Server is runni...