spring boot Redis提供了Pub/Sub功能 示例 代码
时间: 2023-07-30 13:10:18 浏览: 194
下面是一个简单的Spring Boot Redis Pub/Sub示例代码:
首先需要在pom.xml中添加redis和spring-boot-starter-data-redis依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.6.0</version>
</dependency>
```
然后编写一个Redis消息监听器:
```java
@Component
public class RedisMessageListener {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private MessageListenerAdapter messageListenerAdapter;
@PostConstruct
public void init() {
new Thread(() -> {
Jedis jedis = new Jedis("localhost");
jedis.subscribe(messageListenerAdapter, "test-channel");
}).start();
}
@Bean
public MessageListenerAdapter messageListenerAdapter() {
return new MessageListenerAdapter(new RedisMessageSubscriber());
}
public class RedisMessageSubscriber {
public void handleMessage(String message) {
System.out.println("Received message: " + message);
}
}
}
```
然后可以在其他地方发布消息到Redis中:
```java
@RestController
public class RedisController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@GetMapping("/publish")
public String publish() {
stringRedisTemplate.convertAndSend("test-channel", "Hello, Redis!");
return "Message sent";
}
}
```
这样,当调用/publish接口时,就会向Redis的test-channel频道发布一条消息,RedisMessageListener中的RedisMessageSubscriber就会收到该消息并进行处理。
阅读全文