Spring Boot集成redis集群拓扑动态刷新

项目场景:

Spring Boot集成Redis集群,使用lettuce连接Cluster集群实例。


问题描述

redis其中一个节点挂了之后,springboot集成redis集群配置信息没有及时刷新,出现读取操作报错。

java.lang.IllegalArgumentException: Connection to 127.0.0.1:6379 not allowed. This connection point is not known in the cluster view
exceptionStackTrace
io.lettuce.core.cluster.PooledClusterConnectionProvider.getConnectionAsync(PooledClusterConnectionProvider.java:359)
io.lettuce.core.cluster.ClusterDistributionChannelWriter.write(ClusterDistributionChannelWriter.java:93)
io.lettuce.core.cluster.ClusterCommand.complete(ClusterCommand.java:56)
io.lettuce.core.protocol.CommandHandler.decode(CommandHandler.java:563)
io.lettuce.core.protocol.CommandHandler.channelRead(CommandHandler.java:516)

原因分析:

lettuce默认是没有开始拓扑更新及读写分离导致的


解决方案:

这里分为几种情况:

  1. springboot 1.x之前版本默认使用jedis,无需要手动开启刷新
  2. springboot 2.x默认为Lettuce,需要代码设置开启刷新节点拓扑策略
  3. springboot 2.3.0开始,支持集群拓扑刷新功能,属性配置开启即可

第一种情况:springboot1.x版本环境

springboot1.x之前版本默认使用jedis,无需手动开启动态刷新。

第二种情况:springboot2.0~2.3版本环境

springboot2.0-2.3版本默认使用lettuce,默认不支持属性配置集群拓扑刷新。使用lettuce,需要增加配置类,需要手动开启刷新。

 配置类如下:

package com.test.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import lombok.extern.java.Log;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
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.RedisStandaloneConfiguration;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;import java.lang.reflect.Method;
import java.time.Duration;@Log
@Configuration
@EnableCaching // 开启缓存支持
public class RedisConfig {@Autowiredprivate RedisProperties redisProperties;@Bean(destroyMethod = "destroy")	//销毁这个bean之前调用这个destroy回调方法释放资源public LettuceConnectionFactory redisConnectionFactory() {// redis单节点if (null == redisProperties.getCluster() || null == redisProperties.getCluster().getNodes()) {RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(redisProperties.getHost(),redisProperties.getPort());configuration.setPassword(redisProperties.getPassword());	//RedisPassword.of(redisProperties.getPassword())configuration.setDatabase(redisProperties.getDatabase());return new LettuceConnectionFactory(configuration);}// redis集群RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());redisClusterConfiguration.setPassword(redisProperties.getPassword());	//RedisPassword.of(redisProperties.getPassword())redisClusterConfiguration.setMaxRedirects(redisProperties.getCluster().getMaxRedirects());GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();genericObjectPoolConfig.setMaxTotal(redisProperties.getLettuce().getPool().getMaxActive());genericObjectPoolConfig.setMaxIdle(redisProperties.getLettuce().getPool().getMaxIdle());genericObjectPoolConfig.setMinIdle(redisProperties.getLettuce().getPool().getMinIdle());genericObjectPoolConfig.setMaxWaitMillis(redisProperties.getLettuce().getPool().getMaxWait().getSeconds());// 支持自适应集群拓扑刷新和动态刷新源ClusterTopologyRefreshOptions clusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder().enableAllAdaptiveRefreshTriggers()// 开启自适应刷新.enableAdaptiveRefreshTrigger()// 开启定时刷新.enablePeriodicRefresh(Duration.ofSeconds(5)).build();ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder().topologyRefreshOptions(clusterTopologyRefreshOptions).build();LettuceClientConfiguration lettuceClientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(genericObjectPoolConfig)	//如果使用默认配置可以注释genericObjectPoolConfig
//            .readFrom(ReadFrom.SLAVE_PREFERRED)  //读写分离:主写从读模式配置.clientOptions(clusterClientOptions).build();LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisClusterConfiguration, lettuceClientConfiguration);lettuceConnectionFactory.setShareNativeConnection(false);// 是否允许多个线程操作共用同一个缓存连接,默认 true,false 时每个操作都将开辟新的连接lettuceConnectionFactory.resetConnection();// 重置底层共享连接, 在接下来的访问时初始化return lettuceConnectionFactory;}/*** RedisTemplate配置*/@Beanpublic RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory factory) {RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(factory);// 使用注解@Bean返回RedisTemplate的时候,同时配置hashkey和hashValue的序列虎方式// key采用String的序列化方式redisTemplate.setKeySerializer(keySerializer());// value使用jackson序列化方式redisTemplate.setValueSerializer(valueSerializer());// hash的key采用String的序列化方式redisTemplate.setHashKeySerializer(keySerializer());// hash的value使用jackson序列化方式redisTemplate.setHashValueSerializer(valueSerializer());/**必须执行这个函数,初始化RedisTemplate*/// 需要先调用afterPropertiesSet方法,此方法是应该是初始化参数和初始化工作。redisTemplate.afterPropertiesSet();log.info("序列化完成!");return redisTemplate;}@Beanpublic KeyGenerator keyGenerator() {return new KeyGenerator() {@Overridepublic Object generate(Object target, Method method, Object... params) {StringBuffer sb = new StringBuffer();sb.append(target.getClass().getName());sb.append(method.getName());for (Object obj : params) {sb.append(obj.toString());}return sb.toString();}};}/*** key键序列化方式** @return RedisSerializer*/private RedisSerializer<String> keySerializer() {return new StringRedisSerializer();}/*** value值序列化方式** @return*/private Jackson2JsonRedisSerializer valueSerializer() {Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);return jackson2JsonRedisSerializer;}
}

