目的:Springboot Redis Sublish/Publish简单实现
环境:
win10
idea 2019.2
步骤:
1. 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置广播:添加广播相关bean到redis的配置文件,设置监听和接收handle
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
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.connection.jedis.JedisConnectionFactory;
@Configuration
public class RedisConfiguration {
@Bean
@ConfigurationProperties(prefix = "spring.redis")
public JedisConnectionFactory getConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
return factory;
}
//TODO
//省略其他redis基础配置
/* message接收 */
@Bean
MessageListenerAdapter messageListenerAdapter () {
return new MessageListenerAdapter((MessageListener) (message, pattern) -> {
//TODO
//针对接收的广播信息进行处理。如果想要屏蔽本机广播,在接收后进行验证ip/mac或其他进行规避。
System.out.println("message.toString()");
});
}
/* 设置监听, 方法一 */
@Bean
RedisMessageListenerContainer redisMessageListenerContainer(JedisConnectionFactory jedisConnectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(jedisConnectionFactory);
container.addMessageListener(messageListenerAdapter(), channelTopic());
return container;
}
/* 设置监听,方法二,若未配置connectionFactory,可使用RedisConnectionFactory
@Bean
RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(messageListenerAdapter(), channelTopic());
return container;
}
*/
/* 配置监听队列, 示例队列名称为"messageQueue" */
@Bean
ChannelTopic channelTopic () {
return new ChannelTopic("broadCast_Queue_Test");
}
}
3. 消息发布 Sublish
在需要发布消息的地方添加上如下代码即可:
//引用
@Autowired
StringRedisTemplate stringRedisTemplate ;
//调用,往指定队列发送消息(消息类型也可以是jsonString,这样就可以收到json数据了)
//发送到的队列和监听队列全名必须一致。
stringRedisTemplate .convertAndSend("broadCast_Queue_Test","This is a sublish message");