一篇文章理解消息中间件和JMS以及ActiveMQ的安装使用

我们在开发中经常会听到ActiveMq、RabbitMQ、Kafka这些技术,其实他们都是消息中间件。 试想这样一种场:当我们进行分布式开发的时候,随着程序功能的不断增多,模块也逐渐增多,模块间的依赖关系也变得复杂起来。这种模块之间的依赖也称之为耦合。而耦合越多,之后的维护工作就越困难。那么如果改善系统模块调用关系、减少模块之间的耦合呢?这固然是必须的,消息中间件就是针对这种问题的一种解决方案

什么是消息中间件

中间件我们可以理解为是一个介于软件和系统之间的程序,为软件提供基础服务。消息中间件利用高效可靠的消息传递机制进行平台无关的数据交流,并基于数据通信来进行分布式系统的集成。通过提供消息传递和消息排队模型,它可以在分布式环境下扩展进程间的通信。对于消息中间件,常见的角色大致也就有Producer(生产者)、Consumer(消费者)。简单来说消息中间件就是解决两个服务间异步传输消息的软件
常见的消息中间件有:
(1)ActiveMQ
ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线。ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现。

(2)RabbitMQ
AMQP协议的领导实现,支持多种场景。淘宝的MySQL集群内部有使用它进行通讯,OpenStack开源云平台的通信组件,最先在金融行业得到运用。

(3)ZeroMQ
史上最快的消息队列系统

(4)Kafka
Apache下的一个子项目 。特点:高吞吐,在一台普通的服务器上既可以达到10W/s的吞吐速率;完全的分布式系统。适合处理海量数据。

我们通过一张图来直观的体会一下消息中间件在整个系统中充当的角色
在这里插入图片描述通过消息中间件activeMQ使运营商系统与搜索服务、页面生成服务解除了耦合

JMS

什么是JMS

JMS(Java Messaging Service)是Java平台上有关面向消息中间件的技术规范,它便于消息系统中的Java应用程序进行消息交换,并且通过提供标准的产生、发送、接收消息的接口简化企业应用的开发。

JMS本身只定义了一系列的接口规范,是一种与厂商无关的 API,用来访问消息收发系统。它类似于 JDBC(java Database Connectivity):这里,JDBC 是可以用来访问许多不同关系数据库的 API,而 JMS 则提供同样与厂商无关的访问方法,以访问消息收发服务。许多厂商目前都支持 JMS,包括 IBM 的 MQSeries、BEA的 Weblogic JMS service和 Progress 的 SonicMQ,这只是几个例子。 JMS 使您能够通过消息收发服务(有时称为消息中介程序或路由器)从一个 JMS 客户机向另一个 JML 客户机发送消息。消息是 JMS 中的一种类型对象,由两部分组成:报头和消息主体。报头由路由信息以及有关该消息的元数据组成。消息主体则携带着应用程序的数据或有效负载。
JMS 定义了五种不同的消息正文格式,以及调用的消息类型,允许你发送并接收以一些不同形式的数据,提供现有消息格式的一些级别的兼容性。

  • TextMessage–一个字符串对象
  • MapMessage–一套名称-值对
  • ObjectMessage–一个序列化的 Java 对象
  • BytesMessage–一个字节的数据流
  • StreamMessage – Java 原始值的数据流

JMS消息传递类型

对于消息的传递有两种类型:
一种是点对点的,即一个生产者和一个消费者一一对应;
如果有多个消费者接收的话,只有一个能接收到该传递类型的消息

另一种是发布/ 订阅模式,即一个生产者产生消息并进行发送后,可以由多个消费者进行接收。
在这里插入图片描述

ActiveMQ

下载与安装

