首先在服务器部署activemq并启动,开放端口,这个过程比较简单,不多做赘述
今天记录一下我学习的第一步,生产者生产队列(queue)消息
创建maven项目,pom文件需要的jar包内容:
<?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>xiaowu</groupId>
<artifactId>activemq</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.9</version>
</dependency>
<dependency>
<groupId>org.apache.xbean</groupId>
<artifactId>xbean-spring</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
接下来便是生产者生产消息的实现,分8步走
1.创建connection工厂
2.创建connection并启动
3.创建会话session
4.创建目的地queue
5.创建生产者producer
6.生成消息textMessage
7.生产者发送消息
8.关闭释放资源
package com.xiaowu.activemq;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import static javax.jms.Session.AUTO_ACKNOWLEDGE;
public class JmsProduce {
public static final String ACTIVEMQ_URL="tcp://152.136.12.27:61616";//服务器地址使用自己的
public static final String Queuep="queue01";
public static void main(String[] args) throws JMSException {
//1.create factory
ActiveMQConnectionFactory activeMQConnectionFactory=new ActiveMQConnectionFactory(ACTIVEMQ_URL);
//2.create connect and start
Connection connection=activeMQConnectionFactory.createConnection();
connection.start();
//3.create session,这里的方法有两个参数,一个是事务,一个是签收
Session session = connection.createSession(false, AUTO_ACKNOWLEDGE);
//4.create 目的地
Queue queue=session.createQueue(Queuep);
//5.create producer
MessageProducer messageProducer=session.createProducer(queue);
for(int i=0;i<3;i++){
//6.create message
TextMessage textMessage=session.createTextMessage("message---"+i);
//7.send massege
messageProducer.send(textMessage);
}
//8.释放资源
messageProducer.close();
session.close();
connection.close();
System.out.println("消息发送完毕");
}
}
运行,查看activemq服务器控制台
可以看到服务器接收到了队列消息