关于在使用Redssion发布的订阅遇到大bug

2024-09-04 16:52

本文主要是介绍关于在使用Redssion发布的订阅遇到大bug,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录:

  • 故事开始
  • 解决过程
  • 昙花一现
  • 最终解决

在这里插入图片描述

故事开始

在我开发一个仿微信的一个项目的时候,有一个功能在服务端接受到客户端消息时需要做出反应

比如:有多个客户端向服务端发送消息 ,然后服务端将消息返回给多个客户端,此时可以利用redis的发布订阅
通过将消息发送给同一个主题监听这个主题是否接受到消息从未做出相应操作。

我使用了redis 的客户端ReissionClient中的publish方法进行推送消息,使用addlisten进行消息监听
代码如下:
redission的配置

package com.jjy.easy_chat.entity.config;import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.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.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** 自定义序列化方式*/
@Configuration
public class RedisConfig {private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);@Value("${spring.redis.host}")private String redisHost;@Value("${spring.redis.port}")private String redisPort;@Bean("redisTemplate")public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.setConnectionFactory(redisConnectionFactory);return redisTemplate;}@Bean(name = "redissonClient", destroyMethod = "shutdown")public RedissonClient redissonClient() {try {Config config = new Config();String url="redis://" + redisHost + ":" + redisPort;config.useSingleServer().setAddress(url)// 重试间隔时间(单位:毫秒).setRetryInterval(1500)// 最大重试次数.setRetryAttempts(5)// 连接超时时间(单位:毫秒).setTimeout(3000)// 连接池大小.setConnectionPoolSize(64)// 最小空闲连接数.setConnectionMinimumIdleSize(10);RedissonClient redissonClient = Redisson.create(config);return redissonClient;} catch (Exception e) {logger.error("redission配置出错", e);}return null;}
//    @Bean
//    public RedissonClient redissonClient() throws IOException {
//        Config config = Config.fromYAML(RedisConfig.class.getClassLoader().getResource("redission-config.yml"));
//        return Redisson.create(config);
//    }}

创建了MessageHandler去控制

package com.jjy.easy_chat.websocket;import com.jjy.easy_chat.entity.dto.MessageSendDto;
import com.jjy.easy_chat.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import javax.annotation.PostConstruct;@Component("messageHandler")
public class MessageHandler {private final String MESSAGE_TOPIC = "message.topic";private final Logger logger = LoggerFactory.getLogger(MessageHandler.class);@Autowiredprivate RedissonClient redissonClient;@Autowiredprivate ChannelContextUtils channelContextUtils;@PostConstructpublic void init() {logger.info("RedissonClient 连接测试: {}", redissonClient.getConfig().toString());}@PostConstructpublic void listenMessage() {try {logger.info("开始监听");RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);int listenerId = rTopic.addListener(MessageSendDto.class, (channel, sendDto) -> {try {logger.info("收到广播消息: {}", JsonUtils.convertObj2Json(sendDto));// channelContextUtils.sendMsg(sendDto);} catch (Exception e) {logger.error("处理广播消息时出错: {}", e.getMessage(), e);}});logger.info("监听器已添加,ID为: {}", listenerId);} catch (Exception e) {logger.error("监听消息时发生异常: {}", e.getMessage(), e);}}public void sendMessage(MessageSendDto sendDto) {RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);logger.info("发送消息", JsonUtils.convertObj2Json(sendDto));rTopic.publish(sendDto);}}

封装了个接口进行请求

    @RequestMapping("/test")private ResponseVO getTest() {MessageSendDto messageSendDto = new MessageSendDto();messageSendDto.setMessageContent("haahah" + System.currentTimeMillis());messageHandler.sendMessage(messageSendDto);//messageRabbitMqHandler.sendMessage(messageSendDto);return getSuccessResponseVO(messageSendDto);}

最后对该接口进行请求代码没有报错

在这里插入图片描述
但是没有监听到消息 如果监听到消息就会输出广播消息加内容

解决过程

我在网上找了许多方法
起初
起初我以为是以为@postConstruct注解没有起到作用,我用了许多方法去解决这个问题 发现并不是这个问题
通过debug 我发现是addlisten 没有起到作用,我到处查资料找到好多方法。

  1. 配置问题:确保Redisson客户端配置正确,包括正确配置了Redis服务器的地址、端口、密码等。如果配置有误,可能导致无法正确连接到Redis服务器,从而影响监听功能。

  2. 网络问题:网络不稳定或连接数过多可能导致程序与Redis服务断开连接。检查网络连接是否稳定,以及是否有连接数限制。

  3. Redis服务状态:检查Redis服务是否正常运行,以及是否有相关的监听功能被禁用。例如,Redis的notify-keyspace-events配置项需要开启以支持键空间通知功能。

  4. 版本兼容性:确保使用的Redisson版本与Redis服务器版本兼容。不兼容的版本可能导致某些功能无法正常工作。

  5. Redisson线程模型:Redisson使用异步模型来处理事件,如果线程模型配置不当,可能会影响消息的接收。

经过仔细查找 ,配置问题也没有问题,我以为是@Async 不对我重新创建了一个线程去执行这个方法发现也不是
网络上我在校园网和热点中进行切换可惜并没有卵用

昙花一现

最后我选择更新版本,我将pom.xml中的redission的版本调到了最高,redis的版本也调到了最高 然后运行发现成功了
在这里插入图片描述

可惜第二天早上我再次运行又不行了,真的气死

最终解决

我无可奈何,想到了消息中间件的rabbitMQ的发布订阅,既然已经到此何不放手一搏,我直接打算换一个技术栈,我创建了rabbitMQ的配置

package com.jjy.easy_chat.entity.config;import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.core.*;
@Configuration
public class RabbitMqConfig {private final String EXCAHNG_NAME="message.topic";private final String QUNEUNE_NAME="message";//创建交换机@Bean("messageExchange")public Exchange getExchange() {return ExchangeBuilder.topicExchange(EXCAHNG_NAME).durable(true).build();}@Bean("bootQueue")//创建队列public Queue getQueue() {return new Queue(QUNEUNE_NAME);}//绑定交换机//交换机绑定队列@Beanpublic Binding bindMessageQueue(@Qualifier("messageExchange") Exchange exchange, @Qualifier("bootQueue") Queue queue){return BindingBuilder.bind(queue).to(exchange).with("#.message.#").noargs();}
}

MessageRabbitMqHandler

package com.jjy.easy_chat.websocket;import com.jjy.easy_chat.entity.dto.MessageSendDto;
import com.jjy.easy_chat.utils.JsonUtils;
import org.redisson.api.RTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component("messageRabbitMqHandler")
public class MessageRabbitMqHandler {@Autowiredprivate RabbitTemplate rabbitTemplate;@Autowiredprivate ChannelContextUtils channelContextUtils;@RabbitListener(queues = "message")public void listenMessage(MessageSendDto sendDto){logger.info("收到广播消息: {}", JsonUtils.convertObj2Json(sendDto));channelContextUtils.sendMsg(sendDto);}private final Logger logger = LoggerFactory.getLogger(MessageRabbitMqHandler.class);public void sendMessage(MessageSendDto sendDto) {logger.info("发送消息", JsonUtils.convertObj2Json(sendDto));rabbitTemplate.convertAndSend("message.topic","message",sendDto);}
}

最后我同样去请求这个结果发现成功了,后面也再有没有报错,开心!

如果我的内容对你有帮助,请点赞,评论,收藏。创作不易,大家的支持就是我坚持下去的动力
在这里插入图片描述

这篇关于关于在使用Redssion发布的订阅遇到大bug的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1136489

相关文章

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

嵌入式数据库SQLite 3配置使用讲解

《嵌入式数据库SQLite3配置使用讲解》本文强调嵌入式项目中SQLite3数据库的重要性,因其零配置、轻量级、跨平台及事务处理特性,可保障数据溯源与责任明确,详细讲解安装配置、基础语法及SQLit... 目录0、惨痛教训1、SQLite3环境配置(1)、下载安装SQLite库(2)、解压下载的文件(3)、

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图

Springboot如何正确使用AOP问题

《Springboot如何正确使用AOP问题》:本文主要介绍Springboot如何正确使用AOP问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录​一、AOP概念二、切点表达式​execution表达式案例三、AOP通知四、springboot中使用AOP导出

Navicat数据表的数据添加,删除及使用sql完成数据的添加过程

《Navicat数据表的数据添加,删除及使用sql完成数据的添加过程》:本文主要介绍Navicat数据表的数据添加,删除及使用sql完成数据的添加过程,具有很好的参考价值,希望对大家有所帮助,如有... 目录Navicat数据表数据添加,删除及使用sql完成数据添加选中操作的表则出现如下界面,查看左下角从左

python 常见数学公式函数使用详解(最新推荐)

《python常见数学公式函数使用详解(最新推荐)》文章介绍了Python的数学计算工具,涵盖内置函数、math/cmath标准库及numpy/scipy/sympy第三方库,支持从基础算术到复杂数... 目录python 数学公式与函数大全1. 基本数学运算1.1 算术运算1.2 分数与小数2. 数学函数