Springboot 整合redis配置类和封装redis服务

Posted 洛阳泰山

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot 整合redis配置类和封装redis服务相关的知识,希望对你有一定的参考价值。

首先pom文件引入

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

然后 application.yml文件加入以下配置

spring
    redis:
        host: localhost
        port: 6379
        password: 666666
        timeout: 5000
        database: 0


redis配置类


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.tarzan.cms.common.constant.CoreConst;
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.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
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.StringRedisSerializer;

import java.time.Duration;

/**
 * Redis缓存时间、序列化、反序列化等配置
 *
 * @author tarzan liu
 * @since JDK1.8
 * @date 2021年5月11日
 */

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport 

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) 
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration
                .defaultCacheConfig()
                .entryTtl(Duration.ofDays(30))
                .computePrefixWith(CacheKeyPrefix.prefixed(CoreConst.TARZAN_REDIS_CMS_PREFIX))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()));
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(factory))
                .cacheDefaults(cacheConfiguration)
                .transactionAware()
                .build();
    


    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) 
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer());

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        redisTemplate.setKeySerializer(stringRedisSerializer);

        // hash的key也采用String的序列化方式
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        // hash的value序列化方式采用jackson
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    

    /**
     * 配置Jackson2JsonRedisSerializer序列化策略
     */
    @Bean
    public Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() 
        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();

        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;
    

redis封装服务类代码


import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author tarzan liu
 * @since JDK1.8
 * @date 2021年5月11日
 */
@Service
@AllArgsConstructor
public class RedisService 

    private final RedisTemplate<String, Object> redisTemplate;

    public <T> void set(String key, T value) 
        redisTemplate.opsForValue().set(key, value);
    

    public <T> void set(String key, T value, long expire, TimeUnit timeUnit) 
        redisTemplate.opsForValue().set(key, value, expire, timeUnit);
    

    @SuppressWarnings("unchecked")
    public <T> T get(String key) 
        Object o = redisTemplate.opsForValue().get(key);
        return Objects.isNull(o) ? null : (T) o;
    

    public boolean expire(String key, long expire) 
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    

    public void del(String key) 
        redisTemplate.opsForValue().getOperations().delete(key);
    

    public void delBatch(Set<String> keys) 
        redisTemplate.delete(keys);
    

    public void delBatch(String keyPrefix) 
        Set<String> keys = keySet(keyPrefix);
        if (CollectionUtils.isNotEmpty(keys)) 
            delBatch(keys);
        
    

    public <T> void setList(String key, List<T> list) 
        String value = JSON.toJSONString(list);
        set(key, value);
    

    public <T> void setList(String key, List<T> list, long expire, TimeUnit timeUnit) 
        String value = JSON.toJSONString(list);
        set(key, value, expire, timeUnit);
    

    public <T> List<T> getList(String key, Class<T> clz) 
        String json = get(key);
        if (json != null) 
            return JSON.parseArray(json, clz);
        
        return null;
    

    public boolean hasKey(String key) 
        return redisTemplate.hasKey(key);
    

    public long getExpire(String key) 
        return redisTemplate.getExpire(key);
    

    public Set<String> keySet(String keyPrefix) 
        return redisTemplate.keys(keyPrefix + '*');
    

以上是关于Springboot 整合redis配置类和封装redis服务的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 整合 Lettuce Redis

springboot整合mybatis,mongodb,redis

SpringBoot的整合(整合redis)

springboot整合jedis

redis(Springboot中封装整合redis,java程序如何操作redis的5种基本数据类型)

springboot2.x整合redis