详解SpringBoot Redis自适应配置(Cluster Standalone Sentinel)
核心代码段
提供一个JedisConnectionFactory 根据配置来判断单点集群还是哨兵
@Bean @ConditionalOnMissingBean publicJedisConnectionFactoryjedisConnectionFactory(){ JedisConnectionFactoryfactory=null; String[]split=node.split(","); Setnodes=newLinkedHashSet<>(); for(inti=0;i { redisClusterConfiguration.addClusterNode(newRedisNode(n.getHost(),n.getPort())); }); if(!StringUtils.isEmpty(password)){ redisClusterConfiguration.setPassword(RedisPassword.of(password)); } redisClusterConfiguration.setMaxRedirects(maxRedirect); factory=newJedisConnectionFactory(redisClusterConfiguration,jedisClientConfiguration); } returnfactory; }
Configration
importcom.fasterxml.jackson.annotation.JsonAutoDetect; importcom.fasterxml.jackson.annotation.PropertyAccessor; importcom.fasterxml.jackson.databind.ObjectMapper; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; importorg.springframework.cache.Cache; importorg.springframework.cache.CacheManager; importorg.springframework.cache.annotation.CachingConfigurerSupport; importorg.springframework.cache.annotation.EnableCaching; importorg.springframework.cache.interceptor.CacheErrorHandler; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.data.redis.cache.RedisCacheManager; importorg.springframework.data.redis.connection.*; importorg.springframework.data.redis.connection.jedis.JedisClientConfiguration; importorg.springframework.data.redis.connection.jedis.JedisConnectionFactory; importorg.springframework.data.redis.core.RedisTemplate; importorg.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; importorg.springframework.data.redis.serializer.RedisSerializer; importorg.springframework.data.redis.serializer.StringRedisSerializer; importorg.springframework.util.StringUtils; importredis.clients.jedis.HostAndPort; importredis.clients.jedis.JedisPoolConfig; importjava.util.LinkedHashSet; importjava.util.Set; /** *@Authorfoxzzz *@ClassSelfAdaptionRedisConfig *@Description自适应redis配置 *适用于单点[主从]哨兵模式集群模式 *@Date2020/7/614:34 */ @Configuration @EnableCaching publicclassSelfAdaptionRedisConfigextendsCachingConfigurerSupport{ privatefinalstaticLoggerlogger=LoggerFactory.getLogger(SelfAdaptionRedisConfig.class); @Value("${spring.redis.node}") privateStringnode; @Value("${spring.redis.timeout:0}") privateinttimeout; @Value("${spring.redis.password:}") privateStringpassword; @Value("${spring.redis.sentinel:}") privateStringsentinel; @Value("${spring.redis.jedis.pool.max-total:8}") privateintmaxTotal; @Value("${spring.redis.jedis.pool.max-idle:8}") privateintmaxIdle; @Value("${spring.redis.jedis.pool.min-idle:0}") privateintminIdle; @Value("${spring.redis.jedis.pool.max-wait:-1}") privatelongmaxWaitMillis; @Value("${spring.redis.jedis.pool.test-on-borrow:true}") privatebooleantestOnBorrow; @Value("${spring.redis.jedis.factory.max-redirects:5}") privateintmaxRedirect; @Autowired privateJedisPoolConfigjedisPoolConfig; @Autowired privateJedisConnectionFactoryjedisConnectionFactory; @Bean @ConditionalOnMissingBean @Override publicCacheManagercacheManager(){ //初始化缓存管理器,在这里我们可以缓存的整体过期时间什么的,我这里默认没有配置 logger.info("初始化->[{}]","CacheManagerRedisCacheManagerStart"); RedisCacheManager.RedisCacheManagerBuilderbuilder=RedisCacheManager .RedisCacheManagerBuilder .fromConnectionFactory(jedisConnectionFactory); returnbuilder.build(); } @Bean @ConditionalOnMissingBean @Override publicCacheErrorHandlererrorHandler(){ //异常处理,当Redis发生异常时,打印日志,但是程序正常走 logger.info("初始化->[{}]","RedisCacheErrorHandler"); CacheErrorHandlercacheErrorHandler=newCacheErrorHandler(){ @Override publicvoidhandleCacheGetError(RuntimeExceptione,Cachecache,Objectkey){ logger.error("RedisoccurhandleCacheGetError:key->[{}]",key,e); } @Override publicvoidhandleCachePutError(RuntimeExceptione,Cachecache,Objectkey,Objectvalue){ logger.error("RedisoccurhandleCachePutError:key->[{}];value->[{}]",key,value,e); } @Override publicvoidhandleCacheEvictError(RuntimeExceptione,Cachecache,Objectkey){ logger.error("RedisoccurhandleCacheEvictError:key->[{}]",key,e); } @Override publicvoidhandleCacheClearError(RuntimeExceptione,Cachecache){ logger.error("RedisoccurhandleCacheClearError:",e); } }; returncacheErrorHandler; } @Bean @ConditionalOnMissingBean publicJedisPoolConfigjedisPoolConfig(){ JedisPoolConfigconfig=newJedisPoolConfig(); //获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常,小于零:阻塞不确定的时间,默认-1 config.setMaxWaitMillis(maxWaitMillis); //最小空闲连接数,默认0 config.setMinIdle(minIdle); //最大空闲连接数,默认8个 config.setMaxIdle(maxIdle); //最大连接数,默认值8个 config.setMaxTotal(maxTotal); //对拿到的connection进行validateObject校验 config.setTestOnBorrow(testOnBorrow); returnconfig; } //privateJedisClustergetJedisCluster(){ //String[]split=node.split(","); //Set nodes=newLinkedHashSet<>(); //for(inti=0;i nodes=newLinkedHashSet<>(); for(inti=0;i { redisClusterConfiguration.addClusterNode(newRedisNode(n.getHost(),n.getPort())); }); if(!StringUtils.isEmpty(password)){ redisClusterConfiguration.setPassword(RedisPassword.of(password)); } redisClusterConfiguration.setMaxRedirects(maxRedirect); factory=newJedisConnectionFactory(redisClusterConfiguration,jedisClientConfiguration); } returnfactory; } @Bean @ConditionalOnMissingBean publicRedisTemplate redisTemplate(JedisConnectionFactoryjedisConnectionFactory){ //设置序列化 Jackson2JsonRedisSerializerjackson2JsonRedisSerializer=newJackson2JsonRedisSerializer(Object.class); ObjectMapperom=newObjectMapper(); om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //配置redisTemplate RedisTemplate redisTemplate=newRedisTemplate (); redisTemplate.setConnectionFactory(jedisConnectionFactory); RedisSerializerstringSerializer=newStringRedisSerializer(); //key序列化 redisTemplate.setKeySerializer(stringSerializer); //value序列化 redisTemplate.setValueSerializer(newGenericJackson2JsonRedisSerializer()); //redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); //Hashkey序列化 redisTemplate.setHashKeySerializer(stringSerializer); //Hashvalue序列化 redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); returnredisTemplate; } }
pom依赖
org.springframework.boot spring-boot-starter-data-redis ${springboot.version} org.springframework.boot spring-boot-starter provided redis.clients jedis ${redis.version} com.fasterxml.jackson.core jackson-annotations provided com.fasterxml.jackson.core jackson-databind provided com.fasterxml.jackson.core jackson-core provided
配置文件
1.yml配置
1.1支持Cluster模式集群
- node有多个redis的地址,以逗号分隔
- 如果redis没有密码直接去掉配置就可以了yml配置
spring: redis: node:127.0.0.1:1001,127.0.0.1:1002,127.0.0.1:1003 password:123456
properties配置
spring.redis.node=127.0.0.1:1001,127.0.0.1:1002,127.0.0.1:1003 spring.redis.password=123456
1.2支持Standalone模式单点
node里只有一个redis地址的时候,会自动变成单点模式yml配置
spring: redis: node:127.0.0.1:1001 password:123456
properties配置
spring.redis.node=127.0.0.1:1001 spring.redis.password=123456
1.3支持Sentinel模式哨兵
当配置上sentinel以后就变成了哨兵模式多个哨兵可以以逗号分割yml配置
spring: redis: node:127.0.0.1:1001 sentinel:127.0.0.1:1002,127.0.0.1:1003 password:123456
properties配置
spring.redis.node=127.0.0.1:1001 spring.redis.sentinel:127.0.0.1:1002,127.0.0.1:1003 spring.redis.password=123456
1.4覆盖默认配置
如果没有配置这些信息,就会走默认配置也可以在properties或者yml覆盖默认配置
#最大连接数,默认值8个 spring.redis.jedis.pool.max-total=8 #最大空闲连接数,默认8个 spring.redis.jedis.pool.max-idle=8 #最小空闲连接数,默认0 spring.redis.jedis.pool.min-idle=0 #获取连接时的最大等待毫秒数,如果超时就抛异常,小于零:阻塞不确定的时间,默认-1 spring.redis.jedis.pool.max-wait=-1 #对拿到的connection进行validateObject校验 spring.redis.jedis.pool.test-on-borrow=true #集群时最大重定向个数默认5 spring.redis.jedis.factory.max-redirects=5
使用
代码使用
@Autowired privateRedisTemplateredisTemplate;
到此这篇关于详解SpringBootRedis自适应配置(ClusterStandaloneSentinel)的文章就介绍到这了,更多相关SpringBootRedis自适应配置内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!