Java中使用ActiveMQ步骤

1.在maven中导入ActiveMQ相关包
<dependency>
 		<groupId>org.apache.activemq</groupId>
  		<artifactId>activemq-all</artifactId>
  		<version>5.14.0</version>
 </dependency>

步骤:

  1. 连接工厂ActiveMQConnectionFactory,使用默认的用户名,密码等
  2. 通过工厂,创建一个连接Connection
  3. 通过连接,创建一个Session
  4. 创建队列(Queue)或者话题(Topic)对象
  5. 创建消息的生产者或者消费者
  6. 发送或者接收消息
  7. 提交操作 session.commit();
2.编写MQ消息生产者

代码展示

package activemq;

import java.util.concurrent.atomic.AtomicInteger;

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.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.objenesis.instantiator.basic.NewInstanceInstantiator;

public class Producer {

	 // Activemq的默认用户名
	 private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
	 // Activemq的默认密码
	 private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
	 // Activemq的连接地址
	 private static final String BROKEN_URL = ActiveMQConnection.DEFAULT_BROKER_URL;
	 
	 //连接工厂
	 ConnectionFactory connectionFactory;
	 //连接对象
	 Connection connection;
	 // 事物
	 Session session;
	 
	 AtomicInteger count = new AtomicInteger(0);
	 
	 // ThreadLocal保存某个线程共享变量,对于同一个ThreadLocal,
	 //不同线程只能从中get,set,remove自己的变量,而不会影响其他线程的变量
	 ThreadLocal<MessageProducer> threadLocal = new ThreadLocal<MessageProducer>();
	 
	 // 初始化
	 public void init(){
		 try{
			 // 创建一个连接工厂
			 connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKEN_URL);
			 // 创建一个连接
			 connection = connectionFactory.createConnection();
			 // 开启连接
			 connection.start();
			 // 第一个参数,是否使用事物,如果设置为true,操作消息队列之后,必须使用session.commit()
			 // 第二个参数 消息接收方式  此处使用自动接收
			 session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
			 
			 
		 }catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	 }
	 
	 public void sendMessage(String disName){
		 try {
			// 创建一个消息队列
			 Queue queue = session.createQueue(disName);
			 //消息生产者
			 MessageProducer producer = null;
			 if(threadLocal.get()!=null){
				 producer = threadLocal.get();
			 }else{
				 producer = session.createProducer(queue);
			 }
			 for(int i=0;i<3;i++){
				 Thread.sleep(1000);
				 int num = count.getAndIncrement();
				 TextMessage textMessage = session.createTextMessage("生产消息"+num);
				 System.out.println(textMessage.getText());
				 producer.send(textMessage);
				 session.commit();
				 
			 }
			 
			 
		} catch (Exception e) {
			// TODO: handle exception
		}
	 }
	 
}
2.编写MQ消息消费者
package activemq;

import java.util.concurrent.atomic.AtomicInteger;

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

import org.apache.activemq.ActiveMQConnectionFactory;

public class Consumer {

	private static final String USERNAME = ActiveMQConnectionFactory.DEFAULT_USER;
	
	private static final String PASSWORD = ActiveMQConnectionFactory.DEFAULT_PASSWORD;
	
	private static final String BROKER_URL = ActiveMQConnectionFactory.DEFAULT_BROKER_URL;
	
	//创建工厂
	ConnectionFactory connectionFactory;
	//创建连接
	Connection connection;
	//创建事务
	Session session;
	
	ThreadLocal<MessageConsumer> threadLocal = new ThreadLocal<MessageConsumer>();
	AtomicInteger count = new AtomicInteger(0);
	
	public void init(){
		
		try {
			connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_URL);
			connection = connectionFactory.createConnection();
			connection.start();
			session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);

		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	public void getMessage(String queueName){
		try {
			Queue queue = session.createQueue(queueName);
			MessageConsumer consumer = null;
			if(threadLocal.get()!= null){
				consumer = threadLocal.get();
			}else{
				consumer = session.createConsumer(queue);
				threadLocal.set(consumer);
			}
			
			while(true){
				Thread.sleep(1000);
				TextMessage message = (TextMessage) consumer.receive();
				if(message!=null){
					System.out.println("消费消息"+message);
				}
				
			}
			
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
3.测试发送消息
package activemq;

public class TestProducer {

	public static void main(String[] args) {
		Producer producer = new Producer();
		producer.init();
		
		//TestProducer testProducer = new TestProducer();
		try {
			producer.sendMessage("queueName");
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
}

运行结果图:
在这里插入图片描述

4.测试接收消息
package activemq;

public class TestConsumer {

	public static void main(String[] args) {
		Consumer consumer = new Consumer();
		consumer.init();
		
		try {
			//Thread.sleep(1000);
			consumer.getMessage("queueName");
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

运行结果图:
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值