消息队列
不出意外的话,有好多同志在对消息队列是啥都还没研究透彻的时候,就遇到了需要使用的情况(比如我),但是最起码在研究过维基百科百度百科的一系列说辞之后,也差不多有了了解,在这也就不赘述了,能来到这的我相信基本上也都对消息队列有自己的认知了。
如何理解消息队列
如何理解?麦当劳吃过吧,可以类比一下,点餐的是生产者,你点餐速度相比出餐速度是更快的,因此当好多人点完餐之后,点餐的消息就会进入系统,这个点完餐的清单就可以理解为消息队列,而配餐员就相当于消费者,从菜单中读取出一条点餐信息,然后根据需求完成配餐,这条点餐信息消失,可以类比为消费者从队列中消费了一条消息,大差不差应该是这么个理。
横向对比
都精准的查询到ActiveMQ了,我再做横向对比也没啥劲,就跟看《华为手机选购指南》的时候,非要来一个华为三星苹果诺基亚小灵通横向对比,只会觉得你膈应。要想知道消息队列不同技术之间的差异,请移步:>>>cnblog为乐而来:MQ选型<<<
实现
项目的话,我没有用现有的项目,新建了一个Springboot的基础程序。
我的项目结构如下,方便理解:
安装activeMQ
我这里使用的是Linux服务器,如果你是Windows的服务器的话,那有一个好消息,就是本博主与百度展开了深度合作,有什么不会的问题可以去直接百度了,哈哈哈。>>>Windows下使用ActiveMQ<<<
Linux下:
# 下载源码安装包
wget https://ftp.tsukuba.wide.ad.jp/software/apache//activemq/5.16.3/apache-activemq-5.16.3-bin.tar.gz
# 解压
tar -xzvf apache-activemq-5.16.3-bin.tar.gz
# 启动
cd ./apache-activemq-5.16.3/bin
./activemq start
activemq的其他命令可以自行了解,如果你是云服务器,需要远程连接的话,activemq的服务默认是允许的,但是后台web管理界面不行,需要在启动前,找到conf/jetty.xml,把里面的127.0.0.1改成0.0.0.0,位置大约在120行:
然后浏览器访问,后台管理系统的端口没认识8161,API端口是61616,这里访问127.0.0.1:8161,需要输入默认用户名和密码admin/admin,后续自行修改,然后再点击manage activemq broker即可进入管理界面:
至此安装完成。
包导入
需要在pom导入相关的包,这里导入了相关的springboot的起步依赖包:
<!-- activeMQ起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<!-- activeMQ连接池 -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.15.0</version>
</dependency>
因为是Web程序需求,所以Web起步依赖也需要导,还有一些其他的包根据你自己的需求导入就好。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
消息队列配置
然后是配置文件中对MQ就行配置,个人偏好使用yaml配置文件。
server:
port: 8898
spring:
activemq:
broker-url: tcp://127.0.0.1:61616
user: admin
password: admin
non-blocking-redelivery: false # 是否在回滚回滚消息之前停止消息传递。这意味着当启用此命令时,消息顺序不会被保留。
send-timeout: 0 # 等待消息发送响应的时间。设置为0等待永远。
in-memory: true
queue-name: examQueue # queue队列的名称
topic-name: examTopic # topic队列的名称
pool:
enabled: true # 启用连接池
max-connections: 100 # 最大连接数
idle-timeout: 30000 # 空闲的连接过期时间,默认为30秒
以上配置中,queue-name和topic-name并非是activeMQ起步依赖中默认配置项中的属性,但是为了方便,建立了一个自定义的MQ配置,在里面定义了这两个属性,分别用来表示两个队列的名称,实则不定义也行,可以采用硬编码方式写死或者全局静态变量,看需求而定。
接下来是activeMQ的配置类,在配置类中定义了两种模式下的监听器:
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;
@Configuration
//@ConfigurationProperties(prefix = "spring.activemq")
public class MQConfig {
@Value("${spring.activemq.broker-url}")
private String brokerUrl;
@Value("${spring.activemq.user}")
private String username;
@Value("${spring.activemq.password}")
private String password;
@Value("${spring.activemq.queue-name}")
private String queueName;
@Value("${spring.activemq.topic-name}")
private String topicName;
@Bean(name = "queue")
public Queue queue() {
return new ActiveMQQueue(queueName);
}
@Bean(name = "topic")
public Topic topic() {
return new ActiveMQTopic(topicName);
}
@Bean
public ConnectionFactory connectionFactory(){
return new ActiveMQConnectionFactory(username, password, brokerUrl);
}
@Bean
public JmsMessagingTemplate jmsMessageTemplate(){
return new JmsMessagingTemplate(connectionFactory());
}
// 在Queue模式中,对消息的监听需要对containerFactory进行配置
@Bean("queueListener")
public JmsListenerContainerFactory<?> queueJmsListenerContainerFactory(ConnectionFactory connectionFactory){
SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setPubSubDomain(false);
return factory;
}
//在Topic模式中,对消息的监听需要对containerFactory进行配置
@Bean("topicListener")
public JmsListenerContainerFactory<?> topicJmsListenerContainerFactory(ConnectionFactory connectionFactory){
SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setPubSubDomain(true);
return factory;
}
}
生产者
然后是生产者,生产者主要是用来产生消息(发送消息)的,这里写了两种模式下的生产者消息发送接口:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.jms.Destination;
import javax.jms.Queue;
import javax.jms.Topic;
@RestController
@RequestMapping("/mq")
public class ProducerController {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Queue queue;
@Autowired
private Topic topic;
@PostMapping("/queue/send")
public String sendQueue(@RequestBody String str) {
this.sendMessage(this.queue, str);
return "success";
}
@PostMapping("/topic/send")
public String sendTopic(@RequestBody String str) {
this.sendMessage(this.topic, str);
return "success";
}
// 发送消息,destination是发送到的队列,message是待发送的消息
private void sendMessage(Destination destination, final String message){
jmsMessagingTemplate.convertAndSend(destination, message);
}
}
消费者
然后是消费者,生产者在将消息发送到队列中之后,因为有监听器的存在,消费者可以监听到有新消息,然后从特定队列中消费消息,完成工作:
queue消费者:
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class QueueConsumerListener {
//queue模式的消费者
@JmsListener(destination="${spring.activemq.queue-name}", containerFactory="queueListener")
public void readActiveQueue(String message) throws InterruptedException {
Thread.sleep(3000); //模拟时间复杂度较高的工作
System.out.println("queue接受到:" + message);
}
}
topic消费者:
package com.javafeng.mqdemo.consumer;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class TopicConsumerListener {
//topic模式的消费者
@JmsListener(destination="${spring.activemq.topic-name}", containerFactory="topicListener")
public void readActiveQueue(String message) {
Thread.sleep(3000); //模拟时间复杂度较高的工作
System.out.println("topic接受到:" + message);
}
}
其他配置
需要在入口程序,允许自定义配置,并启动消息队列,我这里还配置了扫描组件的基础包位置:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.jms.annotation.EnableJms;
@SpringBootApplication(scanBasePackages = {"com.javafeng.mqdemo"})
@EnableConfigurationProperties // 允许自定义配置,也就是让MQConfig生效
@EnableJms //启动消息队列
public class MqdemoApplication {
public static void main(String[] args) {
SpringApplication.run(MqdemoApplication.class, args);
}
}
测试
运行项目,以上可以得出,queue生产者产生消息的访问路径为/mq/queue/send,topic生产者的访问路径是/mq/topic/send,接下来进行测试:
topic同理,此处我就不再做赘述了,完结撒花。
参考及引用:
博客园-风止雨歇-SpringBoot 整合 ActiveMq:
https://www.cnblogs.com/yufeng218/p/11509486.html