SpringBoot监听redis订阅监听和发布订阅

前言

我们可以在redis中发布一条订阅到通道中,所有监听了这个通道的都可以收到这个发布的内容!

redis订阅监听配置类

image.png

代码如下:
RedisListenerConfig.java

package com.wzq.redis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
 * @description: redis监听器配置
 * @author: Wzq
 * @create: 2019-12-23 15:47
 */
@Configuration(value = "RedisListenerConfigTopic")
public class RedisListenerConfig {

    //redisTemplate
    @Autowired
    private RedisTemplate redisTemplate;

    //redis连接工厂
    @Autowired
    private RedisConnectionFactory connectionFactory;

    //redis 消息监听器
    @Autowired
    private MessageListener redisMsgListener;


    //任务池
    private ThreadPoolTaskScheduler taskScheduler;


    /**
    *@Description 创建任务池,运行线程等待处理redis消息
    *@Param []
    *@Return org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler
    *@Author Wzq
    *@Date 2019/12/23
    *@Time 15:51
    */
    @Bean
    public ThreadPoolTaskScheduler iniTaskScheduler(){
        if(taskScheduler != null){
            return taskScheduler;
        }
        taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(20);
        return taskScheduler;
    }

    /**
    *@Description 定义Redis的监听容器
    *@Param []
    *@Return org.springframework.data.redis.listener.RedisMessageListenerContainer
    *@Author Wzq
    *@Date 2019/12/23
    *@Time 15:52
    */
    @Bean
    public RedisMessageListenerContainer initRedisContainer(){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        //redis 连接工厂
        container.setConnectionFactory(connectionFactory);
        //设置运行任务池
        container.setTaskExecutor(iniTaskScheduler());
        //定义监听渠道,名称为topic1
        Topic topic = new ChannelTopic("topic1");
        //定义监听器监听的Redis的消息
        container.addMessageListener(redisMsgListener,topic);
        return container;
    }



}

监听类

image.png

RedisMessageListener.java

package com.wzq.redis.config;

import org.springframework.data.domain.Page;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

/**
 * @description: redis监听类
 * @author: Wzq
 * @create: 2019-12-23 15:58
 */
@Component
public class RedisMessageListener implements MessageListener {
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //消息
        String body = new String(message.getBody());
        //渠道名称
        String topic = new String(pattern);
        System.out.println(body);
        System.out.println(topic);
    }
}

发布订阅(有两种方式)

1.使用redis命令行发布

命令:

PUBLISH topic1 hello!

image.png

image.png

2.使用redisTemplate对象发布

redisTemplate.convertAndSend("topic1","wzq好帅!");

详细代码TestController.java

package com.wzq.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description:
 * @author: Wzq
 * @create: 2019-12-23 16:16
 */
@RestController
public class Test {


    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping(value = "/test")
    public void test(){
        redisTemplate.convertAndSend("topic1","wzq好帅!");
    }

}

访问:
image.png

接收成功!

image.png

个人微信公众,经常更新一些实用的干货:
image.png

可以回答这个问题。以下是一个简单的 Spring Boot 实现 Redis 发布订阅的例子: 1. 首先,在 pom.xml 文件中添加 RedisSpring Data Redis 的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在 application.properties 文件中配置 Redis 的连接信息: ``` spring.redis.host=127...1 spring.redis.port=6379 ``` 3. 创建一个 Redis 发布者: ``` @Component public class RedisPublisher { @Autowired private RedisTemplate<String, Object> redisTemplate; public void publish(String channel, Object message) { redisTemplate.convertAndSend(channel, message); } } ``` 4. 创建一个 Redis 订阅者: ``` @Component public class RedisSubscriber { @Autowired private MessageListenerAdapter messageListenerAdapter; @PostConstruct public void init() { redisTemplate.execute((RedisCallback<Void>) connection -> { connection.subscribe(messageListenerAdapter, "channel"); return null; }); } @PreDestroy public void destroy() { redisTemplate.execute((RedisCallback<Void>) connection -> { connection.unsubscribe(); return null; }); } } ``` 5. 创建一个消息监听器: ``` @Component public class MessageListenerAdapter extends org.springframework.data.redis.listener.adapter.MessageListenerAdapter { @Override public void onMessage(Message message, byte[] pattern) { String channel = new String(message.getChannel()); String messageBody = new String(message.getBody()); System.out.println("Received message: " + messageBody + " from channel: " + channel); } } ``` 6. 在需要发布消息的地方调用 RedisPublisher 的 publish 方法: ``` @Autowired private RedisPublisher redisPublisher; redisPublisher.publish("channel", "Hello, Redis!"); ``` 这样,当有消息发布到 "channel" 频道时,RedisSubscriber 中的 MessageListenerAdapter 就会收到消息并打印出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值