SpringBoot结合Redis配置工具类实现动态切换库

我使用的版本是SpringBoot 2.6.4

可以实现注入不同的库连接或是动态切换库

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>

    </parent>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
spring:
  redis:
    # open自定义的,使用aop切面控制
    open: false  # 是否开启redis缓存  true开启   false关闭
    database: 0
    host: 127.0.0.1
    password: 123456
    # history 自定义,切换库索引
    history: 1 #历史数据使用的库
    port: 6379
    timeout: 6000ms  # 连接超时时长(毫秒)
    jedis:
      pool:
        max-active: 1000  # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1ms      # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 10      # 连接池中的最大空闲连接
        min-idle: 5       # 连接池中的最小空闲连接

配置类 , 默认0号库使用@Autowired注入,自定义库使用@Resource(name = “history”)注入
动态切库有个问题就是一旦切库 后面的数据就会一直保存在切换的库里面,比如实时数据需要保存在1号库,历史数据需要保存在2号库,切库后 实时的就会存历史里面、下面这种配置,想用哪个库就注入哪个库,不存在切库问题

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
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;

import java.time.Duration;

/**
 * Redis配置
 */
@Configuration
public class RedisConfig {
    @Autowired
    private RedisConnectionFactory factory;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private Integer port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.history}")
    private Integer history;

    /**
     * 实时数据库 配置 默认0号库
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 解决value不能转成string chens 2022-06-08
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        template.setConnectionFactory(factory);
        return template;
    }

    /**
     * redis历史数据库 配置  根据yml配置库
     */
    @Bean("history")
    public RedisTemplate<String, Object> redisTemplatetwo() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 解决value不能转成string 
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        // 建立连接,设置库索引
        redisStandaloneConfiguration.setDatabase(history);
        redisStandaloneConfiguration.setHostName(host);
        redisStandaloneConfiguration.setPort(port);
        redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
        LettuceConnectionFactory factory = new LettuceConnectionFactory(redisStandaloneConfiguration, LettuceClientConfiguration.builder()
                // 超时时间
                .commandTimeout(Duration.ofMinutes(30)).build());
        factory.afterPropertiesSet();
        template.setConnectionFactory(factory);
        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();
    }
}

工具类,setDbIndex()动态切换库,方法调用完成应切回默认库

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @author chens
 */
