springboot2.3.2.RELEASE集成redis,动态切换数据库

springboot集成redis

1、springboot集成redis

1、依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

2、配置

 spring:
   redis:
     host: 192.168.0.100
     port: 16379
     password: ba2020
     database: 0

3、自定义bean

 package com.baian.yeyingcloudredis.config;
 
 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 org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.data.redis.connection.RedisConnectionFactory;
 import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
 import org.springframework.data.redis.core.*;
 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
 import org.springframework.data.redis.serializer.StringRedisSerializer;
 
 /**
  * @author lin
  * @version 1.0
  * @date 2020-05-12 8:48
  * @Description TODO
  */
 @Configuration
 public class RedisConfig {
 
     // 自己定义了一个 RedisTemplate
     @Bean
     public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) {
         // 我们为了自己开发方便,一般直接使用 <String, Object>
         RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
         //关闭共享连接
         factory.setShareNativeConnection(false);
         template.setConnectionFactory(factory);
         // Json序列化配置
         Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
         ObjectMapper om = new ObjectMapper();
         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
         // 会出现警告enableDefaultTyping
 //       om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
         // enableDefaultTyping()过期 使用以下的 spring boot 2.x 以后使用
         om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
         jackson2JsonRedisSerializer.setObjectMapper(om);
         // String 的序列化
         StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
         // key采用String的序列化方式
         template.setKeySerializer(stringRedisSerializer);
         // hash的key也采用String的序列化方式
         template.setHashKeySerializer(stringRedisSerializer);
         // value序列化方式采用jackson
         template.setValueSerializer(jackson2JsonRedisSerializer);
         // hash的value序列化方式采用jackson
         template.setHashValueSerializer(jackson2JsonRedisSerializer);
         template.afterPropertiesSet();
         return template;
    }
 
     @Bean
     public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
         return redisTemplate.opsForHash();
    }
 
     @Bean
     public ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) {
         return redisTemplate.opsForValue();
    }
 
     @Bean
     public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
         return redisTemplate.opsForList();
    }
 
     @Bean
     public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
         return redisTemplate.opsForSet();
    }
 
     @Bean
     public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
         return redisTemplate.opsForZSet();
    }
 
 }
 

4、使用、判断key是否存在

 
     @Autowired
     private RedisTemplate<String, Object> redisTemplate;
 
     /**
      * 判断key是否存在
      *
      * @param key 键
      * @return true 存在 false不存在
      */
     public boolean hasKey(String key, Integer dbIndex) {
         setDbIndex(dbIndex);
         try {
             return redisTemplate.hasKey(key);
        } catch (Exception e) {
             e.printStackTrace();
             return false;
        }
    }

每个人可以自定义一个通用方法

图片

2、动态切换数据库

1、使用

 /**
  * Redis工具类
  * <p>
  * 封装了对象和字符串的存,取,删除,设置过期时间操作. 所有操作可以指定数据库索引. 存,取可以设置过期时间. 没有设置默认过期时间,存值时尽量设置过期时间
  *
  * @author chunhui.tan
  * @version 创建时间:2018年10月8日 下午3:31:00
  */
 @Component
 public class RedisUtils {
     @Autowired
     private RedisTemplate<String, Object> redisTemplate;
     @Autowired
     private ValueOperations<String, String> valueOperations;
     @Autowired
     private HashOperations<String, String, Object> hashOperations;
     @Autowired
     private ListOperations<String, Object> listOperations;
     @Autowired
     private SetOperations<String, Object> setOperations;
     @Autowired
     private ZSetOperations<String, Object> zSetOperations;
     /** 默认过期时长,单位:秒 */
     //public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
     /**
      * 不设置过期时长
      */
     public final static long NOT_EXPIRE = -1;
     private final static Gson gson = new Gson();
 
     public RedisTemplate<String, Object> getRedisTemplate() {
         return redisTemplate;
    }
 
     /**
      * 判断key是否存在
      *
      * @param key 键
      * @return true 存在 false不存在
      */
     public boolean hasKey(String key, Integer dbIndex) {
         setDbIndex(dbIndex);
         try {
             return redisTemplate.hasKey(key);
        } catch (Exception e) {
             e.printStackTrace();
             return false;
        }
    }
 
     /**
      * 插入值-对象,指定数据库索引,指定过期时间
      *
      * @param key     键
      * @param value   值
      * @param dbIndex 数据库索引 范围 0-15 默认0
      * @param expire 过期时间 单位:秒
      */
     public void set(String key, Object value, Integer dbIndex, long expire) {
         // 选择数据库
         setDbIndex(dbIndex);
         valueOperations.set(key, toJson(value));
         if (expire != NOT_EXPIRE) {
             redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }
 }

2、自定义切库方法

     /**
      * 设置数据库索引
      *
      * @param dbIndex
      */
     private void setDbIndex(Integer dbIndex) {
         if (dbIndex == null || dbIndex > 15 || dbIndex < 0) {
             dbIndex = 0;
        }
         LettuceConnectionFactory redisConnectionFactory = (LettuceConnectionFactory) redisTemplate
                .getConnectionFactory();
         if (redisConnectionFactory == null) {
             return;
        }
         redisConnectionFactory.setDatabase(dbIndex);
         redisTemplate.setConnectionFactory(redisConnectionFactory);
         redisConnectionFactory.afterPropertiesSet();
         redisConnectionFactory.resetConnection();
    }

3、测试

     @Resource
     RedisUtils redisUtils;
 
     @Test
     void contextLoads() {
         int dbIndex = 14;
         String key = "ttttt";
         final String s1 = redisUtils.get(key, dbIndex);
         System.out.println("s1 = " + s1);
         redisUtils.set(key, "test", 14, 20);
         System.out.println(redisUtils.get(key, dbIndex));
         redisUtils.set(key + "1", key, 4, 60 * 3);
    }

结果:

s1 = nulltest

图片

源码: https://gitee.com/naimaohome/frames.git

公众号:

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

航迹者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值