springboot2 + redis 缓存项目实战

一、关键配置
pom.xml

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

<dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
</dependency>

二、application.properties配置

spring.redis.database = 0
spring.redis.host = localhost
spring.redis.port = 6379
spring.redis.password =
spring.redis.timeout=5000
spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0

三、代码

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.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.connection.lettuce.LettuceConnectionFactory;
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;


@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置连接工厂
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // 设置hash key 和 value 序列化
        template.setHashKeySerializer(redisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @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);
        // 配置序列化(解决乱码的问题)
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

四、RedisUtils工具类

import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void setDataBase( int num) {
        LettuceConnectionFactory  connectionFactory = (LettuceConnectionFactory ) redisTemplate.getConnectionFactory();
        if (connectionFactory != null && num != connectionFactory.getDatabase()) {
            connectionFactory.setDatabase(num);
            this.redisTemplate.setConnectionFactory(connectionFactory);
            // 必须先调用,实现初始化
            connectionFactory.afterPropertiesSet();
            connectionFactory.resetConnection();
        }
    }

    /**
     * @Title: expire
     * @Description: 指定缓存失效时间
     * @author w
     * @Param [db, key, time] 库,键,时间(秒)
     * @date 2021/4/18 21:18
     * @return boolean
     * @throws
     */
    public boolean expire(int db, String key,long time){
        try {
            if(time>0){
                setDataBase(db);
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Title: getExpire
     * @Description: 根据key 获取过期时间
     * @author w
     * @Param [db, key] 库,键 不能为null
     * @date 2021/4/18 21:19
     * @return long 时间(秒) 返回0代表为永久有效
     * @throws
     */
    public long getExpire(int db, String key){
        setDataBase(db);
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }

    /**
     * @Title: hasKey
     * @Description: 判断key是否存在
     * @author w
     * @Param [db, key] 库,键
     * @date 2021/4/18 21:19
     * @return boolean true:存在 false:不存在
     * @throws
     */
    public boolean hasKey(int db, String key){
        try {
            setDataBase(db);
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Title: del
     * @Description: 删除缓存
     * @author w
     * @Param [db, key] 库,键 可以传一个值 或多个
     * @date 2021/4/18 21:21
     * @return void
     * @throws
     */
    public void del(int db, String ... key){
        setDataBase(db);
        if(key!=null&&key.length>0){
            if(key.length==1){
                redisTemplate.delete(key[0]);
            }else{
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
            }
        }
    }

    //-----------------String操作---------------------
    /**
     * @Title: set
     * @Description: 添加缓存
     * @author w
     * @Param [db, key, value] 库,键,值
     * @date 2021/4/18 21:22
     * @return boolean true:成功 false:失败
     * @throws
     */
    public boolean set(int db, String key, Object value) {
        try {
            setDataBase(db);
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Title: get
     * @Description: 获取缓存
     * @author w
     * @Param [db, key] 库,键
     * @date 2021/4/18 21:23
     * @return java.lang.Object
     * @throws
     */
    public Object get(int db,String key) {
        setDataBase(db);
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * @Title: delete
     * @Description: 删除缓存
     * @author w
     * @Param [db, key] 库,键
     * @date 2021/4/18 21:24
     * @return void
     * @throws
     */
    public void delete(int db, String key) {
        setDataBase(db);
        redisTemplate.delete(key);
    }

    /**
     * @Title: set
     * @Description: 添加缓存,缓存设置有效期
     * @author w
     * @Param [db, key, value, time]
     * @date 2021/4/18 21:25
     * @return boolean
     * @throws
     */
    public boolean set(int db, String key,Object value,long time){
        try {
            if(time>0){
                setDataBase(db);
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            }else{
                set(db, key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值