Redis发布订阅模式
1、创建发送者
TEST_CHANNEL 为自定义通道,发送者将消息发送到通道中,接受者订阅了这个通道就可以获取到信息
@Component
public class RedisSender {
public static final String TEST_CHANNEL = "test_channel";
@Autowired
private RedisTemplate redisTemplate;
public void send(String channel, String message) {
redisTemplate.convertAndSend(channel, message);
}
}
2、创建订阅者
现在接受到了消息只是简单的打印了出来
@Component
public class RedisRecipient implements MessageListener {
public static final String TEST_CHANNEL = "test_channel";
@Override
public void onMessage(Message message, byte[] pattern) {
System.out.println("接受到的信息为:" + message.toString());
}
}
3、配置消息监听
@Configuration
public class RedisConfig {
/**
* 配置消息监听
*/
@Bean
public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, RedisRecipient redisRecipient) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
// 订阅频道
Topic topic = new PatternTopic(RedisRecipient.TEST_CHANNEL);
// 使用监听器监听Redis的消息
container.addMessageListener(redisRecipient, topic);
return container;
}
}
4、测试
@SpringBootTest
public class RedisTest {
@Resource
private RedisSender redisSender;
@Test
public void test02() {
redisTemplate.opsForValue().set("cKey", "11");
Object cKey = redisTemplate.opsForValue().get("cKey");
System.out.println(cKey);
redisSender.send(RedisSender.TEST_CHANNEL, "你好");
}
}
转载自:https://juejin.cn/post/7358109207995006987