@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Resource(name = "history")
    private RedisTemplate<String, Object> historyTemplate;
    @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;
    // 默认数据库
    private static Integer database = 0;
    /**
     * 默认过期时长,单位:秒
     */
    public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
    /**
     * 不设置过期时长
     */
    public final static long NOT_EXPIRE = -1;
    private final static Gson gson = new Gson();

    public void set(String key, Object value, long expire) {
        valueOperations.set(key, toJson(value));
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    public void set(Integer index, String key, Object value, long expire) {
        setDbIndex(index);
        valueOperations.set(key, toJson(value));
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    public void set(String key, Object value) {
        set(key, value, DEFAULT_EXPIRE);
    }

    public void set(Integer index, String key, Object value) {
        setDbIndex(index);
        set(key, value, DEFAULT_EXPIRE);
    }

    public <T> T get(String key, Class<T> clazz, long expire) {
        String value = valueOperations.get(key);
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value == null ? null : fromJson(value, clazz);
    }

    public <T> T get(Integer index, String key, Class<T> clazz, long expire) {
        setDbIndex(index);
        String value = valueOperations.get(key);
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value == null ? null : fromJson(value, clazz);
    }

    // 获取实时数据集合 chens
    public <T> List<T> getList(List<String> keys, Class<T> clazz) {
        List<T> list = new LinkedList<>();
        if (keys.size() < 1) return list;
        for (String key : keys) {
            T t = get(key, clazz, NOT_EXPIRE);
            if (t != null) {
                list.add(t);
            }
        }
        //keys.forEach(i -> list.add(get(i, clazz, NOT_EXPIRE)));
        return list;
    }

    public <T> T get(String key, Class<T> clazz) {
        return get(key, clazz, NOT_EXPIRE);
    }

    public <T> T get(Integer index, String key, Class<T> clazz) {
        setDbIndex(index);
        return get(key, clazz, NOT_EXPIRE);
    }

    public String get(String key, long expire) {
        String value = valueOperations.get(key);
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value;
    }

    public String get(Integer index, String key, long expire) {
        setDbIndex(index);
        String value = valueOperations.get(key);
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value;
    }

    public String get(String key) {
        return get(key, NOT_EXPIRE);
    }

    public String get(Integer index, String key) {
        setDbIndex(index);
        return get(key, NOT_EXPIRE);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public void delete(Integer index, String key) {
        setDbIndex(index);
        redisTemplate.delete(key);
    }

    /**
     * Object转成JSON数据
     */
    private String toJson(Object object) {
        if (object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String) {
            return String.valueOf(object);
        }
        return gson.toJson(object);
    }

    /**
     * JSON数据,转成Object
     */
    private <T> T fromJson(String json, Class<T> clazz) {
        //T t = JSONObject.parseObject(json, clazz);

        return gson.fromJson(json, clazz);
    }

    /**
     * 设置数据库索引
     * chens
     *
     * @param dbIndex 数据库索引
     */
    private void setDbIndex(Integer dbIndex) {
        // 边界判断
        if (dbIndex == null || dbIndex > 15 || dbIndex < 0) {
            dbIndex = database;
        }
        LettuceConnectionFactory redisConnectionFactory = (LettuceConnectionFactory) redisTemplate
                .getConnectionFactory();
        if (redisConnectionFactory == null) {
            return;
        }
        redisConnectionFactory.setDatabase(dbIndex);
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 属性设置后
        redisConnectionFactory.afterPropertiesSet();
        // 重置连接
        redisConnectionFactory.resetConnection();
    }

}

到此这篇关于SpringBoot结合Redis配置工具类实现动态切换库的文章就介绍到这了,更多相关SpringBoot Redis动态切换库内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Springboot基础之RedisUtils工具类

    SpringBoot整合Redis 引入Redis依赖 <!-- redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 设置Redis的Template RedisConfig.java package cn

  • SpringBoot 整合Redis 数据库的方法

    Redis简介 Redis(官网: https://redis.io )是一个基于内存的日志型可持久化的缓存数据库,保存形式为key-value格式,Redis完全免费开源,它使用ANSI C语言编写.与其他的key - value缓存产品一样,Redis具有以下三个特点. • Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用: • Redis不仅支持简单的key-value类型数据,同时还提供字符串.链表.集合.有序集合和哈希等数据结构的存储: • R

  • SpringBoot集成Redis数据库,实现缓存管理

    目录 一.Redis简介 二.Spring2.0集成Redis 1.核心依赖 2.配置文件 3.简单测试案例 4.自定义序列化配置 5.序列化测试 三.源代码地址 一.Redis简介 Spring Boot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis, MongoDB, Elasticsearch.这些案例整理好后,陆续都会上传Git. SpringBoot2 版本,支持的组件越来越丰富,对Redis的支持不仅仅是扩展

  • springboot 如何使用jedis连接Redis数据库

    springboot 使用jedis连接Redis数据库 1. 在 pom.xml 配置文件中添加依赖 <!-- redis 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- jedis 依赖

  • SpringBoot整合Redis及Redis工具类撰写实例

    目录 一.Maven依赖 二.application.properties中加入redis相关配置 三.写一个redis配置类 四.写一个Redis工具类 五.小结 SpringBoot整合Redis的博客很多,但是很多都不是我想要的结果.因为我只需要整合完成后,可以操作Redis就可以了,并不需要配合缓存相关的注解使用(如@Cacheable).看了很多博客后,我成功的整合了,并写了个Redis操作工具类.特意在此记录一下,方便后续查阅. 一.Maven依赖 (1)本文所采用的SpringBo

  • SpringBoot结合Redis配置工具类实现动态切换库

    我使用的版本是SpringBoot 2.6.4 可以实现注入不同的库连接或是动态切换库 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.4</version> </parent> <dependency> <

  • SpringBoot集成Kafka 配置工具类的详细代码

    目录 1.单播模式,只有一个消费者组 2.广播模式,多个消费者组 spring-kafka 是基于 java版的 kafka client与spring的集成,提供了 KafkaTemplate,封装了各种方法,方便操作,它封装了apache的kafka-client,不需要再导入client依赖 <!-- kafka --> <dependency> <groupId>org.springframework.kafka</groupId> <arti

  • spring boot结合Redis实现工具类的方法示例

    自己整理了 spring boot 结合 Redis 的工具类 引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 加入配置 # Redis数据库索引(默认为0) spring.redis.database=0 # Redis

  • springboot封装JsonUtil,CookieUtil工具类代码实例

    这篇文章主要介绍了springboot封装JsonUtil,CookieUtil工具类过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 JsonUtil public class JsonUtil { private static ObjectMapper objectMapper = new ObjectMapper(); public static String objectToString(Object object) throws

  • SpringBoot为啥不用配置启动类的实现

    前言 在学习SparkJava.Vert.x等轻量级Web框架的时候,都遇到过打包问题,这两个框架打包的时候都需要添加额外的Maven配置,并指定启动类才能得到可执行的JAR包: 而springboot项目,似乎都不需要额外的配置,直接package就可以得到可执行的JAR包,这是怎么回事呢? Vert.x要怎么配? 我们先来看看,Vert.x打包做哪些配置 1)引入maven-shade-plugin插件 2)在插件中指定在package完成时触发shade操作 3)指定启动类 <plugin

  • 使用Spring静态注入实现读取配置工具类新方式

    目录 Spring静态注入实现读取配置工具类 核心代码 拓展 Spring两种方式注入到静态工具类里 方式1 方式2:zs Spring静态注入实现读取配置工具类 Spring静态注入的核心首先是需要是一个Bean,才可以从Spring上下文中注入Bean,下例中environment是需要Autowired注入的Bean,之所以选择Environment是因为它有Spring已经加载好的属性配置,直接拿来用比从文件中读取更优雅,从文件中读取需要面临jar包外部配置问题,暂时未找到较好解决办法.

  • Springboot内置的工具类之CollectionUtils示例讲解

    前言 实际业务开发中,集合的判断和操作也是经常用到的,Spring也针对集合的判断和操作封装了一些方法,但是最令我惊讶的是,我在梳理这些内容的过程中发现了一些有趣的现象,我的第一反应是不敢相信,再想一想,没错,我是对的.所以强烈建议大家可以认真看完这篇文章,这一篇绝对有价值,因为有趣的是我我竟然发现了Spring的两个bug. org.springframework.util.CollectionUtils 集合的判断 boolean hasUniqueObject(Collection col

  • springboot实现后台上传图片(工具类)

    本文实例为大家分享了springboot实现后台上传图片的具体代码,供大家参考,具体内容如下 1.先配置启动类 继承WebMvcConfigurer 重写方法 @SpringBootApplication //@MapperScan("com.example.demo.Mapper") public class DemoApplication implements WebMvcConfigurer { public static void main(String[] args) { S

  • Springboot如何通过自定义工具类获取bean

    目录 Springboot 自定义工具类获取bean 在工具类注入bean的三种方式 1. 需求/目的 2.使用环境 3.方法一:获取ApplicationContext上下文 4.方法二:将工具类的对象也添加为bean 5.方法三:在spring Boot 启动时创建工具类自身的静态对象 Springboot 自定义工具类获取bean /** * Created with IntelliJ IDEA. * * @Auther: zp * @Date: 2021/03/26/13:32 * @D

随机推荐