ActiveMQ的介绍以及入门demo
一.浅谈JMS
jms全称Java message service;在Java基础包中就有了定义,所以市面上的很多消息中间件和数据库连接相似;Java定义了接口,各个消息中间件给了具体实现;我们的消息中间件的接口就在javax.jms下面(可以自行考察);
消息中间件利用高效可靠的消息传递机制进行平台无关的数据交流,并基于数据通信来进行分布式系统的集成。通过提供消息传递和消息排队模型,它可以在分布式环境下扩展进程间的通信。对于消息中间件,常见的角色大致也就有Producer(生产者)、Consumer(消费者)
常见的消息中间件产品:
(1)ActiveMQ
ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线。ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现。我们在本次课程中介绍 ActiveMQ的使用。
(2)RabbitMQ
AMQP协议的领导实现,支持多种场景。淘宝的MySQL集群内部有使用它进行通讯,OpenStack开源云平台的通信组件,最先在金融行业得到运用。
(3)ZeroMQ
史上最快的消息队列系统
(4)Kafka
Apache下的一个子项目 。特点:高吞吐,在一台普通的服务器上既可以达到10W/s的吞吐速率;完全的分布式系统。适合处理海量数据。
如果说消息中间件在实际项目的应用,我想就是为了解决模块之前的解耦,通过异步将非必须实时的操作放到队列里,事后执行。
二.ActiveMQ的安装
(1)将apache-activemq-5.12.0-bin.tar.gz 上传至服务器
(2)解压此文件
tar zxvf apache-activemq-5.12.0-bin.tar.gz
(3)进入apache-activemq-5.12.0\bin目录,
执行./activemq start
;
通过./activemq status
查看是否启动成功
默认的请求端口为8161;用户名密码均为admin
三.简单demo测试
pom.xml依赖(服务端我们已经在linux搭建好,这里引入依赖也是客户端)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.zsl.mq</groupId>
<artifactId>rabbitmqdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--mq的依赖-->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-client</artifactId>
<version>5.13.4</version>
</dependency>
</dependencies>
</project>
对于消息的传递有两种类型:
一种是点对点的,即一个生产者和一个消费者一一对应;
队列生产者者代码
package cn.zsl.mq;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
/**
* 队列模式的生产者
*/
public class QueueProducer {
public static void main(String[] args) throws JMSException {
//创建连接工厂
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
//创建连接
Connection connection = connectionFactory.createConnection();
//启动
connection.start();
//创建session对象 false表示是否自动提交;
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
//创建队列 des的子类!
Queue queue = session.createQueue("zsl-queue");
//创建生产者
MessageProducer messageProducer = session.createProducer(queue);
//创建文本消息
Message message = session.createTextMessage("这是我的队列生产者发送的消息");
//发送消息
messageProducer.send(message);
//关闭资源
messageProducer.close();
session.close();
connection.close();
}
}
这里的连接的是tcp
;而且端口默认为61616
队列消费者代码
package cn.zsl.mq;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.io.IOException;
public class QueueConsumer {
public static void main(String[] args) throws JMSException, IOException {
//创建连接工厂
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhsot:61616");
//创建连接
Connection connection = connectionFactory.createConnection();
//启动
connection.start();
//创建session对象 false表示是否自动提交;
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
//创建队列 des的子类!
Queue queue = session.createQueue("zsl-queue");
//创建消费者
MessageConsumer messageConsumer = session.createConsumer(queue);
messageConsumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println(textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
System.in.read();
//关闭资源
messageConsumer.close();
session.close();
connection.close();
}
}
System.in.read();主要是为了等待录入,不然程序执行完不就停了嘛!
另一种是发布/ 订阅模式,即一个生产者产生消息并进行发送后,可以由多个消费者进行接收。
发布/订阅生产者
package cn.zsl.mq;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class TopicProducer {
public static void main(String[] args) throws JMSException {
//创建连接工厂
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://119.23.229.151:61616");
//创建连接
Connection connection = connectionFactory.createConnection();
//启动
connection.start();
//创建session对象 false表示是否自动提交;
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic("test-topic");
MessageProducer messageProducer = session.createProducer(topic);
Message message = session.createTextMessage("这是我的队列生产者发送的消息");
//发送消息
messageProducer.send(message);
//关闭资源
messageProducer.close();
session.close();
connection.close();
}
}
发布/订阅消费者
package cn.zsl.mq;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.io.IOException;
public class TopicConsumer {
public static void main(String[] args) throws JMSException, IOException {
//创建连接工厂
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://119.23.229.151:61616");
//创建连接
Connection connection = connectionFactory.createConnection();
//启动
connection.start();
//创建session对象 false表示是否自动提交;
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
//创建队列 des的子类!
Topic topic = session.createTopic("test-topic");
//创建消费者
MessageConsumer messageConsumer = session.createConsumer(topic);
messageConsumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println(textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
System.in.read();
//关闭资源
messageConsumer.close();
session.close();
connection.close();
}
}
四.与spring整合
其实把上面的看懂,这一部分基本一眼带过,就是把代码配置在xml里面了。
pom依赖和上面一样,多了测试的依赖。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cm.zsl.springmq</groupId>
<artifactId>producer</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-client</artifactId>
<version>5.13.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
接下来我会把两种模式在生产者/消费者的区别写出来,共用一套代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 自动扫描quick4j包 ,将带有注解的类 纳入spring容器管理 -->
<context:component-scan base-package="cn.zsl.mq"></context:component-scan>
<!--activemq的连接工厂-->
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://119.23.229.151:61616"></property>
</bean>
<!--spring的jms连接工厂-->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<property name="targetConnectionFactory" ref="targetConnectionFactory"></property>
</bean>
<bean id="jmstemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"></property>
</bean>
<!--队列目的地-->
<!--<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">-->
<!--<constructor-arg value="test-queue"></constructor-arg>-->
<!--</bean>-->
<!--发布订阅目的地-->
<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="test-queue"></constructor-arg>
</bean>
</beans>
两个都为queueDestination的Destination,唯一的区别在于class,两种模式可以*切换
package cn.zsl.mq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
@Component
public class QueueProducer {
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private Destination destination;
public void send(final String text){
jmsTemplate.send(destination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(text);
}
});
}
}
发送消息类(不要被名称所误导),我们在spring配置文件配置的是什么,他表示的就是什么模式
生产者测试类
package cn.zsl.mq;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:springapplication.xml")
public class TestProducer {
@Autowired
private QueueProducer queueProducer;
@Test
public void test(){
queueProducer.send("与spring整合的队列消息");
}
}
消费者部分代码
spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 自动扫描quick4j包 ,将带有注解的类 纳入spring容器管理 -->
<context:component-scan base-package="cn.zsl.mq"></context:component-scan>
<!--activemq的连接工厂-->
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://119.23.229.151:61616"></property>
</bean>
<!--spring的jms连接工厂-->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<property name="targetConnectionFactory" ref="targetConnectionFactory"></property>
</bean>
<bean id="jmstemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"></property>
</bean>
<!--队列目的地-->
<!--<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">-->
<!--<constructor-arg value="test-queue"></constructor-arg>-->
<!--</bean>-->
<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="test-queue"></constructor-arg>
</bean>
<!--自定义容器-->
<bean id="myListener" class="cn.zsl.mq.MyListenter"></bean>
<!--监听的容器-->
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"></property>
<property name="destination" ref="queueDestination"></property>
<property name="messageListener" ref="myListener"></property>
</bean>
</beans>
这里多一个自定义监听器MyListenter
package cn.zsl.mq;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
public class MyListenter implements MessageListener {
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println(textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
最后就是测试代码
package cn.zsl.mq;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:springapplication.xml")
public class QueueConsumer {
@Test
public void test(){
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
结尾:
说说两种在应用中的区别把;
Queue是队列,它存储在队列中,等有消费者消费时取出,只能一个消费者消费;所以就看谁动手快;
Topic做为发布/订阅,也叫做广播,所以,生产者发送消息的时候,只有在线的消费者可以接收到,事后启动是接收不到之前的消息的。
所以,Queue多用于一次性导入(例如solr的索引库生成,只需要一遍);Topic多用于集群的同步数据;