1. 官网下载ActiveMQ包,官网地址:Index of /dist/activemq
这里讲述的是apache-activemq-5.16.4这个版本,版本请勿随意使用,其与JDK有相互依赖关系,如下图:
2. 解压使用
2.1 将下载好的包解压到本地磁盘:
2.2 启动并访问。进入bin文件夹,双击打开“activemq.bat”。
如遇到打开“activemq.bat”黑框一闪而过时,请用命令方式启动。启动命令:
activemq-admin.bat start
浏览器访问:http://127.0.0.1:8161/,用户名和密码都是admin
3. 依赖引入
pom.xml增加相关依赖
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-spring</artifactId>
<version>5.16.4</version>
</dependency>
4. 相关代码
Constant.java
/**
* 常量类
*/
public class Constant {
public static String USER = "admin";
public static String PASSWORD = "admin";
public static String URL = "failover://tcp://127.0.0.1:61616";
public static String SUBJECT = "XXX-MSG";
}
MsgTypeEnum.java
public enum MsgTypeEnum {
TEXT("text", "文本信息"),
// MAP("map", "Map信息"),
// STREAM("stream", "流信息"),
OBJECT("object", "对象信息"),
BYTES("byte", "字节信息");
public String key;
public String value;
/**
* 创建一个新的实例MsgTypeEnum.
*
* @param key
* @param value
*/
MsgTypeEnum(String key, String value) {
this.key = key;
this.value = value;
}
}
MqMessage.java
import lombok.Data;
import java.io.Serializable;
@Data
public class MqMessage implements Serializable {
/**
* 序列化ID
*/
private static final long serialVersionUID = 7543452786622377175L;
private String name;
private Integer id;
}
MqSender.java
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.io.Serializable;
/**
* 发送mq消息
*/
public class MqSender {
private Destination destination = null;
private Connection conn = null;
private Session session = null;
private MessageProducer producer = null;
/**
* 获取conn
*
* @return conn conn
*/
public Connection getConn() {
return conn;
}
/**
* 初始化
*
* @throws Exception
*/
public void initialize() throws Exception {
// 连接工厂
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(Constant.USER, Constant.PASSWORD, Constant.URL);
conn = connectionFactory.createConnection();
// 事务性会话,自动确认消息
session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 消息的目的地(Queue/Topic)
destination = session.createQueue(Constant.SUBJECT);
// destination = session.createTopic(SUBJECT);
// 消息的提供者(生产者)
producer = session.createProducer(destination);
// 不持久化消息
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
public void sendMessage(MsgTypeEnum msgTypeEnum, Object msgObject) throws Exception {
initialize();
// 连接到JMS提供者(服务器)
conn.start();
switch (msgTypeEnum) {
// 发送字节消息
case BYTES:
BytesMessage msg2 = session.createBytesMessage();
msg2.writeBytes(msgObject.toString().getBytes());
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
producer.send(msg2);
break;
// 发送Map消息
// case MAP:
// MapMessage msg = session.createMapMessage();
// msg.setBoolean("boolean", true);
// msg.setShort("short", (short) 0);
// msg.setLong("long", 123456);
// msg.setString("MapMessage", "ActiveMQ Map Message!");
// producer.send(msg);
// break;
// 发送对象消息
case OBJECT:
ObjectMessage msg12 = session.createObjectMessage();
msg12.setObject((Serializable) msgObject);
producer.send(msg12);
break;
// 发送流消息
// case STREAM:
// StreamMessage msg1 = session.createStreamMessage();
// msg1.writeBoolean(false);
// msg1.writeLong(1234567890);
// producer.send((StreamMessage) msg1);
// break;
// 发送文本消息
case TEXT:
TextMessage msg11 = session.createTextMessage();
msg11.setText((String) msgObject);
producer.send(msg11);
break;
default:
break;
}
close();
}
/**
* 关闭连接
*
* @throws JMSException
*/
public void close() throws JMSException {
if (producer != null) {
producer.close();
}
if (session != null) {
session.close();
}
if (conn != null) {
conn.close();
}
}
}
MqAccept.java
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.util.Enumeration;
/**
* 接收mq消息
*/
public class MqAccept implements MessageListener {
private Destination dest = null;
private Connection conn = null;
private Session session = null;
private MessageConsumer consumer = null;
private boolean stop = false;
/**
* 初始化
*
* @throws Exception
*/
private void initialize() throws Exception {
// 连接工厂是用户创建连接的对象.
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(Constant.USER, Constant.PASSWORD, Constant.URL);
// 连接工厂创建一个jms connection
conn = connectionFactory.createConnection();
// 是生产和消费的一个单线程上下文。会话用于创建消息的生产者,消费者和消息。会话提供了一个事务性的上下文。
session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); // 不支持事务
// 目的地是客户用来指定他生产消息的目标还有他消费消息的来源的对象.
dest = session.createQueue(Constant.SUBJECT);
// dest = session.createTopic(SUBJECT);
// 会话创建消息的生产者将消息发送到目的地
consumer = session.createConsumer(dest);
}
/**
* 消费消息
*
* @throws JMSException
* @throws Exception
*/
public void startReceiveMessage() throws JMSException, Exception {
initialize();
conn.start();
consumer.setMessageListener(this);
// 等待接收消息
while (!stop) {
Thread.sleep(5000);
}
}
@SuppressWarnings("rawtypes")
@Override
public void onMessage(Message msg) {
try {
if (msg instanceof TextMessage) {
TextMessage message = (TextMessage) msg;
System.out.println("------Received TextMessage------");
System.out.println(message.getText());
} else if (msg instanceof MapMessage) {
MapMessage message = (MapMessage) msg;
System.out.println("------Received MapMessage------");
System.out.println(message.getLong("long"));
System.out.println(message.getBoolean("boolean"));
System.out.println(message.getShort("short"));
System.out.println(message.getString("MapMessage"));
System.out.println("------Received MapMessage for while------");
Enumeration enumer = message.getMapNames();
while (enumer.hasMoreElements()) {
Object obj = enumer.nextElement();
System.out.println(message.getObject(obj.toString()));
}
} else if (msg instanceof StreamMessage) {
StreamMessage message = (StreamMessage) msg;
System.out.println("------Received StreamMessage------");
System.out.println(message.readString());
System.out.println(message.readBoolean());
System.out.println(message.readLong());
} else if (msg instanceof ObjectMessage) {
System.out.println("------Received ObjectMessage------");
ObjectMessage message = (ObjectMessage) msg;
MqMessage mqMessage = (MqMessage) message.getObject();
System.out.println("name: " + mqMessage.getName());
} else if (msg instanceof BytesMessage) {
System.out.println("------Received BytesMessage------");
BytesMessage message = (BytesMessage) msg;
byte[] byteContent = new byte[1024];
int length = -1;
StringBuffer content = new StringBuffer();
while ((length = message.readBytes(byteContent)) != -1) {
content.append(new String(byteContent, 0, length));
}
System.out.println(content.toString());
} else {
System.out.println(msg);
}
stop = true;
} catch (JMSException e) {
e.printStackTrace();
}
}
/**
* 关闭连接
*
* @throws JMSException
*/
public void close() throws JMSException {
System.out.println("Consumer:->Closing connection");
if (consumer != null) {
consumer.close();
}
if (session != null) {
session.close();
}
if (conn != null) {
conn.close();
}
}
}
MQSendMsg.java
public class MQSendMsg {
public static void sendMsg(MsgTypeEnum type, Object msgObj) throws Exception {
MqSender sender = new MqSender();
// 连接到JMS提供者(服务器)
sender.initialize();
sender.getConn().start();
sender.sendMessage(type, msgObj);
sender.close();
}
}
5. 测试代码
TestReceive.java
public class TestReceive {
public static void main(String[] args) throws Exception {
new MqAccept().startReceiveMessage();
}
}
TestSend.java
public class TestSend {
public static void main(String[] args) throws Exception {
MQSendMsg.sendMsg(MsgTypeEnum.TEXT, "这是测试哈123...");
}
}
测试发送接收功能
文章来源:https://www.toymoban.com/news/detail-437717.html
基础使用到此结束!文章来源地址https://www.toymoban.com/news/detail-437717.html
到了这里,关于Windows下ActiveMQ的安装和简单使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!