一、消息中间件的好处
- 解耦 、异步、横向扩展、安全可靠、顺序保证…
二、消息中间件概述
-
中间件:非底层操作系统软件,非业务应用软件,不直接给最终用户使用,不直接给客户带来价值的软件就是中间件。
-
消息中间件:关注数据的发送和接收,利用搞高效可靠的异步消息传递机制集成分布式系统。
应用A —> 应用程序接口 —>消息中间件(发送消息) 应用B <— 应用程序接口 <—消息中间件(接收消息)
-
JMS(Java Message Service):Java平台面向消息中间件的API,在两个应用程序或分布式系统中发送消息,完成异步通信。(JMS仅为API规范,并非协议)。
JMS规范: - 提供者:实现JMS规范的消息中间件服务器; - 客户端:发送或接收消息的应用程序; - 生产者(发布者):创建并发送消息的客户端; - 消费者(订阅者):接收并处理消息的客户端; - 消息:应用程序之间传递的数据内容; - 消息模式:在客户端之间传递消息的方式,JMS中定义了主题(Topic)和队列(Queue)两种模式。 队列(Queue)模型: - 客户端包括生产者和消费者; - 队列中的消息**只能被一个消费者消费**; - 消费者可以随时消费队列中的消息; 主题(Topic)模型: - 客户端包括发布者和订阅者; - 主题中的消息被所有订阅者消费; - 消费者**不能消费订阅之前就发送到主题中的消息**;
三、本地安装ActiveMQ
- Windows平台
下载后解压,进入
\apache-activemq-5.16.0-bin\apache-activemq-5.16.0\bin\win64
目录下运行activemq.bat文件。
在浏览器中访问http://127.0.0.1:8161打开管理界面,默认用户名和密码为admin
另一种启动方式是通过服务的方式,这里略过。 - Linux平台
下载安装包,解压(tar -zxvf)后运行(./activemq start)即可。
关闭服务(./activemq stop)
四、队列模式及主题模式demo
- 创建一个Gradle工程;
- build.gradle中 配置ActiveMQ相关依赖:
plugins {
id 'java'
}
group 'com.demo.ActiveMQ'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
// mavenCentral()
//阿里云Maven远程仓库
maven { url "http://maven.aliyun.com/nexus/content/groups/public/" }
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
// https://mvnrepository.com/artifact/org.springframework/spring-context
compile group: 'org.springframework', name: 'spring-context', version: '5.1.9.RELEASE'
// https://mvnrepository.com/artifact/org.apache.activemq/activemq-all
compile group: 'org.apache.activemq', name: 'activemq-all', version: '5.15.9'
// https://mvnrepository.com/artifact/org.apache.activemq/activemq-pool
compile group: 'org.apache.activemq', name: 'activemq-pool', version: '5.15.9'
// https://mvnrepository.com/artifact/org.springframework/spring-jms
compile group: 'org.springframework', name: 'spring-jms', version: '5.1.9.RELEASE'
}
- 新建队列(queue)模式package,创建生产者,目录结构和代码如下:
生产者AppProducer
package com.demo.jms.queue;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class AppProducer {
// 定义常量:ActiveMQ服务器地址、队列名
private static final String url="tcp://localhost:61616";
private static final String queueName="queue-test";
public static void main(String[] args) throws JMSException {
// 1、创建ConnectionFactory
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
// 2、创建Connection
Connection connection = connectionFactory.createConnection();
// 3、启动连接
connection.start();
// 4、创建会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 5、创建目的地(消息发送到的地址)
Destination destination = session.createQueue(queueName);
// 6、创建生产者
MessageProducer producer = session.createProducer(destination);
for(int i=0;i<100;i++) {
//7、创建消息
TextMessage textMessage = session.createTextMessage("test"+i);
producer.send(textMessage);
//8、发布消息
System.out.println("send message "+textMessage.getText());
}
// 9、关闭连接
connection.close();
}
}
输出
消费者AppConsumer
package com.demo.jms.queue;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class AppConsumer {
private static final String url="tcp://localhost:61616";
private static final String queueName="queue-test";
public static void main(String[] args) throws JMSException {
// 1、创建ConnectionFactory
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
// 2、创建Connection
Connection connection = connectionFactory.createConnection();
// 3、启动连接
connection.start();
// 4、创建会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 5、创建目的地(消息发送到的地址)
Destination destination = session.createQueue(queueName);
// 6、创建消费者
MessageConsumer consumer = session.createConsumer(destination);
//7、创建监听器
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println("get message "+textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
// 8、关闭连接
// connection.close();
}
}
- 主题(topic)模式下package,代码如下:
AppProducer
package com.demo.jms.queue;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class AppProducer {
// 定义常量:ActiveMQ服务器地址、队列名
private static final String url="tcp://localhost:61616";
private static final String queueName="queue-test";
public static void main(String[] args) throws JMSException {
// 1、创建ConnectionFactory
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
// 2、创建Connection
Connection connection = connectionFactory.createConnection();
// 3、启动连接
connection.start();
// 4、创建会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 5、创建目的地(消息发送到的地址)
Destination destination = session.createQueue(queueName);
// 6、创建生产者
MessageProducer producer = session.createProducer(destination);
for(int i=0;i<10;i++) {
//7、创建消息
TextMessage textMessage = session.createTextMessage("test"+i);
producer.send(textMessage);
//8、发布消息
System.out.println("send message "+textMessage.getText());
}
// 9、关闭连接
connection.close();
}
}
AppConsumer
package com.demo.jms.queue;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
public class AppConsumer {
private static final String url="tcp://localhost:61616";
private static final String queueName="queue-test";
public static void main(String[] args) throws JMSException {
// 1、创建ConnectionFactory
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
// 2、创建Connection
Connection connection = connectionFactory.createConnection();
// 3、启动连接
connection.start();
// 4、创建会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 5、创建目的地(消息发送到的地址)
Destination destination = session.createQueue(queueName);
// 6、创建消费者
MessageConsumer consumer = session.createConsumer(destination);
//7、创建监听器
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println("get message "+textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
// 8、关闭连接
// connection.close();
}
}
五、Spring集成JMS连接ActiveMQ
- build.gradle配置文件
//构建脚本(给脚本用的脚本)
buildscript {
//存储一个属于gradle的变量,整个工程都能用,可通过gradle.ext.springBootVersion使用
ext {
springBootVersion = '4.2.5.RELEASE'
springVersion="4.2.5.RELEASE"
}
}
plugins {
id 'java'
}
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
// mavenCentral()
maven { url "http://maven.aliyun.com/nexus/content/groups/public/" }
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
// https://mvnrepository.com/artifact/org.springframework/spring-context
compile group: 'org.springframework', name: 'spring-context', version: '5.1.9.RELEASE'
// https://mvnrepository.com/artifact/org.apache.activemq/activemq-all
compile group: 'org.apache.activemq', name: 'activemq-all', version: '5.15.9'
// https://mvnrepository.com/artifact/org.apache.activemq/activemq-pool
compile group: 'org.apache.activemq', name: 'activemq-pool', version: '5.15.9'
compile group: 'org.apache.activemq', name: 'activemq-core', version: '5.7.0'
// https://mvnrepository.com/artifact/org.springframework/spring-jms
compile group: 'org.springframework', name: 'spring-jms', version: '5.1.9.RELEASE'
}
- resources中新建producer.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--生产者和消费者都需要用到的-start-->
<!--配置包扫描路径-->
<context:component-scan base-package="com.caihao.activemqdemo.producer"/>
<context:component-scan base-package="com.caihao.activemqdemo.consumer"/>
<!--ActiveMQ为我们提供的ConnectionFactory-->
<bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:61616"/>
</bean>
<!--spring jms 为我们提供的连接池,这个connectionFactory也是下面的jmsTemplate要使用的,
它其实就是对activeMQ的ConnectionFactory的一个封装-->
<bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<property name="targetConnectionFactory" ref="targetConnectionFactory"/>
</bean>
<!--提供一个队列模式的目的地,点对点的-->
<bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
<!--目的地队列的名字-->
<constructor-arg value="queue-demo"/>
</bean>
<!--生产者和消费者都需要用到的-end-->
<!--生产者所需要的-start-->
<!--配置jmsTemplate用于发送消息-->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
<!--生产者所需要的-end-->
<!--消费者所需要的start-->
<!--配置消息监听器1,即消息的消费者-->
<bean id="queueListener1" class="com.caihao.activemqdemo.consumer.QueueListener1"/>
<!--配置消息容器1-->
<bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<!--指定连接工厂-->
<property name="connectionFactory" ref="connectionFactory"/>
<!--指定消息目的地-->
<property name="destination" ref="queueDestination"/>
<!--指定消息监听器-->
<property name="messageListener" ref="queueListener1"/>
</bean>
<!--配置消息监听器2,即消息的消费者-->
<bean id="queueListener2" class="com.caihao.activemqdemo.consumer.QueueListener2"/>
<!--配置消息容器2-->
<bean id="jmsContainer2" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<!--指定连接工厂-->
<property name="connectionFactory" ref="connectionFactory"/>
<!--指定消息目的地-->
<property name="destination" ref="queueDestination"/>
<!--指定消息监听器-->
<property name="messageListener" ref="queueListener2"/>
</bean>
<!--消费者所需要的end-->
</beans>