activeMQ嵌入Java代码的使用

初学amq,根据网上学习到的一些,整理了一下amq嵌入Java代码的使用,如有错误请指出。

 

首先需要导入两个jar包:

activemq-all-5.5.1.jar
slf4j-nop-1.4.3.jar

 

import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;

public class AmqManager {
	
	public static BrokerService broker = new BrokerService();
	private final static AmqManager amq = new AmqManager();
	/** 连接器 */
	private static Connection connection = null;
	/** 按队列名获取session */
	private static Map<String, Session> sessionMap = new ConcurrentHashMap<String, Session>();
	/** 按队列名称获取生产者对象 */
	private static Map<String, MessageProducer> producerMap = new ConcurrentHashMap<String, MessageProducer>();
	/** 按队列名称获取消费者对象 */
	private static Map<String, MessageConsumer> consumerMap = new ConcurrentHashMap<String, MessageConsumer>();
	
	private AmqManager(){};
	
	public static synchronized AmqManager getAMQ() throws Exception {
		return amq;
	}
	/**
	 * 获取连接器
	 * @param brokerUri
	 * @param clientID
	 * @return
	 * @throws Exception 
	 */
	public synchronized Connection initConnection(String brokerUri, String clientID) throws Exception {
		if (null == connection) {
			ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUri);
			connection = connectionFactory.createConnection();
			connection.setClientID(clientID);
			connection.start();
		}
		return connection;
	}
	
	/**
	 * 初始化生产者
	 * @param queueName
	 * @param acknowledgeMode
	 * @param deliveryMode
	 * @return
	 * @throws JMSException
	 */
	public MessageProducer initProducer(String queueName, int acknowledgeMode, int deliveryMode) throws JMSException {
		MessageProducer producer = null;
		if (connection != null) {
			Session session = connection.createSession(false, acknowledgeMode);
			Destination destination = session.createQueue(queueName);
			producer = session.createProducer(destination);
	        producer.setDeliveryMode(deliveryMode);
	        sessionMap.put(queueName, session);
	        producerMap.put(queueName, producer);
		}
		return producer;
	}
	
	/**
	 * 初始化消费者
	 * @param queueName
	 * @param acknowledgeMode
	 * @param deliveryMode
	 * @return
	 * @throws JMSException
	 */
	public MessageConsumer initConsumer(String queueName, int acknowledgeMode) throws JMSException {
		MessageConsumer consumer = null;
		if (connection != null) {
			Session session = connection.createSession(false, acknowledgeMode);
			Destination destination = session.createQueue(queueName);
			consumer = session.createConsumer(destination);
			consumerMap.put(queueName, consumer);
		}
		return consumer;
	}

	/**
	 * 接收消息
	 * @param consumer
	 * @throws JMSException
	 */
	public void getMessage(String queueName) throws JMSException
    {
	    MessageConsumer consumer = consumerMap.get(queueName);
	    while (true) {
	        TextMessage textMessage = (TextMessage) consumer.receive(100000);
	        if(textMessage != null){
	            System.out.println("收到消息:" + textMessage.getText());
	        }else {
	            System.out.println("接收消息异常");
	            break;
	        }
	    }
    }

	/**
	 * 发送消息
	 * @param queueName
	 * @param message
	 * @throws JMSException
	 */
	public void sendMessage(String queueName, String message) throws JMSException {
	    TextMessage msg = sessionMap.get(queueName).createTextMessage(message);
	    //msg.setStringProperty("sqlId", "comstar-market-data-feedhub");
	    producerMap.get(queueName).send(msg);
	}
	
	/**
	 * 发送消息
	 * @param queueName
	 * @param message
	 * @param headName
	 * @param headValue
	 * @throws JMSException
	 */
	public void sendMessage(String queueName, String message, String headName,
	                String headValue) throws JMSException {
		TextMessage msg = sessionMap.get(queueName).createTextMessage(message);
		msg.setStringProperty(headName, headValue);
		producerMap.get(queueName).send(msg);
	}

	/**
	 * 关闭session
	 * @param queueName
	 * @throws JMSException
	 */
	public void close(String queueName) throws JMSException {
		Session session = sessionMap.get(queueName);
		if (null != session) {
			session.close();
			sessionMap.remove(queueName);
			destroy();
		}
	}
	
	/**
	 * 销毁连接
	 * note:如果session都没有了,则销毁连接
	 * @throws JMSException
	 */
	private synchronized void destroy() throws JMSException {
		if (connection != null) {
			if (0 == sessionMap.size()) {
				connection.close();
				connection = null;
			}
		}
	}
	
	public synchronized static void initAMQ() {
		try {
			TransportConnector connector = new TransportConnector();
			connector.setUri(new URI("tcp://localhost:61616"));
			broker.addConnector(connector);
			broker.start();
		} catch (JMSException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void destoryAMQ() {
		try {
			//close("");
			broker.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		try {
			getAMQ();
			//BrokerService broker = new BrokerService();
			TransportConnector connector = new TransportConnector();
			connector.setUri(new URI("tcp://localhost:61616"));
			broker.addConnector(connector);
			broker.start();
			amq.initConnection("failover://tcp://localhost:61616", "cning");
			amq.initProducer("queue.test", Session.AUTO_ACKNOWLEDGE, DeliveryMode.NON_PERSISTENT);
			amq.initConsumer("queue.test", Session.AUTO_ACKNOWLEDGE);
			amq.sendMessage("queue.test", "hahahahahahahhahaha");
			amq.getMessage("queue.test");
			amq.destoryAMQ();
		} catch (JMSException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值