码迷,mamicode.com
首页 > 其他好文 > 详细

ActiveMQ 入门例子

时间:2015-08-02 21:46:24      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:activemq

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

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

二:

server

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

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服务


版权声明:本文为博主原创文章,未经博主允许不得转载。

ActiveMQ 入门例子

标签:activemq

原文地址:http://blog.csdn.net/mn960mn/article/details/47209537

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!