ActiveMQ 入门例子[通俗易懂]

ActiveMQ 入门例子[通俗易懂]一:新建Maven项目,加入如下依赖 org.apache.activemq activemq-all 5.11.1二:server(嵌入式,无需下载安装activemq)packagecom.lala.mq;importjava.util.concurrent.TimeUnit;importorg.apache.activemq.broker.B

大家好,欢迎来到IT知识分享网。

一:新建Maven项目,加入如下依赖

<dependency>
	<groupId>org.apache.activemq</groupId>
	<artifactId>activemq-all</artifactId>
	<version>5.11.1</version>
</dependency>

IT知识分享网

二:

server(嵌入式,无需下载安装activemq)

IT知识分享网package com.lala.mq;

import java.util.concurrent.TimeUnit;

import org.apache.activemq.broker.BrokerService;

public class Server 
{
	public static void main(String[] args)throws Exception
	{
		BrokerService broker = new BrokerService();
		broker.addConnector("tcp://127.0.0.1:55551");
		broker.setUseJmx(false);
		broker.start();
		TimeUnit.SECONDS.sleep(9999);
	}
}

Producer(生产者)

package com.lala.mq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class MyProducer
{
	public static void main(String[] args) throws Exception
	{
		ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://127.0.0.1:55551");
		
		Connection conn = cf.createConnection();
		
		conn.start();
		
		Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
		
		Queue queue = session.createQueue("cib");
		
		MessageProducer producer = session.createProducer(queue);
		
		TextMessage tm = null;
		
		for(int i=1;i<=5;i++)
		{
			tm = session.createTextMessage("this is test message and msgid = " + i);
			producer.send(tm);
		}
		
		session.close();
		
		conn.close();
	}
}

Consumer(消费者)

IT知识分享网package com.lala.mq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class MyConsumer 
{
	public static void main(String[] args)throws Exception
	{
		ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://127.0.0.1:55551");
		
		Connection conn = cf.createConnection();
		
		conn.start();
		
		Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
		
		Queue queue = session.createQueue("cib");
		
		MessageConsumer consumer = session.createConsumer(queue);
		
		consumer.setMessageListener((message) -> {
			TextMessage tm = (TextMessage)message;
			try {
				System.out.println("收到消息:" + tm.getText());
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
	}
}

三:运行

先运行:Server

再运行:Consumer

最后运行:Producer

即可看到输出

最后

注意:以上做法不需要事先下载安装activemq服务

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/7109.html

(0)
上一篇 2023-01-03 09:52
下一篇 2023-01-03 09:52

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信