Redis学习(九)SpringBoot实现(Pub/Sub)发布订阅


ACGkaka_

已于 2023-10-08 20:51:31 修改

阅读量666
 收藏 4

点赞数 3
分类专栏: # Redis 文章标签: redis 学习 spring boot
版权

Redis
专栏收录该内容
10 篇文章1 订阅
订阅专栏
目录
一、背景
二、Redis的发布订阅
2.1 订阅单个频道
常用命令
2.2 按规则(Pattern)订阅频道
2.3 不推荐使用的原因
三、SpringBoot实现发布订阅
3.1 RedisUtil.java 发布类
1)MessageDTO.java 实体类
2)发布测试
3.2 订阅实现方式一:实现MessageListener接口
1)RedisConfig.java 配置类
2)RedisMessageListener.java 监听类
3)执行结果
3.2 订阅实现方式二:注入MessageListenerAdapter实例,反射调用
1)RedisConfig.java 配置类
2)RedisMessageReceiver.java 监听类
3)执行结果
一、背景
Redis 的 List 数据类型可以通过 rpush 和 blpop 命令实现消息队列(先进后出),没有任何元素可以弹出的时候,连续会被阻塞。

但是基于 List 实现的消息队列,不支持一对多的消息广播,相当于只有一个消费者。

如果要实现一对多的消息广播,怎么办?

二、Redis的发布订阅
Redis 2.8 及以上版本实现了发布订阅的功能。

2.1 订阅单个频道
首先思考一个问题:如果消息的生产者和消费者是不同的客户端,连接到同一个 Redis。通过什么对象把生产者和消费者关联起来呢?

在 RabbitMQ 里面叫 Queue,在 Kafka 里面叫 Topic,在 Redis 里面叫 channel(频道)。

订阅者可以订阅一个或多个 channel。 消息的发布者可以给指定的 channel 发布消息。只要消息到达了 channel,所有订阅了这个 channel 的订阅者都会收到这条消息。

常用命令
订阅命令,一次可以订阅多个频道:

subscribe channel-1 channel-2

发布消息,一次只能在一个频道发布:

publish channel-1 hello

取消订阅(不能再订阅状态下使用):

unsubscribe channel-1

测试-

2.2 按规则(Pattern)订阅频道
支持 ? 和 * 占位符:

?:代表一个字符。
*:代表 0 个或多个字符。
例如:现在有三个新闻频道:

运动新闻(news-sport)
音乐新闻(news-music)
天气新闻(news-weather)


消费端1,订阅运动新闻:

psubscribe *sport

消费端2,订阅所有新闻:

psubscribe news*

消费端3,订阅天气新闻:

psubscribe new-weather

生产者,向三个频道分别发布三条消息,对应的订阅者能收到消息:

publish news-sport kobe
publish news-music jaychou
publish news-weather sunny
1
2
3
2.3 不推荐使用的原因
消息丢失: Redis 的 Pub/Sub 模式不会对消息进行持久化,如果订阅者在消息发布之前未连接到 Redis 服务器,它们将无法接收到之前发布的消息。这意味着如果订阅者在消息发布之前断开连接或重新启动,它们将错过这些消息。
内存占用: 由于 Redis 将所有订阅者的订阅信息存储在内存中,当订阅者数量非常大时,可能会导致 Redis 服务器的内存占用过高。这会对 Redis 的性能和可伸缩性产生负面影响。
阻塞问题: 当订阅者在执行阻塞操作(例如阻塞式读取)时,它们将无法处理其他的 Redis 命令。这可能会导致性能问题,特别是在高并发环境中。
无法保证消息传递顺序: 在 Pub/Sub 模式中,消息的传递是异步的,并且无法保证消息的传递书匈奴。如果应用程序需要处理有序的消息,Pub/Sub 模式可能不适合。
一般来说,考虑到性能和持久化等因素,不建议使用 Redis 的发布订阅功能来实现 MQ。Redis 的一些内部机制用到了发布订阅功能。

