Redis + SpringBoot实现消息发布订阅

Redis + SpringBoot实现消息发布订阅

  •  11个月前
  •  712
  •  Java SpringBoot Redis 

消息的三个要素:发布者、订阅者和主题。

直接看代码吧。

Maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置文件

# redis
spring.redis.host=192.168.5.64
spring.redis.port=6379
spring.redis.password=51creditCom
spring.redis.database=0

# 主题
topic=redisTopic

发布者

@Component
public class RedisPublisher {

    @Value("${topic}")
    private String subChannel;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void sendMessage(String message) {
        System.out.println("发布消息:" + message);
        redisTemplate.convertAndSend(subChannel, message);
    }

}

订阅者

@Component
public class RedisSubscriber {

    public void onMessage(String message) {
        System.out.println("接收消息:" + message);
    }

}

Redis配置

@Configuration
public class RedisConfiguration {

    @Value("${topic}")
    private String topic;

    @Bean
    public RedisTemplate<?, ?> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<?, ?> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        return redisTemplate;
    }

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory, MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic(topic));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(RedisSubscriber subscriber) {
        return new MessageListenerAdapter(subscriber, "onMessage");
    }

}

单元测试

@SpringBootTest
@RunWith(SpringRunner.class)
public class ApplicationTest {

    @Autowired
    private RedisPublisher publisher;

    @Test
    public void main() {
        publisher.sendMessage("This is a message !");
    }
}

源码地址

https://github.com/chenpeidong/spring-boot-demo

扫一扫分享到微信

已有 条评论
写评论