Java中适配Redis单机和集群模式

/**
* 根据配置创建Redis连接工厂
* 支持单机和集群模式
*
*/

application.properties配置文件

Redis配置类:

package com.t6bi.carrier.app.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.*;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import top.topsoft.support.util.any.EncryptionKit;
import top.topsoft.support.util.any.ObjectKit;

import java.util.Arrays;
import java.util.List;

/**
 * Redis配置类
 * 用于配置Redis连接工厂和Redis模板
 */
@Configuration
public class RedisConfig {

    private final Environment environment;

    /**
     * 构造函数,注入环境变量对象
     * 用于获取配置信息
     * 
     * @param environment 环境变量对象
     */
    public RedisConfig(Environment environment) {
        this.environment = environment;
    }

    /**
     * 根据配置创建Redis连接工厂
     * 支持单机和集群模式
     * 
     * @return RedisConnectionFactory 连接工厂实例
     */
    @Bean(name = "myRedisConnectionFactory")
    public RedisConnectionFactory myLettuceConnectionFactory() {
        String mode = environment.getProperty("spring.redis.mode", "single");
        if ("cluster".equals(mode)) {
            return createClusterConnectionFactory();
        } else {
            return createSingleConnectionFactory();
        }
    }

    /**
     * 创建单机模式的Redis连接工厂
     * 
     * @return LettuceConnectionFactory 单机模式连接工厂实例
     */
    private RedisConnectionFactory createSingleConnectionFactory() {
        LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory();
        Integer port = Integer.valueOf(environment.getProperty("spring.redis.port"));
        String hostName = environment.getProperty("spring.redis.host");
        String password = environment.getProperty("spring.redis.password");

        // 解密密码
        if (password != null && password.startsWith("DES@")) {
            String key = ObjectKit.md5("REDIS", true, 16);
            String pwdSub = password.substring("DES@".length());
            password = EncryptionKit.decrypt(pwdSub, key, 0);
        }

        connectionFactory.setPort(port);
        connectionFactory.setHostName(hostName);
        connectionFactory.setPassword(password);
        return connectionFactory;
    }

    /**
     * 创建集群模式的Redis连接工厂
     * 
     * @return LettuceConnectionFactory 集群模式连接工厂实例
     */
    private RedisConnectionFactory createClusterConnectionFactory() {
        String clusterNodes = environment.getProperty("spring.redis.cluster.nodes");
        List<String> nodes = Arrays.asList(clusterNodes.split(","));
        RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration();

        nodes.forEach(node -> {
            String[] parts = node.split(":");
            clusterConfig.addClusterNode(new RedisNode(parts[0], Integer.parseInt(parts[1])));
        });

        String password = environment.getProperty("spring.redis.password");
        if (password != null && password.startsWith("DES@")) {
            String key = ObjectKit.md5("REDIS", true, 16);
            String pwdSub = password.substring("DES@".length());
            password = EncryptionKit.decrypt(pwdSub, key, 0);
        }
        clusterConfig.setPassword(RedisPassword.of(password));

        return new LettuceConnectionFactory(clusterConfig);
    }

    /**
     * 创建Redis模板
     * 用于操作Redis数据库
     * 
     * @param factory Redis连接工厂
     * @return RedisTemplate Redis模板实例
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(@Qualifier("myRedisConnectionFactory") RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(factory);
        return template;
    }

    /**
     * 创建字符串类型的Redis模板
     * 用于操作字符串类型的Redis数据
     * 
     * @param factory Redis连接工厂
     * @return StringRedisTemplate 字符串类型Redis模板实例
     */
    @Bean
    public StringRedisTemplate stringRedisTemplate(@Qualifier("myRedisConnectionFactory") RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory);
        stringRedisTemplate.setKeySerializer(new StringRedisSerializer());
        stringRedisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return stringRedisTemplate;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值