配置文件:

#Redis Configuration
spring.redis.cluster.max-redirects=10
spring.redis.cluster.nodes=127.0.0.1:8001,127.0.0.1:8002
spring.redis.timeout=60000ms
spring.redis.password=
spring.redis.lettuce.pool.max-active=10
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-wait=-1ms

 注意:注入LettuceConnectionFactory后,一定要记得注入RedisTemplate,并 redisTemplate.setConnectionFactory(factory);

apache commons-pool2 包提供了一个通用的对象池技术的实现。可以很方便的基于它来实现自己的对象池,比如 DBCP 和 Jedis 他们的内部对象池的实现就是依赖于 commons-pool2 。

<dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.8.0</version>
</dependency>

第三种情况:springboot2.3之后版本环境

springboot2.3之后版本默认使用lettuce,默认支持属性配置开启集群拓扑刷新,其解决方案:属性配置开启即可。

spring.redis.lettuce.cluster.refresh.adaptive= true
spring.redis.lettuce.cluster.refresh.period=30000    # 30秒自动刷新一次

 

关联文章:Spring Boot集成Redis集群报错UnsupportedOperationException-CSDN博客

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/91783.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第 114 场 LeetCode 双周赛题解

A 收集元素的最少操作次数 模拟: 反序遍历数组&#xff0c;用一个集合存当前遍历过的不超过 k k k 的正数 class Solution { public:int minOperations(vector<int> &nums, int k) {unordered_set<int> vis;int n nums.size();int i n - 1;for (;; i--) {if…

CentOS 8开启bbr

CentOS 8 默认内核版本为 4.18.x&#xff0c;内核版本高于4.9 就可以直接开启 BBR&#xff0c;所以CentOS 8 启用BBR非常简单不需要再去升级内核。 开启bbr echo "net.core.default_qdiscfq" >> /etc/sysctl.conf echo "net.ipv4.tcp_congestion_contro…

第8章 Spring(一)

