Spring Boot集成Redis实现消息队列
1.简介
本文主要介绍Spring Boot连接Redis数据库实现消息队列。
2.环境
- jdk 1.8+
- Maven 3.0+
- IDEA
- Redis
3.实现消息队列
项目源码地址 :https://github.com/826643679/Spring-Boot-Learning/tree/master/spring-boot-redis-mq
3.0 项目结构
3.1 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
3.2 配置Application文件
application.yml
spring:
redis:
host: localhost
port: 6379
database: 1
timeout: 0
pool:
max-active: 8
max-wait: -1
max-idle: 500
min-idle: 0
3.3 创建消息的接收者
此处直接定义一个类来作为消息接收者,并实现默认的消息接收方法:打印出消息的信息。
Receiver.java
import java.util.concurrent.CountDownLatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 is <" + message + ">");
latch.countDown();
}
}
CountDownLatch : 用于线程的计数,每完成一个线程记录一个,计数器递减。此处用于消息的顺序接收。
3.4 实现发送和接收消息
Spring Boot Data Redis提供基于Redis发送和接收消息的所有需要的组件,我们只需要配置好三个东西:
- 一个连接工厂(connection factory)
- 一个消息监听者容器(message listener container)
- 一个Redis的模板(redis template)
实现过程是通过Redis模板来发送消息,同时将Receiver注册给消息监听者容器。 连接工厂将两者连接起来,使得它们可以通过Redis服务器通信。
package com.example.redismq;
import com.example.message.Receiver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import java.util.concurrent.CountDownLatch;
@SpringBootApplication
public class RedismqApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(RedismqApplication.class);
/**
* 配置消息监听容器,监听topic为message的消息
**/
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("message"));
return container;
}
/**
* 通过消息适配器来将消息接收者和默认消息监听方法注册给容器
**/
@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}
@Bean
Receiver receiver(CountDownLatch latch) {
return new Receiver(latch);
}
@Bean
CountDownLatch latch() {
return new CountDownLatch(1);
}
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
public static void main(String[] args) throws Exception{
ApplicationContext ctx = SpringApplication.run(RedismqApplication.class, args);
StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
CountDownLatch latch = ctx.getBean(CountDownLatch.class);
LOGGER.info("Sending message...");
LOGGER.info("Begin to receive message ...");
template.convertAndSend("message", "Hello Lu Hao !");
latch.await();
LOGGER.info("Reciived completed successfully!");
System.exit(0);
}
/**
* 2020-05-02 21:07:46.018 INFO 34740 --- [ main] com.example.redismq.RedismqApplication : Sending message...
* 2020-05-02 21:07:46.018 INFO 34740 --- [ main] com.example.redismq.RedismqApplication : Begin to receive message ...
* 2020-05-02 21:07:46.040 INFO 34740 --- [ container-2] com.example.message.Receiver : Received message is <Hello Lu Hao !>
* 2020-05-02 21:07:46.040 INFO 34740 --- [ main] com.example.redismq.RedismqApplication : Reciived completed successfully!
**/
}
连接工厂我们使用Spring Boot默认的RedisConnectionFactory,是Jedis Redis库提供的JedisConnectionFactory实现。
我们将在listenerAdapter方法中定义的Bean注册为一个消息监听者,它将监听message主题的消息。
因为Receiver类是一个POJO,要将它包装在一个消息监听者适配器(实现了MessageListener接口),这样才能被监听者容器RedisMessageListenerContainer的addMessageListener方法添加到连接工厂中。有了这个适配器,当一个消息到达时,就会调用receiveMesage()方法进行响应
。
就这么简单,配置好连接工厂和消息监听者容器,你就可以监听消息啦!
发送消息就更简单了,我们使用StringRedisTemplate来发送键和值均为字符串的消息
。在main()方法中我们创建一个Spring应用的Context,初始化消息监听者容器,开始监听消息。然后获取StringRedisTemplate的实例,往message主题发送一个消息。我们看到,消息可以被成功的接收到并打印出来,搞定!