三、SpringBoot实现发布订阅
3.1 RedisUtil.java 发布类
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p> @Title RedisUtil
 * <p> @Description Redis工具类
 *
 * @author ACGkaka
 * @date 2021/6/16 16:32
 */
@Slf4j
@Component
public class RedisUtil {

    @Qualifier("redisTemplate")
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 向频道发布消息
     * @param channel   频道
     * @param message   消息
     * @return true成功 false失败
     */
    public boolean publish(String channel, Object message) {
        if (!StringUtils.hasText(channel)) {
            return false;
        }
        try {
            redisTemplate.convertAndSend(channel, message);
            log.info("发送消息成功,channel:{}, message:{}", channel, message);
            return true;
        } catch (Exception e) {
            log.error("发送消息失败,channel:{}, message:{}", channel, message, e);
        }
        return false;
    }

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
1)MessageDTO.java 实体类
package com.demo.redis.listener;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.time.LocalDateTime;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class MessageDTO implements Serializable {

    /**
     * 消息标题
     */
    private String title;

    /**
     * 消息内容
     */
    private String content;

    /**
     * 消息内容
     */
    private LocalDateTime createTime;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2)发布测试
import com.demo.redis.listener.MessageDTO;
import com.demo.util.RedisUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.time.LocalDateTime;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootRedisApplicationTests {

    @Autowired
    private RedisUtil redisUtil;

    @Test
    public void test1() {
        // 订阅主题
        final String TOPIC_NAME_1 = "TEST_TOPIC_1";
        final String TOPIC_NAME_2 = "TEST_TOPIC_2";
        // 发布消息
        MessageDTO dto = new MessageDTO("测试标题", "测试内容", LocalDateTime.now());
        redisUtil.publish(TOPIC_NAME_1, dto);
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
3.2 订阅实现方式一:实现MessageListener接口
1)RedisConfig.java 配置类
import com.demo.redis.RedisCustomizeProperties;
import com.demo.redis.listener.RedisMessageListener;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

@Configuration
@EnableConfigurationProperties(RedisCustomizeProperties.class)
public class RedisConfig {

    /**
     * 配置RedisTemplate
     *
     * @param redisConnectionFactory 连接工厂
     * @return RedisTemplate
     */
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        //设置key的存储方式为字符串
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置为value的存储方式为JDK二进制序列化方式,还有jackson序列化方式(Jackson2JsonRedisSerialize)
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        //设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

    /**
     * Redis消息监听器容器(实现方式一)
     *
     * @param redisConnectionFactory    连接工厂
     * @param listener                  消息监听器
     * @return Redis消息监听容器
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory,
                                                   RedisMessageListener listener) {
        // 订阅主题
        final String TOPIC_NAME_1 = "TEST_TOPIC_1";
        final String TOPIC_NAME_2 = "TEST_TOPIC_2";
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        // 设置连接工厂
        container.setConnectionFactory(redisConnectionFactory);
        // 订阅频道(可以添加多个)
        container.addMessageListener(listener, new PatternTopic(TOPIC_NAME_1));
        container.addMessageListener(listener, new PatternTopic((TOPIC_NAME_2)));

        return container;
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
2)RedisMessageListener.java 监听类
package com.demo.redis.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class RedisMessageListener implements MessageListener {

    @Qualifier("redisTemplate")
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 打印渠道
        log.info(">>>>>>>>>> 【INFO】订阅的channel:{}", new String(pattern));

        // 获取消息
        byte[] messageBody = message.getBody();
        // 序列化对象
        MessageDTO messageDTO = (MessageDTO) redisTemplate.getValueSerializer().deserialize(messageBody);

        // 打印消息
        log.info(">>>>>>>>>> 【INFO】收到的message:{}", messageDTO);
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
3)执行结果
执行 3.1 的发布测试,结果如下:

3.2 订阅实现方式二:注入MessageListenerAdapter实例,反射调用
1)RedisConfig.java 配置类
import com.demo.redis.listener.RedisMessageReceiver;
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.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

@Configuration
public class RedisConfig {

    /**
     * 配置RedisTemplate
     *
     * @param redisConnectionFactory 连接工厂
     * @return RedisTemplate
     */
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        //设置key的存储方式为字符串
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置为value的存储方式为JDK二进制序列化方式,还有jackson序列化方式(Jackson2JsonRedisSerialize)
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        //设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

    /**
     * Redis消息监听器容器(实现方式二)
     *
     * @param redisConnectionFactory    连接工厂
     * @param adapter                   消息监听器
     * @return Redis消息监听容器
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory,
                                                    MessageListenerAdapter adapter) {
        // 订阅主题
        final String TOPIC_NAME_1 = "TEST_TOPIC_1";
        final String TOPIC_NAME_2 = "TEST_TOPIC_2";
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        // 设置连接工厂
        container.setConnectionFactory(redisConnectionFactory);
        // 订阅频道(可以添加多个)
        container.addMessageListener(adapter, new PatternTopic(TOPIC_NAME_1));
        container.addMessageListener(adapter, new PatternTopic((TOPIC_NAME_2)));

        return container;
    }

    /**
     * 用于接收消息的消息接收器
     * @param receiver
     * @return
     */
    @Bean
    public MessageListenerAdapter listenerAdapter(RedisMessageReceiver receiver) {
        // receiveMessage 为反射调用,用于接收消息的方法名
        MessageListenerAdapter receiveMessage = new MessageListenerAdapter(receiver, "receiveMessage");
        receiveMessage.setSerializer(new JdkSerializationRedisSerializer());
        return receiveMessage;
    }

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
2)RedisMessageReceiver.java 监听类
package com.demo.redis.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * <p> @Title RedisMessageReceiver
 * <p> @Description Redis消息接收器(实现方式二)
 *
 * @author ACGkaka
 * @date 2023/10/7 18:28
 */
@Slf4j
@Component
public class RedisMessageReceiver {

    /**
     * 接收消息(在 RedisConfig.java 中反射调用)
     */
    public void receiveMessage(MessageDTO messageDTO, String channel) {
        // 打印渠道
        log.info(">>>>>>>>>> 【INFO】订阅的channel:{}", channel);

        // 打印消息
        log.info(">>>>>>>>>> 【INFO】收到的message:{}", messageDTO);
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
3)执行结果
执行 3.1 的发布测试,结果如下:

整理完毕,完结撒花~ 🌻


参考地址:

1.Spring boot整合Redis实现发布订阅(超详细),https://blog.csdn.net/BBQ__ZXB/article/details/124980860

2.springboot中使用redis发布订阅,https://blog.csdn.net/H900302/article/details/113914979

3.Redis的Pub/Sub为何不建议进行消息订阅,https://www.jianshu.com/p/3eff7425429a
————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
                        
原文链接:https://blog.csdn.net/qq_33204709/article/details/133687613

<think>我们正在使用Spring Boot实现Redis集群环境下的Pub/Sub功能。根据用户提供的引用,我们可以使用Redisson或Lettuce(Spring Data Redis默认使用Lettuce)来连接Redis集群。这里我们将展示两种方式,但重点放在Spring Data Redis的Lettuce实现上,因为它更常用。 步骤: 1. 配置Redis集群连接。 2. 创建消息监听容器和消息监听器。 3. 发布消息。 引用[1]中提供了Redisson连接集群的配置,但用户问题中要求的是Spring Boot实现,而Spring Boot通常使用Spring Data Redis,它默认使用Lettuce。因此,我们将以Lettuce为例。 但是,注意引用[2]中提到了一个监听器,它是用于监听Redis key过期事件的,而不是Pub/Sub。不过我们可以借鉴其实现方式来实现Pub/Sub的监听器。 引用[3]是关于Spring Boot配置文件的,我们可以参考其中的配置项来配置Redis集群。 实现步骤: 一、添加依赖 在pom.xml中添加Spring Data Redis依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 二、配置Redis集群 在application.properties或application.yml中配置Redis集群节点。例如: application.yml: ```yaml spring: redis: cluster: nodes: - 192.168.0.231:6380 - 192.168.0.231:6381 - 192.168.0.232:6382 - 192.168.0.232:6383 - 192.168.0.233:6384 - 192.168.0.233:6385 password: 123123 # 如果是SSL,则使用rediss:// ``` 三、创建消息监听器 创建一个类实现`MessageListener`接口,用于处理接收到的消息。 ```java import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.MessageListener; public class RedisMessageSubscriber implements MessageListener { @Override public void onMessage(Message message, byte[] pattern) { String channel = new String(message.getChannel()); String body = new String(message.getBody()); System.out.println("Received message: " + body + " from channel: " + channel); } } ``` 四、配置Redis监听容器 创建一个配置类,配置`RedisMessageListenerContainer`和`RedisTemplate`。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; 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.adapter.MessageListenerAdapter; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfig { // 创建RedisTemplate,使用String序列化 @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(new StringRedisSerializer()); return template; } // 创建消息监听容器 @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); // 订阅频道,可以添加多个 container.addMessageListener(listenerAdapter, new ChannelTopic("news")); // 可以继续添加其他频道 return container; } // 消息监听器适配器,将消息监听器绑定到指定的方法 @Bean MessageListenerAdapter listenerAdapter(RedisMessageSubscriber subscriber) { // 指定消息监听器处理消息的方法名 return new MessageListenerAdapter(subscriber, "onMessage"); } @Bean RedisMessageSubscriber subscriber() { return new RedisMessageSubscriber(); } } ``` 注意:这里我们使用`MessageListenerAdapter`将`RedisMessageSubscriber`的`onMessage`方法适配为消息处理方法。 五、发布消息 我们可以使用`RedisTemplate`来发布消息。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @Service public class RedisMessagePublisher { @Autowired private RedisTemplate<String, Object> redisTemplate; public void publish(String channel, String message) { redisTemplate.convertAndSend(channel, message); } } ``` 六、测试 在Controller中注入`RedisMessagePublisher`,调用其publish方法发布消息。 注意事项: 1. Redis集群模式下,Pub/Sub消息会广播到所有节点,因此无论订阅者连接到哪个节点,只要订阅了相应的频道,就能收到消息。 2. 上述配置中,我们使用String序列化,如果消息体是复杂对象,需要自定义序列化。 如果使用Redisson客户端,配置方式会有所不同(如引用[1]所示),但Spring Data Redis提供了更高级的抽象,通常使用Lettuce即可。 关于资源消耗:每个订阅者连接都会占用一个连接,在集群中,如果同一个频道在多个节点都有订阅者,那么发布消息时,每个节点都会收到消息并转发给本地订阅者。 相关问题: 1. 如何确保消息不丢失?Redis Pub/Sub不保证消息持久化,如果要求可靠,可以考虑使用Redis Streams。 2. 如何监听多个频道?在配置容器时,多次调用`container.addMessageListener`,或者使用`PatternTopic`(支持通配符)代替`ChannelTopic`。 参考引用[1]中Redisson的配置,如果用户希望使用Redisson,也可以配置RedissonClient,然后使用Redisson的RTopic来实现Pub/Sub,但这里我们主要使用Spring Data Redis的方式。 因此,我们提供了基于Spring Data Redis(Lettuce)的实现。</think>### Spring Boot 实现 Redis 集群 Pub/Sub 功能 在 Spring Boot实现 Redis 集群的 Pub/Sub 功能,需要结合 Redis Cluster 配置、消息监听器和发布操作。以下是完整实现方案: --- #### 1. 添加依赖 在 `pom.xml` 中添加 RedisSpring Data Redis 依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> <!-- 集群支持 --> </dependency> ``` --- #### 2. 配置 Redis 集群 在 `application.yml` 中配置集群节点(参考引用[1][3]): ```yaml spring: redis: cluster: nodes: - 192.168.0.231:6380 - 192.168.0.231:6381 - 192.168.0.232:6382 - 192.168.0.232:6383 - 192.168.0.233:6384 - 192.168.0.233:6385 password: 123123 max-redirects: 3 # 最大重定向次数 lettuce: pool: max-active: 8 # 连接池配置 ``` --- #### 3. 创建消息监听器 实现 `MessageListener` 接口(参考引用[2]): ```java import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.MessageListener; @Component public class RedisMessageListener implements MessageListener { private static final Logger logger = LoggerFactory.getLogger(RedisMessageListener.class); @Override public void onMessage(Message message, byte[] pattern) { String channel = new String(message.getChannel()); String body = new String(message.getBody()); logger.info("收到消息 | 频道: {} | 内容: {}", channel, body); // 业务处理逻辑 if ("order:paid".equals(channel)) { handleOrderPayment(body); } } private void handleOrderPayment(String orderData) { // 订单处理逻辑 } } ``` --- #### 4. 配置消息监听容器 创建 Redis 监听容器配置类: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.listener.ChannelTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; @Configuration public class RedisPubSubConfig { // 需要监听的频道列表 private static final String[] CHANNELS = {"news", "order:paid", "system:alert"}; @Bean public RedisMessageListenerContainer container( RedisConnectionFactory connectionFactory, RedisMessageListener listener) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); // 注册监听器和频道 for (String channel : CHANNELS) { container.addMessageListener(listener, new ChannelTopic(channel)); } return container; } } ``` --- #### 5. 实现消息发布服务 ```java import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @Service public class RedisMessagePublisher { private final RedisTemplate<String, Object> redisTemplate; public RedisMessagePublisher(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } public void publish(String channel, Object message) { redisTemplate.convertAndSend(channel, message); // 集群模式下会自动广播到所有节点 } } ``` --- #### 6. 使用示例 **发布消息:** ```java @RestController public class OrderController { @Autowired private RedisMessagePublisher publisher; @PostMapping("/order/pay") public ResponseEntity<String> payOrder(@RequestBody Order order) { // 业务逻辑... // 发布支付成功消息 publisher.publish("order:paid", order.getId()); return ResponseEntity.ok("支付成功"); } } ``` **订阅消息:** ```java // 自动监听配置的频道 // 日志输出示例: // 收到消息 | 频道: order:paid | 内容: ORDER-12345 ``` --- ### 关键配置说明 1. **集群连接** 使用 Lettuce 客户端(默认)支持 Redis Cluster,自动处理节点发现和重定向[^1]。 2. **消息序列化** 默认使用 JDK 序列化,建议配置 JSON 序列化: ```java @Bean public RedisTemplate<String, Object> redisTemplate( RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); template.setDefaultSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); return template; } ``` 3. **错误处理** 添加重连机制(在 `application.yml` 中): ```yaml spring: redis: lettuce: shutdown-timeout: 100ms pool: max-wait: 2000ms # 连接等待时间 ``` --- ### 注意事项 1. **集群特性** Pub/Sub 消息会广播到所有节点,确保订阅者无论连接哪个节点都能收到消息。 2. **性能优化** - 避免高频发布(> 10k msg/s) - 使用连接池管理资源 - 分离业务线程和监听线程 3. **消息丢失问题** Redis Pub/Sub 不保证消息持久化,如需可靠传输: - 改用 Redis Streams(支持消息持久化) - 集成 RabbitMQ/Kafka 4. **通配符订阅** 支持 `PSUBSCRIBE news.*` 模式匹配: ```java container.addMessageListener(listener, new PatternTopic("news.*")); ``` > 完整代码示例参考:[GitHub 示例项目](https://github.com/spring-projects/spring-data-redis/tree/main/src/test/java/org/springframework/data/redis)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值