8.1 Spring是什么?为什么要用它 难度:★★★★ 重点:★★★★ 白话解析 Spring目前是Java技术体系中最核心的框架,没有之一,不管是SpringBoot也好还是SpringCloud,都是建立在Spring的基础之上的(这句话别不当回事,后面讲SpringBoot和SpringCloud的时候,你们就会真正理…

[Framework] Android Binder 工作原理

Binder 是 Android 系统中主要的 IPC 通信方式&#xff0c;其性能非常优异。但是包括我在内的很多开发者都对它望而却步&#xff0c;确实比较难&#xff0c;每次都是看了忘&#xff0c;忘了看&#xff0c;但是随着工作的时间约来越长&#xff0c;每次看也都对 Binder 有新的认识…

蓝桥等考Python组别十级008

第一部分:选择题 1、Python L10 (15分) 已知s = Python,下列说法正确的是( )。 s[0]对应的字符是Ps[2]对应的字符是Ps[-1]对应的字符是os[4]对应的字符是h正确答案:A 2、Python L10 (15分) 运行下面程序,输入字符串“classroom”,输出的结果是( )。

使用自功率谱、互功率谱估计滤波器幅频特性

这段时间终于对工程中的随机信号的一般处理方式有点头绪了&#xff0c;功率谱密度估计是十分重要的方式之一&#xff0c;仍需继续深入细化相关内容。 示例&#xff1a;使用自功率谱、互功率谱估计滤波器幅频特性&#xff0c;自己实现 & Matlab自带函数实现。 clc;clear;cl…

HTML之如何下载网页中的音频(二)

简介&#xff1a; CSDN博客专家&#xff0c;专注Android/Linux系统&#xff0c;分享多mic语音方案、音视频、编解码等技术&#xff0c;与大家一起成长&#xff01; 优质专栏&#xff1a;Audio工程师进阶系列【原创干货持续更新中……】&#x1f680; 人生格言&#xff1a; 人生…

毅速课堂:3D打印随形水路设计应注意什么?

随形水路是一种基于3D打印技术的新型模具冷却水路&#xff0c;能有效提高冷却效率、缩短冷却周期、提升产品良率、提高生产效率、 与传统的水路设计相比&#xff0c;随形水路更加贴合模具型腔表面&#xff0c;能够更加均匀地分配冷却水&#xff0c;使模具各部分的冷却效果得到有…

系统集成|第二十一章(笔记)

目录 第二十一章 知识产权与法律法规21.1 知识产权21.2 法律法规 上篇&#xff1a;第二十章、收尾管理 第二十一章 知识产权与法律法规 21.1 知识产权 概述&#xff1a;狭义的知识产权就是传统意义上的知识产权&#xff0c;包括著作权&#xff08;含邻接权&#xff09;&#x…

【IPC 通信】信号处理接口 Signal API(7)

收发信号思想是 Linux 程序设计特性之一&#xff0c;一个信号可以认为是一种软中断&#xff0c;通过用来向进程通知异步事件。 本文讲述的 信号处理内容源自 Linux man。本文主要对各 API 进行详细介绍&#xff0c;从而更好的理解信号编程。 exit(5) 遵循 C11&#xff0c; POSI…

生产者、消费者问题

线程六个状态&#xff1a; public enum State {/*** 新生*/NEW,/*** 运行*/RUNNABLE,/***阻塞*/BLOCKED,/*** 等待*/WAITING,/*** 超时等待*/TIMED_WAITING,/**死亡**/TERMINATED;} synchronized和lock的区别 1、synchronized是关键字&#xff0c;lock是类 2、synchronized全自…

从0到一配置单节点zookeeper

我的软件&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1nImkjOgzPkgaFOuUPwd1Sg?pwd2wqo 提取码&#xff1a;2wqo 视频教程p1-zookeeper安装和配置以及启动服务和检测是否运行成功_哔哩哔哩_bilibili 一、安装zookeeper http://zookeeper.apache.org/releases.h…

doT.js模板学习笔记

doT.js模板学习笔记 欢迎学习doT.js模板学习笔记doT.js模板是什么doT.js 主要优势在doT.js好处引入方式基本语法语法示例结尾 欢迎学习doT.js模板学习笔记 doT.js官方网站 本文章得示例源码 doT.js模板是什么 doT.js 是一个 JavaScript 模板框架&#xff0c;在 web 前端使用 d…

堆的介绍、堆的向上、 向下调整法与基本功能实现

&#x1f493;博主csdn个人主页&#xff1a;小小unicorn ⏩专栏分类&#xff1a;数据结构 &#x1f69a;代码仓库&#xff1a;小小unicorn的代码仓库&#x1f69a; &#x1f339;&#x1f339;&#x1f339;关注我带你学习编程知识 堆 二叉树的顺序结构堆的概念&#xff1a;堆的…

webpack优化策略

这三点是webpack优化策略的一部分&#xff0c;具体解释如下&#xff1a; 优化正则匹配&#xff08;Test&#xff09;&#xff1a;在webpack的配置中&#xff0c;test属性是一个正则表达式&#xff0c;用于匹配需要应用该loader的文件的扩展名。在您提供的代码中&#xff0c;te…

企业风险管理策略终极指南

企业风险管理不一定是可怕的。企业风险管理是一个模糊且难以定义的主题领域。它涵盖了企业的多种风险和程序&#xff0c;与传统的风险管理有很大不同。 那么&#xff0c;企业风险管理到底是什么&#xff1f;在本文中&#xff0c;我们将确定它是什么&#xff0c;提出两种常见的…

超级好用绘图工具(Draw.io+Github)

超级好用绘图工具&#xff08;Draw.ioGithub&#xff09; 方案简介 绘图工具&#xff1a;Draw.io 存储方式&#xff1a; Github 1 Draw.io 1.2 简介 ​ 是一款免费开源的在线流程图绘制软件&#xff0c;可以用于创建流程图、组织结构图、网络图、UML图等各种类型的图表。…

JAVA 学习笔记 2年经验

文章目录 基础String、StringBuffer、StringBuilder的区别jvm堆和栈的区别垃圾回收标记阶段清除阶段 异常类型双亲委派机制hashmap和hashtable concurrentHashMap 1.7和1.8的区别java的数据结构排序算法&#xff0c;查找算法堆排序 ThreadLocal单例模式常量池synchronizedsynch…

AIOT入门指南:探索人工智能与物联网的交汇点

AIOT入门指南&#xff1a;探索人工智能与物联网的交汇点 1. 引言 随着技术的快速发展&#xff0c;人工智能&#xff08;AI&#xff09;和物联网&#xff08;IoT&#xff09;已经成为当今最热门的技术领域。当这两个领域交汇时&#xff0c;我们得到了AIOT - 一个结合了AI的智能…

第42节——路由知识额外扩展

一、路由匹配规则 1、基本匹配规则 /path&#xff1a;精确匹配路径为 /path 的路由。 /path/subpath&#xff1a;精确匹配路径为 /path/subpath 的路由 import { BrowserRouter as Router, Route, Routes } from react-router-dom;<Router><Routes><Route p…