什么场景需要使用消息队列(MessageQuery)
1、解耦
2、异步,查询数据库需要有4次查询,1次10秒,2次4秒,3次3秒,4次10秒(同步就需要28秒,而异步要10秒)
3、削峰,某个时间用户量特大,其他时间用户量不大
一、因为上面的问题,所以来引申出了消息队列,而只有应用了消息队列,该项目才不算**玩具
本篇学了ActiveMQ,上activemq.apaqi下载对应的zip或者tar包,解压
http://activemq.apache.org
在conf上的user.properties最下面修改登录的用户名和密码,但修改之后似乎无效
window下直接在bin的win64目录下运行activemq.bat文件即可
浏览器登录http://localhost:8161/admin
登录默认为admin:admin
在java中的简单实现:
1、简单实现前的准备,需要引入相应的jar包,直接新建maven工程(junit为测试使用的jar,可加可不加)
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.8</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
2、直接在test目录下新建一个测试类:
其实基本测试就是通过new 一个ActiveMQConnectionFactory,设置用户名密码以及url,
产生ConnectionFactory,在createConnection()一个Connection,
通过Connection来createSession(),需要传两个参数为true,和收到自动确认响应回来Session.AUTO_ACKNOWLEDGE
获取Session,然后主要操作Session**,首先session.createQueue(“queue-1”)确认一个标记(目标)Destination,
再该标记Destination放入到Session构建createProducer的消息生产者对象中,同时session再构建文本内容createTextMessage(…)
获得TextMessage,最后通过Session构建的消息生产者来发送操作文本messageProducer.send(textMessage),
同时session需要进行事务的提交session.commit(),最后关闭Session和Connection
(1)直接打上@Test注解,首先是提供者(制造者),总共需要10步
1. 创建mq工厂
ConnectionFactory
2. 获取连接
Connection
(最好需要Connection.start() 开启连接)
3. 获取session
4. 设置目标(点对点模式)
Destination
5. 创建生产者
MessageProducer
6. 设置发送文本内容
TextMessage
7. 发送
messageProducer.send(textMessage);
8. 提交发送
session.commit();
9. 关闭连接
session.close();
connection.close();
对应的属性为,需要用户名和密码以及连接的brokerURL
/** ActiveMQ的登录账号 */
private String userName = "admin";
/** ActiveMQ的登录密码 */
private String password = "admin";
/** ActiveMQ的连接地址 */
private String brokerURL = "tcp://127.0.0.1:61616";
@Test
public void testProducer() throws JMSException {
// 1. 创建mq工厂
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, password, brokerURL);
// 2. 获取连接
Connection connection = connectionFactory.createConnection();
// 3. 获取session
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
/*
* Session.AUTO_ACKNOWLEDGE,消费者得到消息后自动给ActiveMQ发送一条收到消息的通知,
* 收到通知后ActiveMQ会把队列中的消息删除
* Session.CLIENT_ACKNOWLEDGE,消费者得到消息后需要手动给ActiveMQ发送一条收到消息的通知
*/
// 4. 设置目标(点对点模式)(这里的queue-1相应于约定的标记,消费者(客户端)通过此标记获取到该文本等内容)
Destination destination = session.createQueue("queue-1");
// 5. 创建消息生产者
MessageProducer messageProducer = session.createProducer(destination);
// 6. 设置发送文本内容
TextMessage textMessage = session.createTextMessage("你好,世界!");
// 7. 发送
messageProducer.send(textMessage);
// 8. 提交发送
session.commit();
// 9. 关闭连接
session.close();
connection.close();
}
同样的消费者也是一样的:
只是相比起提供者session生产messageProducer的步骤,消费者的session为生产createConsumer,
并放入约定好的标记destination,同时通过MessageConsumerreceive(100000)来接受,获取到信息Message,
并打印出来((TextMessage) message).getText(),最后需要同时关闭Session和Connection
@Test
public void testConsumer() throws JMSException {
// 1. 创建mq工厂
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, password, brokerURL);
// 2. 获取连接
Connection connection = connectionFactory.createConnection();
// 3. 打开连接
connection.start();
// 4. 获取session
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
// 5. 设置目标
Destination destination = session.createQueue("queue-2");
// 6. 创建生产者
MessageConsumer messageConsumer = session.createConsumer(destination);
// 7. 接收信息
// Message message = messageConsumer.receive(100000);
messageConsumer.receive();
messageConsumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
if (message instanceof TextMessage) {
try {
System.out.println(((TextMessage) message).getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
// 8. 处理消息
// if (message instanceof TextMessage) {
// System.out.println(((TextMessage) message).getText());
// }
// 9. 确认消息接收,如果使用AUTO_ACKNOWLEDGE则不需要手动确认
// message.acknowledge();
session.commit();
// 10. 关闭连接
session.close();
connection.close();}
二、使用ActiveMQ的订阅,代码基本一致,唯一需要修改的为
通过Session构建标记(目标)时,需要换成createTopic即可,提供者和消费者都一样,其他不变
Destination destination = session.createTopic(“topic-1”);
三、将ActiveMQ与Spring框架整合:
1、首先需要有对应的提供者类、对应的点与点类以及订阅类(第一个为提供者,后三个位消费者,共4个类)
2、后面的3个消费者类需要实现implements MessageListener此接口,然后重写onMessage方法即可
在重写方法获取文本并打印即可,代码如下(此类为举例,对应的订阅类其实换个类名就行了,主要是配置文件配置**):
public class QueueReciver implements MessageListener{
@Override
public void onMessage(Message message) {
if (message instanceof TextMessage) {
try {
System.err.println(((TextMessage) message).getText());
} catch (JMSException e) {e.printStackTrace();}} } }
3、提供者类,需要提供两个方法:
需要自动注入通过Spring容器管理bean下的JmsTemplate ,其中一个为jmsTemplateQueue,jmsTemplateTopic
注意*:因为此处的@Autowired是根据类型自动注入,所以需要再加上
@Qualifier("jmsTemplateQueue")此注解根据名称注入,必须与Autowired一起使用
然后直接根据JmsTemplate的send方法执行,放入约定的标记以及文本内容
一个为点对点的执行方法,另一个为订阅的执行方法
public class TestProvider {
@Autowired
@Qualifier("jmsTemplateQueue")
JmsTemplate jmsTemplateQueue;
@Autowired
@Qualifier("jmsTemplateTopic")
JmsTemplate jmsTemplateTopic;
/*(成员变量的get/set需要提供)*/
public void sendQueue(String name,String text) {
jmsTemplateQueue.send(name,new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(text);
}
});
}
public void sendtopic(String name,String text) {
jmsTemplateTopic.send(name,new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(text); }});}
}
4、配置文件spring-jms.xml (最最主要***)(会在最后面直接给好--(此时订阅还未完成,明天修改))
(1)需要依赖一个jar包,即可(会将其他的依赖都引入进来,eg:spring等)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
(2)直接新建一个spring bean configration file的配置文件,文件名为spring-jms.xml
在对应的规范(第二个命名空间namespaces)中添加context,jms,core.没有amq,需要手动添加进入
在xsi:schemaLocation中添加上http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
在添加xmlns:amq="http://activemq.apache.org/schema/core"即可
(3)需要配置<amq:connectionFactory id="amqConnectionFactory" userName="admin" password="admin" brokerURL="tcp://192.168.248.102:61616"/>
<!-- Spring管理ActiveMQ的ConnectionFactory -->
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<!-- 指定ActiveMQ创建出来的Bean -->
<constructor-arg name="targetConnectionFactory" ref="amqConnectionFactory"/>
<!-- 配置session的最大连接数 -->
<property name="sessionCacheSize" value="100"/>
</bean>
(4)此代码为直接通过spring容器依赖注入JmsTemplate的两个实体,一个开启订阅,一个不开启
<bean id="jmsTemplateQueue" class="org.springframework.jms.core.JmsTemplate">
<constructor-arg name="connectionFactory" ref="connectionFactory"/>
<!-- 设置是否订阅模式,true是订阅模式,false是点对点 -->
<property name="pubSubDomain" value="false"/>
</bean>
<bean id="jmsTemplateTopic" class="org.springframework.jms.core.JmsTemplate">
<constructor-arg name="connectionFactory" ref="connectionFactory"/>
<!-- 设置是否订阅模式,true是订阅模式,false是点对点 -->
<property name="pubSubDomain" value="true"/>
</bean>
(5)此代码为直接通过spring容器的规格管理直接创建两个监听器,分别destination-type分别为queue和topic
然后在<jms:listener-container>中打入<jms:listener>的属性 destination="test.queue"
注意*:test.queue需要跟等下测试类时提供的name一致,才能获取到文本
<!-- 监听消息,会自动创建Bean无需提供class -->
<jms:listener-container
destination-type="queue"
container-type="default"
connection-factory="connectionFactory"
acknowledge="auto">
<jms:listener destination="test.queue" ref="queueReciver"/>
</jms:listener-container>
<jms:listener-container
destination-type="topic"
container-type="default"
connection-factory="connectionFactory"
acknowledge="auto">
<jms:listener destination="test.topic" ref="topicReceiver1"/>
<jms:listener destination="test.topic" ref="topicReceiver2"/>
</jms:listener-container>
(6)ActiveMQ与Spring容器的整合基本完成,
最后一步,需要直接bean实例化出开头提到的1个提供者和3个消费者,直接公国ref引用进来即可
<bean id="messageProvider" class="com.qyl.jms.MessageProvider">
<property name="jmsTemplateQueue" ref="jmsTemplateQueue"/>
<property name="jmsTemplateTopic" ref="jmsTemplateTopic"/>
</bean>
<!-- 点对点的消费者 -->
<bean id="queueReciver" class="com.qyl.jms.QueueReciver" />
<!-- 订阅的消费者 -->
<bean id="topicReceiver1" class="com.qyl.jms.TopicReciver1" />
<bean id="topicReceiver2" class="com.qyl.jms.TopicReciver2" />
完整的xml配置文件=开始===============================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:amq="http://activemq.apache.org/schema/core"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
">
<!-- 创建ActiveMQ的ConnectionFactory,不需要指定class会自动把这个bean创建出来 -->
<amq:connectionFactory id="amqConnectionFactory" userName="admin" password="admin" brokerURL="tcp://192.168.248.102:61616"/>
<!-- Spring管理ActiveMQ的ConnectionFactory -->
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<!-- 指定ActiveMQ创建出来的Bean -->
<constructor-arg name="targetConnectionFactory" ref="amqConnectionFactory"/>
<!-- 配置session的最大连接数 -->
<property name="sessionCacheSize" value="100"/>
</bean>
<bean id="jmsTemplateQueue" class="org.springframework.jms.core.JmsTemplate">
<constructor-arg name="connectionFactory" ref="connectionFactory"/>
<!-- 设置是否订阅模式,true是订阅模式,false是点对点 -->
<property name="pubSubDomain" value="false"/>
</bean>
<bean id="jmsTemplateTopic" class="org.springframework.jms.core.JmsTemplate">
<constructor-arg name="connectionFactory" ref="connectionFactory"/>
<!-- 设置是否订阅模式,true是订阅模式,false是点对点 -->
<property name="pubSubDomain" value="true"/>
</bean>
<!-- 监听消息,会自动创建Bean无需提供class -->
<jms:listener-container
destination-type="queue"
container-type="default"
connection-factory="connectionFactory"
acknowledge="auto">
<jms:listener destination="test.queue" ref="queueReciver"/>
</jms:listener-container>
<jms:listener-container
destination-type="topic"
container-type="default"
connection-factory="connectionFactory"
acknowledge="auto">
<jms:listener destination="test.topic" ref="topicReceiver1"/>
<jms:listener destination="test.topic" ref="topicReceiver2"/>
</jms:listener-container>
<bean id="messageProvider" class="com.qyl.jms.MessageProvider">
<property name="jmsTemplateQueue" ref="jmsTemplateQueue"/>
<property name="jmsTemplateTopic" ref="jmsTemplateTopic"/>
</bean>
<!-- 点对点的消费者 -->
<bean id="queueReciver" class="com.qyl.jms.QueueReciver" />
<!-- 订阅的消费者 -->
<bean id="topicReceiver1" class="com.qyl.jms.TopicReciver1" />
<bean id="topicReceiver2" class="com.qyl.jms.TopicReciver2" />
=完整的xml配置文件结束=================================
5、进行测试,直接在test包在新建一个测试类
直接读取配置文件即可,使用ClassPathXmlApplicationContext读取
然后获取提供者的bean,TestProvider pro = ac.getBean(TestProvider.class);
最后分别执行点对点以及订阅的方法,
注意***:此处执行方法时,写入的第一个属性name,需要与xml刚配置的标记一致,
第二个就是传输内容,随便写一写即可
public class TestJms {
private ClassPathXmlApplicationContext ac;
@Before
public void getac() {
ac= new ClassPathXmlApplicationContext("classpath:spring-jms.xml");
}
@Test
public void TestP() {
ac.start();
TestProvider pro = ac.getBean(TestProvider.class);
pro.sendQueue("test.queue", "hellokity");
ac.close();
}
@Test
public void TestT() {
ac.start();
TestProvider pro = ac.getBean(TestProvider.class);
pro.sendtopic("test.topic", "hellokity");
ac.close();}}