spring boot/spring cloud 集成redis sentinel 哨兵集群

发布时间:2023-04-11 08:30

哨兵集群搭建请参考我的另一篇文章《docker-compose 搭建单机版/多机版 redis sentinel 哨兵集群》

本文主要说明 spring boot/spring cloud 集成redis 集群,直接上代码

集成所需目录结构

spring boot/spring cloud 集成redis sentinel 哨兵集群_第1张图片

只需要添加三个文件即可

RedisTemplateConfig.java

/*
 *    Copyright (c) 2018-2025, orient All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yingcan.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: orient
 */

package com.minicloud.authentication.test.config;
import io.lettuce.core.ReadFrom;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import lombok.AllArgsConstructor;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * RedisTemplate  配置
 *
 * @author alan.wang
 */

@Configuration
@AllArgsConstructor
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class RedisTemplateConfig {



	@Bean
	public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate redisTemplate = new RedisTemplate<>();
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setHashKeySerializer(new StringRedisSerializer());
		redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
		redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		return redisTemplate;
	}

	@Bean
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {

		StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
		stringRedisTemplate.setKeySerializer(new StringRedisSerializer());
		stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
		return stringRedisTemplate;
	}


	@Autowired
	RedisProperties redisProperties;

	@Bean
	public GenericObjectPoolConfig poolConfig() {
		GenericObjectPoolConfig config = new GenericObjectPoolConfig();
		config.setMinIdle(redisProperties.getLettuce().getPool().getMinIdle());
		config.setMaxIdle(redisProperties.getLettuce().getPool().getMaxIdle());
		config.setMaxTotal(redisProperties.getLettuce().getPool().getMaxActive());
		config.setMaxWaitMillis(redisProperties.getLettuce().getPool().getMaxWait().toMillis());
		return config;
	}

	@Bean
	@ConditionalOnProperty(value = "spring.redis.mode",havingValue = "sentinel")
	public RedisSentinelConfiguration redisSentinelConfiguration() {
		RedisSentinelConfiguration redisConfig = new RedisSentinelConfiguration();
		redisConfig.setMaster(redisProperties.getSentinel().getMaster());
		if(redisProperties.getSentinel().getNodes()!=null) {
			List sentinelNode=new ArrayList();
			for(String sen : redisProperties.getSentinel().getNodes()) {
				String[] arr = sen.split(":");
				sentinelNode.add(new RedisNode(arr[0],Integer.parseInt(arr[1])));
			}
			redisConfig.setDatabase(redisProperties.getDatabase());
			redisConfig.setPassword(redisProperties.getPassword());
			redisConfig.setSentinelPassword(redisConfig.getPassword());
			redisConfig.setSentinels(sentinelNode);
		}
		return redisConfig;
	}

	@Bean("redisConnectionFactory")
	@ConditionalOnProperty(value = "spring.redis.mode",havingValue = "sentinel")
	public LettuceConnectionFactory redisConnectionFactory(@Qualifier("poolConfig") GenericObjectPoolConfig config,
														 RedisSentinelConfiguration redisConfig) {//注意传入的对象名和类型RedisSentinelConfiguration
		LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(config).build();
		return new LettuceConnectionFactory(redisConfig, clientConfiguration);
	}



	@Bean
	@ConditionalOnProperty(value = "spring.redis.mode",havingValue = "cluster")
	public RedisClusterConfiguration redisClusterConfiguration() {

		RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());
		redisClusterConfiguration.setPassword(redisProperties.getPassword());
		return redisClusterConfiguration;
	}


	@Bean("redisConnectionFactory")
	@ConditionalOnProperty(value = "spring.redis.mode",havingValue = "cluster")
	public LettuceConnectionFactory redisConnectionFactory(RedisClusterConfiguration redisClusterConfiguration) {

		ClusterTopologyRefreshOptions clusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
				.enablePeriodicRefresh()
				.enableAllAdaptiveRefreshTriggers()
				.refreshPeriod(Duration.ofSeconds(5))
				.build();
		ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
				.topologyRefreshOptions(clusterTopologyRefreshOptions).build();
		LettuceClientConfiguration lettuceClientConfiguration = LettuceClientConfiguration.builder()
				.readFrom(ReadFrom.REPLICA_PREFERRED)
				.clientOptions(clusterClientOptions).build();
		return new LettuceConnectionFactory(redisClusterConfiguration, lettuceClientConfiguration);
	}



}

spring.redis.mode 是配置文件里配置的配置项,可以直接支持sentinel与cluster模式进行切换

请参考我的另一篇《RedisTemplateConfig sentinel(哨兵模式)/ cluster(集群模式) 常用配置 以及如何 一键配置切换》

application.yml

redis:
    mode: sentinel
    password: 123456
    sentinel:
      master: local-master
      nodes:
        - 192.168.1.177:26379
        - 192.168.1.177:26380
        - 192.168.1.177:26381
    lettuce:
      pool:
        max-active: 10
        max-wait: -1
        max-idle: 5
        min-idle: 1
    database: 3

记得顶层是spring:

pom.xml

  
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            org.apache.commons
            commons-pool2
        

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号