SpringBoot中使用redis发布订阅的学习

1、引入POM文件:

 1 <dependency>
 2     <groupId>org.springframework.boot</groupId>
 3     <artifactId>spring-boot-starter-web</artifactId>
 4 </dependency>
 5 <dependency>
 6     <groupId>org.springframework.boot</groupId>
 7     <artifactId>spring-boot-starter-web</artifactId>
 8 </dependency>
 9 <dependency>
10     <groupId>org.springframework.boot</groupId>
11     <artifactId>spring-boot-starter-data-redis</artifactId>
12 </dependency>

2、Redis配置(在application.yml文件中配置):

1 spring:
2     redis:
3         database: 0   # Redis数据库索引(默认为0)
4         host: localhost  # Redis服务器地址
5         port: 6379  # Redis服务器连接端口
6         password:    # Redis服务器连接密码(默认为空)
7         timeout: 5000  # 连接超时时间(毫秒)

3、实现消息生产者:

 1 @RestController
 2 public class SampleController {
 3 
 4     @Autowired
 5     private RedisTemplate<String, String> redisTemplate;
 6 
 7     @GetMapping(value = "/send1")
 8     public String send1(String message) {
 9         redisTemplate.convertAndSend("TextChannel", message);
10         return "send1 success";
11     }
12 
13     @GetMapping(value = "send2")
14     public String send2(String message) {
15         redisTemplate.convertAndSend("kafkaChannel", message);
16         return "send2 success";
17     }
18 }

4、实现消息消费者:

1 @Component
2 public class RedisSubscriber extends MessageListenerAdapter {
3 
4     @Override
5     public void onMessage(Message message, byte[] pattern) {
6         System.out.println(message);
7     }
8 }

5、配置消费者连接的Bean

1 @Bean
2 public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
3                                                MessageListenerAdapter listenerAdapter) {
4     RedisMessageListenerContainer container = new RedisMessageListenerContainer();
5     container.setConnectionFactory(connectionFactory);
6     container.addMessageListener(listenerAdapter, new PatternTopic("TextChannel"));
7     container.addMessageListener(listenerAdapter, new PatternTopic("kafkaChannel"));//配置要订阅的订阅项
8     return container;
9 }

6、测试:

http://localhost:8080/send1?message=111111
http://localhost:8080/send2?message=2222222

 

posted on 2019-10-29 15:52  小夏coding  阅读(307)  评论(0编辑  收藏  举报

导航