1.官方网站下载:http://activemq.apache.org/
2.linux下安装
(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目录赋权

chmod 777 apache-activemq-5.12.0

(4)进入apache-activemq-5.12.0/bin目录

cd apache-activemq-5.12.0/bin

(5)赋与执行权限

chmod 755 activemq 

(6)启动

./activemq start

启动完成后,访问 http://服务器ip地址:8161,如果可以正常访问,则已经启动成功,如果无法访问,首先检查服务器8161端口是否开启。如果已开启依然不能访问,可以参考https://blog.youkuaiyun.com/WB1224678/article/details/100097553这篇博客

入门Demo

点对点模式

1.创建maven工程引入ActiveMQ依赖

<dependency>
		<groupId>org.apache.activemq</groupId>
		<artifactId>activemq-client</artifactId>
		<version>5.13.4</version>
</dependency>

2.编写消息生产者

public class QueueProducer {
	public static void main(String[] args) throws JMSException {
		//1.创建连接工厂
		ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://140.143.21.45:61616");
		//2.获取连接
		Connection connection = factory.createConnection();
		//3.启动连接
		connection.start();
		//4.获取Session(参数是1否启动事务,参数2消息确认模式)
		/*AUTO_ACKNOWLEDGE = 1    自动确认
			CLIENT_ACKNOWLEDGE = 2    客户端手动确认   
			DUPS_OK_ACKNOWLEDGE = 3    自动批量确认
			SESSION_TRANSACTED = 0    事务提交并确认*/
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		//5.创建队列对象
		Queue queue = session.createQueue("test-queue");
		//6.创建消息生产者
		MessageProducer producer = session.createProducer(queue);
		//7.创建消息
		TextMessage message = session.createTextMessage("Hello ActiveMQ");
		//8.发送消息
		producer.send(message);
		//9.关闭资源
		producer.close();
		session.close();
		connection.close();
	}
}

3.编写消息消费者

public class QueueConsumer {
	public static void main(String[] args) throws JMSException, IOException {
		//1.创建连接工厂
		ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://140.143.21.45:61616");
		//2.创建连接
		Connection connection = factory.createConnection();
		//3.开启连接
		connection.start();
		//4.获取Session
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		//5.创建消息队列对象
		Queue queue = session.createQueue("test-queue");
		//6.创建消息消费者
		MessageConsumer consumer = session.createConsumer(queue);
		//7.监听消息
		consumer.setMessageListener(new MessageListener() {
			public void onMessage(Message message) {
				TextMessage textMessage = (TextMessage) message;
				try {
					System.out.println(textMessage.getText());
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		});
		//8.等待键盘输入,因为是个入门demo,写这句话是为了防止还没有监听到信息,资源就都关闭了
		System.in.read();
		//9.关闭资源
		consumer.close();
		session.close();
		connection.close();
	}
}
发布/订阅模式

消息生产者

    //1.创建连接工厂
	ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("tcp://192.168.25.135:61616");
	//2.获取连接
	Connection connection = connectionFactory.createConnection();
	//3.启动连接
	connection.start();
	//4.获取session  (参数1:是否启动事务,参数2:消息确认模式)
	Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
	//5.创建主题对象
	Topic topic = session.createTopic("test-topic");
	//6.创建消息生产者
	MessageProducer producer = session.createProducer(topic);
	//7.创建消息
	TextMessage textMessage = session.createTextMessage("欢迎来到神奇的品优购世界");
	//8.发送消息
	producer.send(textMessage);
	//9.关闭资源
	producer.close();
	session.close();
	connection.close();

消息消费者

    //1.创建连接工厂
	ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("tcp://192.168.25.135:61616");
	//2.获取连接
	Connection connection = connectionFactory.createConnection();
	//3.启动连接
	connection.start();
	//4.获取session  (参数1:是否启动事务,参数2:消息确认模式)
	Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
	//5.创建主题对象
	//Queue queue = session.createQueue("test-queue");
	Topic topic = session.createTopic("test-topic");
	//6.创建消息消费
	MessageConsumer consumer = session.createConsumer(topic);
	
	//7.监听消息
	consumer.setMessageListener(new MessageListener() {
		public void onMessage(Message message) {
			TextMessage textMessage=(TextMessage)message;
			try {
				System.out.println("接收到消息:"+textMessage.getText());
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	});
	//8.等待键盘输入
	System.in.read();
	//9.关闭资源
	consumer.close();
	session.close();
	connection.close();

Spring整合Demo

点对点模式

1.消息提供者
(1)创建工程springjms_producer,在POM文件中引入SpringJms 、activeMQ以及单元测试相关依赖
(2)在src/main/resources下创建spring配置文件applicationContext-jms-producer.xml

<context:component-scan base-package="cn.gzc.demo"></context:component-scan>        
    <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->  
	<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
	    <property name="brokerURL" value="tcp://192.168.25.135:61616"/>  
	</bean>          
    <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->  
	<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
	<!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->  
	    <property name="targetConnectionFactory" ref="targetConnectionFactory"/>  
	</bean>  	   
    <!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->  
	<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
	    <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->  
	    <property name="connectionFactory" ref="connectionFactory"/>  
	</bean>      
    <!--这个是队列目的地,点对点的  文本信息-->  
	<bean id="queueTextDestination" class="org.apache.activemq.command.ActiveMQQueue">  
	    <constructor-arg value="queue_text"/>  
	</bean>    

(3)在cn.gzc.demo包下创建消息生产者类

@Component
public class QueueProducer {
	
	@Autowired
	private JmsTemplate jmsTemplate;
	
	@Autowired
	private Destination queueTextDestination;
	
	/**
	 * 发送文本消息
	 * @param text
	 */
	public void sendTextMessage(final String text){
		jmsTemplate.send(queueTextDestination, new MessageCreator() {			
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(text);
			}
		});		
	}
}

(4)单元测试
在src/test/java创建测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-jms-producer.xml")
public class TestQueue {

	@Autowired
	private QueueProducer queueProducer;
	
	@Test
	public void testSend(){
		queueProducer.sendTextMessage("SpringJms-点对点");
	}	
}

2.消息消费者
(1)创建工程springjms_consumer,在POM文件中引入依赖 (同上一个工程)
(2)创建配置文件 applicationContext-jms-consumer-queue.xml

<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->  
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
    <property name="brokerURL" value="tcp://192.168.25.135:61616"/>  
</bean>	   
<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->  
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
<!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->  
    <property name="targetConnectionFactory" ref="targetConnectionFactory"/>  
</bean>  	
<!--这个是队列目的地,点对点的  文本信息-->  
<bean id="queueTextDestination" class="org.apache.activemq.command.ActiveMQQueue">  
    <constructor-arg value="queue_text"/>  
</bean>    
<!-- 我的监听类 -->
<bean id="myMessageListener" class="cn.gzc.demo.MyMessageListener"></bean>
<!-- 消息监听容器 -->
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
	<property name="connectionFactory" ref="connectionFactory" />
	<property name="destination" ref="queueTextDestination" />
	<property name="messageListener" ref="myMessageListener" />
</bean>	

(3)编写监听类

public class MyMessageListener implements MessageListener {
	public void onMessage(Message message) {
	TextMessage textMessage=(TextMessage)message;		
		try {
			System.out.println("接收到消息:"+textMessage.getText());
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
}

(4)创建测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-jms-consumer-queue.xml")
public class TestQueue {
	@Test
	public void testQueue(){
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}	
}
发布/订阅模式

1.消息生产者
(1)在工程springjms_producer的applicationContext-jms-producer.xml增加配置

<!--这个是订阅模式  文本信息-->  
	<bean id="topicTextDestination" class="org.apache.activemq.command.ActiveMQTopic">  
	    <constructor-arg value="topic_text"/>  
	</bean>  

(2)创建生产者类

@Component
public class TopicProducer {
	@Autowired
	private JmsTemplate jmsTemplate;
	
	@Autowired
	private Destination topicTextDestination;
	
	/**
	 * 发送文本消息
	 * @param text
	 */
	public void sendTextMessage(final String text){
		jmsTemplate.send(topicTextDestination, new MessageCreator() {			
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(text);
			}
		});		
	}
}

(3)编写测试类

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;
import cn.gzc.demo.TopicProducer;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-activemq-producer.xml")
public class TestTopic {
	@Autowired
	private TopicProducer topicProducer;
	@Test
	public void sendTextQueue(){		
		topicProducer.sendTextMessage();
	}	
}

2.消息消费者
(1)在activemq-spring-consumer工程中创建配置文件applicationContext-jms-consumer-topic.xml

<!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->  
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
    <property name="brokerURL" value="tcp://192.168.25.135:61616"/>  
</bean>
<!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->  
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
<!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->  
    <property name="targetConnectionFactory" ref="targetConnectionFactory"/>  
</bean>  
<!--这个是队列目的地,点对点的  文本信息-->  
<bean id="topicTextDestination" class="org.apache.activemq.command.ActiveMQTopic">  
    <constructor-arg value="topic_text"/>  
</bean>    
<!-- 我的监听类 -->
<bean id="myMessageListener" class="cn.gzc.demo.MyMessageListener"></bean>
<!-- 消息监听容器 -->
<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
	<property name="connectionFactory" ref="connectionFactory" />
	<property name="destination" ref="topicTextDestination" />
	<property name="messageListener" ref="myMessageListener" />
</bean>

(2)编写测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext-jms-consumer-topic.xml")
public class TestTopic {
	@Test
	public void testTopic(){
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}		
}

测试:同时运行多个消费者工程,在运行生产者工程,查看三个消费者工程的控制台输出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值