1. 程式人生 > >Spring boot 配置 Redis哨兵模式

Spring boot 配置 Redis哨兵模式

Spring官方提供了Redis哨兵的配置,這篇文章主要指導讀者手動配置Redis哨兵模式
ps: 參考我的文章<<Spring boot 配置 Redis叢集模式>>可將該配置改成按資原始檔載入

以下是我搜集並整理出來的一個configuration,不足之處或錯誤請大家提出並指正

package cn.xt.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.HashSet;
import java.util.Set;

/**
 * Redis 配置叢集
 */
@Configuration
public class RedisConfig {

    private final Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Value("${redis.jndi-name}")
    private String redisJndiName;

    /**
     * 建立連線工廠
     * @return
     */
    @Bean
    public JedisConnectionFactory createConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = null;
        // 哨兵模式
        RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration();
        try {
            // 載入JNDI配置(因為有些敏感資訊運維是不希望IT直接看到的)
            Context context = new InitialContext();
            RedisConfigBean redisConfigBean = (RedisConfigBean)context.lookup(redisJndiName);

            // 設定哨兵Master
            redisSentinelConfiguration.setMaster(redisConfigBean.getMasterName());
            // 獲取到所有節點
            Set<String> serviceRedisNodes = redisConfigBean.getSentinelNodes();
            // 轉換成Redis點節
            Set<RedisNode> sentinelNodes = new HashSet<>();
            for(String node : serviceRedisNodes) {
                String[] ipAndPort = StringUtils.split(node, ":");
                String ip = ipAndPort[0];
                Integer port = Integer.parseInt(ipAndPort[1]);
                sentinelNodes.add(new RedisNode(ip, port));
            }
            redisSentinelConfiguration.setSentinels(sentinelNodes);
            // 建立連線工廠
            jedisConnectionFactory = new JedisConnectionFactory(redisSentinelConfiguration, redisConfigBean.getMasterPoolConfig());
            jedisConnectionFactory.setDatabase(redisConfigBean.getDatabase());
            jedisConnectionFactory.setPassword(redisConfigBean.getPassword());
        } catch (Exception e) {
            logger.error("建立Redis連線工廠錯誤:{}", e);
        }
        return jedisConnectionFactory;
    }

    /**
     * 註冊RedisTemplate
     * @param factory 連線工廠
     * @return
     */
    @Bean
    public RedisTemplate registerRedisTemplate(JedisConnectionFactory factory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }
}

package cn.xt.config;

import redis.clients.jedis.JedisPoolConfig;

import java.util.Set;

/**
 * Redis配置(若為規範專案,該類包名請配置到專案的DTO中)
 */
public class RedisConfigBean {

    private String masterName;

    private Set<String> sentinelNodes;

    private JedisPoolConfig masterPoolConfig;

    private Integer database;

    private String password;

    public String getMasterName() {
        return masterName;
    }

    public void setMasterName(String masterName) {
        this.masterName = masterName;
    }

    public Set<String> getSentinelNodes() {
        return sentinelNodes;
    }

    public void setSentinelNodes(Set<String> sentinelNodes) {
        this.sentinelNodes = sentinelNodes;
    }

    public JedisPoolConfig getMasterPoolConfig() {
        return masterPoolConfig;
    }

    public void setMasterPoolConfig(JedisPoolConfig masterPoolConfig) {
        this.masterPoolConfig = masterPoolConfig;
    }

    public Integer getDatabase() {
        return database;
    }

    public void setDatabase(Integer database) {
        this.database = database;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}