栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot-Redis配置工具类,动态切换库

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot-Redis配置工具类,动态切换库

我使用的版本是SpringBoot 2.6.4
可以实现注入不同的库连接或是动态切换库

    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.4
        
    
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
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;


@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;

    
    @Bean
    public RedisTemplate redisTemplate() {
        RedisTemplate 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;
    }

    
    @Bean("history")
    public RedisTemplate redisTemplatetwo() {
        RedisTemplate 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 hashOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForHash();
    }

    @Bean
    public ValueOperations valueOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForValue();
    }

    @Bean
    public ListOperations listOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForList();
    }

    @Bean
    public SetOperations setOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForSet();
    }

    @Bean
    public ZSetOperations zSetOperations(RedisTemplate 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;


@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource(name = "history")
    private RedisTemplate historyTemplate;
    @Autowired
    private ValueOperations valueOperations;
    @Autowired
    private HashOperations hashOperations;
    @Autowired
    private ListOperations listOperations;
    @Autowired
    private SetOperations setOperations;
    @Autowired
    private ZSetOperations 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 get(String key, Class 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 get(Integer index, String key, Class 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  List getList(List keys, Class clazz) {
        List 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 get(String key, Class clazz) {
        return get(key, clazz, NOT_EXPIRE);
    }

    public  T get(Integer index, String key, Class 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);
    }

    
    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);
    }

    
    private  T fromJson(String json, Class clazz) {
        //T t = JSONObject.parseObject(json, clazz);

        return gson.fromJson(json, clazz);
    }

    
    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();
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1005866.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号