SpringBoot整合Redis,怎么实现发布-订阅?,linux资料

/**

  • 消息监听器适配器,绑定消息处理器
  • 可以配置多个 listenerAdapter,监听不同的通道
    */ @Bean
    MessageListenerAdapter listenerAdapter(RedisMessageListener receiver) {
    return new MessageListenerAdapter(receiver, “onMessage”);
    }

也就是说,当我们订阅的频道,当有消息进来时,指定它的处理类以及处理方法

三、注入消息处理器

上面我们已经注入了 RedisMessageListener 消息处理器,并指定了处理方法 onMessage(),代码如下:

package com.zyxx.common.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component; /**

  • Redis 消息接收
  • @Author Lizhou
    **/ @Slf4j
    @Component
    public class RedisMessageListener implements MessageListener {

@Override
public void onMessage(Message message, byte[] pattern) { // 接收的topic log.info(“channel:” + new String(pattern)); // 消息的POJO log.info(“message:” + message.toString());
}
}

需要实现 MessageListener 接口,重写 onMessage() 方法,然后就可以获取到通道以及消息了,从而进行我们的一些业务逻辑处理

四、操作API

在 RedisUtils 中,我们增加一个操作方法

/**

  • 向通道发布消息
    */ public boolean convertAndSend(String channel, Object message) {
    if (StringUtils.isBlank(channel)) {
    return false;
    }
    try {
    template.convertAndSend(channel, message);
    log.info(“发送消息成功,channel:{},message:{}”, channel, message);
    return true;
    } catch (Exception e) {
    log.info(“发送消息失败,channel:{},message:{}”, channel, message);
    e.printStackTrace();
    }
    return false;
    }

这里的 channel 相当于 我们存入数据的时候的 key,如果该通道不存在,则会新建一个通道

五、测试

  • 1、测试用例

package com.zyxx.redistest;

import com.zy

【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】

浏览器打开:qq.cn.hn/FTf 开源分享

xx.redistest.common.RedisUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class RedisTestApplicationTests {

@Autowired
private RedisUtils redisUtil;

@Test
void contextLoads() {
String message = “Hello World!”; // 发送消息 redisUtil.convertAndSend(“user”, message);
}
}

我们向通道 user 发送了一条 “Hello World!” 的消息

  • 2、测试结果

image.png

可以看出,我们的消息发送成功,再看控制台

image.png

我们接收到通道 user 发送了一条 “Hello World!” 的消息

作者:Asurplus、
原文链接:https://lizhou.blog.csdn.net/article/details/109238701

我们接收到通道 user 发送了一条 “Hello World!” 的消息

作者:Asurplus、
原文链接:https://lizhou.blog.csdn.net/article/details/109238701

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值