SpringBoot——redis发布与订阅(二十一)
引入依赖
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
|
配置RedisTemplate
1 2 3 4 5 6 7 8 9 10 11 12
| @Configuration public class RedisConfig {
@Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); return redisTemplate; } }
|
订阅监听类
订阅者
1 2 3 4 5 6 7 8 9 10
| public class SubscribeListener implements MessageListener {
@Override public void onMessage(Message message, byte[] pattern) { System.out.println(new String(pattern) + "主题发布:" + new String(message.getBody())); } }
|
发布者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Component public class PublishService { @Autowired StringRedisTemplate redisTemplate;
public void publish(String channel, Object message) { redisTemplate.convertAndSend(channel, message); } }
|
添加监听主题
在RedisConfig中配置监听test-topic主题
1 2 3 4 5 6 7 8
| @Bean public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(redisConnectionFactory); container.addMessageListener(new SubscribeListener(), new PatternTopic("test-topic")); return container; }
|
发布订阅测试
1 2 3 4 5 6 7 8 9 10 11 12 13
| @RunWith(SpringRunner.class) @SpringBootTest public class RedisMqPsApplicationTests { @Autowired private PublishService service;
@Test public void contextLoads() { for (int i = 0; i < 10; i++) { service.publish("test-topic", "hello~~~" + i); } } }
|