SpringBoot-Jedis哨兵

1.application.properties

spring.redis.sentinel.nodes= ***:*, ***:*, ***:*
spring.redis.sentinel.password=*
spring.redis.sentinel.master=*
spring.redis.sentinel.command-timeout=10000
spring.redis.sentinel.max-attempts=2
spring.redis.sentinel.max-redirects=3
spring.redis.sentinel.max-active=16
spring.redis.sentinel.max-wait=3000
spring.redis.sentinel.max-idle=8
spring.redis.sentinel.min-idle=0
spring.redis.sentinel.test-on-borrow=true

2.RedisConfig

@Configuration
@ConditionalOnClass(JedisCluster.class)
public class RedisConfig {
    Logger logger = LoggerFactory.getLogger(RedisCacheConfiguration.class);

    @Resource
    private RedisProperties redisProperties;

    /**
     * 配置 Redis 連接池信息
     */
    @Bean
    public JedisPoolConfig getJedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig =new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());
        jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWait());
        jedisPoolConfig.setTestOnBorrow(redisProperties.isTestOnBorrow());

        return jedisPoolConfig;
    }

    //哨兵
    @Bean
    public JedisSentinelPool jedisSentinelPool() {

        Set<String> nodeSet = new HashSet<>();
        String[] nodeStr = redisProperties.getNodes().split(",");
        for(String node:nodeStr){
            nodeSet.add(node);
        }
        //JedisSentinelPool其實(shí)本質(zhì)跟JedisPool類似,都是與redis主節(jié)點(diǎn)建立的連接池
        //JedisSentinelPool并不是說與sentinel建立的連接池,而是通過sentinel發(fā)現(xiàn)redis主節(jié)點(diǎn)并與其建立連接
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());
        jedisPoolConfig.setMaxTotal(redisProperties.getMaxActive());
        jedisPoolConfig.setMinIdle(redisProperties.getMinIdle());
        jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWait());
        return new JedisSentinelPool(redisProperties.getMaster(), nodeSet, jedisPoolConfig, redisProperties.getPassword());
    }
    /**
     * 設(shè)置數(shù)據(jù)存入redis 的序列化方式
     *  redisTemplate序列化默認(rèn)使用的jdkSerializeable
     *  存儲二進(jìn)制字節(jié)碼,導(dǎo)致key會出現(xiàn)亂碼,所以自定義序列化類
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        logger.info("redis cluster集群連接成功");
        return redisTemplate;
    }
}

3.RedisProperties

@Component
@ConfigurationProperties(prefix = "spring.redis.sentinel")
@Data
public class RedisProperties {

    private String nodes;

    private String password;

    private Integer commandTimeout;

    private Integer maxAttempts;

    private Integer maxRedirects;

    private Integer maxActive;

    private Integer maxWait;

    private Integer maxIdle;

    private Integer minIdle;

    private boolean testOnBorrow;

    private String master;

    public String getMaster() {
        return master;
    }

    public void setMaster(String master) {
        this.master = master;
    }

    public String getNodes() {
        return nodes;
    }

    public void setNodes(String nodes) {
        this.nodes = nodes;
    }

    public String getPassword() {
        return password;
    }

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

    public Integer getCommandTimeout() {
        return commandTimeout;
    }

    public void setCommandTimeout(Integer commandTimeout) {
        this.commandTimeout = commandTimeout;
    }

    public Integer getMaxAttempts() {
        return maxAttempts;
    }

    public void setMaxAttempts(Integer maxAttempts) {
        this.maxAttempts = maxAttempts;
    }

    public Integer getMaxRedirects() {
        return maxRedirects;
    }

    public void setMaxRedirects(Integer maxRedirects) {
        this.maxRedirects = maxRedirects;
    }

    public Integer getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(Integer maxActive) {
        this.maxActive = maxActive;
    }

    public Integer getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(Integer maxWait) {
        this.maxWait = maxWait;
    }

    public Integer getMaxIdle() {
        return maxIdle;
    }

    public void setMaxIdle(Integer maxIdle) {
        this.maxIdle = maxIdle;
    }

    public Integer getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(Integer minIdle) {
        this.minIdle = minIdle;
    }

    public boolean isTestOnBorrow() {
        return testOnBorrow;
    }

    public void setTestOnBorrow(boolean testOnBorrow) {
        this.testOnBorrow = testOnBorrow;
    }

    @Override
    public String toString() {
        return "RedisProperties{" +
                "nodes='" + nodes + '\'' +
                ", password='" + password + '\'' +
                ", commandTimeout=" + commandTimeout +
                ", maxAttempts=" + maxAttempts +
                ", maxRedirects=" + maxRedirects +
                ", maxActive=" + maxActive +
                ", maxWait=" + maxWait +
                ", maxIdle=" + maxIdle +
                ", minIdle=" + minIdle +
                ", testOnBorrow=" + testOnBorrow +
                '}';
    }
}

4.JedisUtil

@Component
public class JedisUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JedisUtil.class);
    @Autowired
    private JedisSentinelPool jedisSentinelPool;
    @Resource
    private RedisProperties redisProperties;

    public <T> void setObject(String key, int expireTime, T obj) {
       Jedis jedis = null;
        try {
            //獲取客戶端
            jedis = jedisSentinelPool.getResource();
            //執(zhí)行命令
            jedis.setex(key, expireTime, JSON.toJSONString(obj));
        } catch (Exception e) {
            LOGGER.error("JedisUtil setex error", e);
        }finally {
            if (jedis != null) {
                //這里使用的close不代表關(guān)閉連接,指的是歸還資源
                jedis.close();
            }
        }
    }

    public String getObject(String key) {
        Jedis jedis = null;
        try {
            //獲取客戶端
            jedis = jedisSentinelPool.getResource();
        } catch (Exception e) {
            LOGGER.error("JedisUtil get error", e);
        }finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return jedis.get(key);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容