码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot2.x整合Redis缓存自定义序列化

时间:2019-06-26 16:28:27      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:ttl   就是   autowired   data   ram   null   rabbit   tab   gnu   

一、导入Jar包

<!--rabbitmq-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.49</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>   

 

二、配置文件

package com.liangjian.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * reids配置类
 */

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);

        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        // 设置value的序列化规则和 key的序列化规则
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 配置序列化(解决乱码的问题),过期时间30秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(1800000))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

 

 

三、application.yml 添加以下配置

spring:
## Redis 配置
## Redis数据库索引(默认为0)
  redis:
    database: 0
  ## Redis服务器地址
    host: 127.0.0.1
  ## Redis服务器连接端口
    port: 6379
  ## Redis服务器连接密码(默认为空)
    password:
  ## 连接超时时间(毫秒)
   # timeout: 1800000
  ## 连接池最大连接数(使用负值表示没有限制)
    jedis:
      pool:
        max-active: 8
  ## 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1
  ## 连接池中的最大空闲连接
        max-idle: 8
  ## 连接池中的最小空闲连接
        min-idle: 0

 

四、在方法上使用@Cacheable(value = "MyRedis"/*上一级包名*/, key = "redis")进行添加缓存

(方法必须有返回值,返回值就是存入Redis的数据)

 

五、删除缓存:

  方法一:删除指定Key

 

@Caching(evict = {
@CacheEvict(value = "MyRedis",key=“redis”)
})

方法二:删除指定文件下(value值)所有的Key

 

@Caching(evict = {
@CacheEvict(value = "MyRedis",allEntries=true/*表示删除MyRedis文件下所有的缓存*/)
})



六、有时候通过注解方式无法满足需求,可以使用RedisTemplate对象进行存储,关键代码如下:
 //获取redisTemplate对象
 @Autowired
 private RedisTemplate redisTemplate;

//新增 参数分别为:Key名、存入的数据、过期时间、过期时间的类型(TimeUnit.SECONDS 是以秒计算)
redisTemplate.opsForValue().set(“token”,admins,1800, TimeUnit.SECONDS);

//获取 参数:Key值
redisTemplate.opsForValue().get(“token”)

//删除 参数:Key值
redisTemplate.delete("token");


 




SpringBoot2.x整合Redis缓存自定义序列化

标签:ttl   就是   autowired   data   ram   null   rabbit   tab   gnu   

原文地址:https://www.cnblogs.com/castlechen/p/11090505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!