springboot整合redis实现发布订阅消息例子
时间: 2023-03-28 22:02:34 浏览: 151
好的,我可以回答这个问题。以下是一个使用 Spring Boot 整合 Redis 实现发布订阅消息的例子:
1. 首先,在 pom.xml 文件中添加 Redis 和 Spring Data Redis 的依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
```
2. 在 application.properties 文件中配置 Redis 的连接信息:
```
spring.redis.host=localhost
spring.redis.port=6379
```
3. 创建一个 Redis 发布者:
```
@Component
public class RedisPublisher {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void publish(String channel, Object message) {
redisTemplate.convertAndSend(channel, message);
}
}
```
4. 创建一个 Redis 订阅者:
```
@Component
public class RedisSubscriber {
@Autowired
private MessageListenerAdapter messageListenerAdapter;
@Autowired
private RedisConnectionFactory redisConnectionFactory;
public void subscribe(String channel) {
RedisConnection redisConnection = redisConnectionFactory.getConnection();
redisConnection.subscribe(messageListenerAdapter, channel.getBytes());
}
}
```
5. 创建一个消息监听器:
```
@Component
public class MessageListener {
@org.springframework.data.redis.connection.MessageListener(topics = "test")
public void onMessage(Message message, byte[] pattern) {
System.out.println("Received message: " + message.toString());
}
}
```
6. 在启动类中启动订阅者:
```
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private RedisSubscriber redisSubscriber;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
redisSubscriber.subscribe("test");
}
}
```
这样,当发布者发布消息时,订阅者就会收到消息并输出到控制台。
阅读全文