<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置订阅
/**
订阅配置 channel1是频道,可以多个
也可以patternToppic
*/
@Configuration
public class MyRedisMessageListenerContainer {
@Bean
MessageListenerAdapter messageListener() {
return new MessageListenerAdapter(new MySubcribe());
}
@Bean
RedisMessageListenerContainer redisContainer(RedisConnectionFactory factory) {
final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(factory);
container.addMessageListener(messageListener(), new ChannelTopic("channel1"));
return container;
}
}
订阅者
package com;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class MySubcribe implements MessageListener {
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public void onMessage(Message message, byte[] pattern) {
System.out.println("接收数据:"+message.toString());
System.out.println("订阅频道:"+new String(message.getChannel()));
}
}
发布者
@GetMapping("/anon/publish")
@ResponseStatus(HttpStatus.OK)
public void publish() {
System.out.println("执行发布");
redisTemplate.convertAndSend("channel1", "Hello, I'm Tom!");
}
PS:后加入的订阅者,接收不到发布者之前发布的数据