在pom中加入redis依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.properties文件中加入redis连接信息:
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.4.100
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=20
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=20
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=1000
创建消息接受者:
public class Receiver {
private static final Logger logger = LoggerFactory.getLogger(Receiver.class);
private CountDownLatch latch;
@Autowired
public Receiver(CountDownLatch latch) {
this.latch = latch;
}
public void receiveMessage(String message) {
logger.info("Received Message=== " + message );
latch.countDown();
}
}
在Application启动类中注入相关Bean:
//注入消息接收者
@Bean
Receiver receiver(CountDownLatch latch) {
return new Receiver(latch);
}
@Bean
CountDownLatch latch() {
return new CountDownLatch(1);
}
//使用spring-data-reids提供的StringRedisTemplate发送消息
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
//注入消息监听容器
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("topic"));
return container;
}
@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}
写一个Controller进行测试:
@RestController
public class RedisQueueController {
@Autowired
StringRedisTemplate stringRedisTemplate;
@RequestMapping("/sendRedisMsg")
@ResponseBody
public void sendRedisMessage(String message) {
//convertAndSend的第一个参数(这里是topic)要与监听器容器中addMessageListener方法所监听的一致
stringRedisTemplate.convertAndSend("topic", message);
}
}
通过Postman访问此接口:
控制台输出信息:
要对接收到的信息进行入库等后续操作,即可在Receiver类中进行处理。