package com.yu.mq.producer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQPrefetchPolicy;
import org.apache.log4j.Logger;
public class ActiveMqManager {
static Logger log = Logger.getLogger(ActiveMqManager.class);
public static Map<String, List<Object[]>> producerMqMap = new HashMap<String, List<Object[]>>();
public static List<Map<String, String>> failedMQList = new ArrayList<Map<String, String>>();
public static List<Map<String, String>> outMQList = new ArrayList<Map<String, String>>();
private String user = ActiveMQConnection.DEFAULT_USER;
private String password = ActiveMQConnection.DEFAULT_PASSWORD;
private String url = "";
public ActiveMqManager(String url) {
this.url = url;
}
/**
* 创建MQ连接
*/
public Connection connect() {
// 创建工厂
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
user, password, url);
// 设置消息预处理数量
ActiveMQPrefetchPolicy prefetchPolicy = connectionFactory
.getPrefetchPolicy();
prefetchPolicy.setAll(100);
connectionFactory.setPrefetchPolicy(prefetchPolicy);
Connection connection = null;
try {
// 建立链接
connection = connectionFactory.createConnection();
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
}
return connection;
}
/**
* 关闭MQ连接
*/
public void close(Connection connection) {
try {
if (connection != null) {
connection.close();
connection = null;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
}
}
/**
* 发送消息
*
* @param Session
* session mq会话
* @param MessageProducer
* producerMQ生产端
* @param MapMessage
* message mq消息对象
* @return
*/
public boolean sendMessage(Session session, MessageProducer producer,
Message message) {
boolean ret = false;
try {
long begin = System.currentTimeMillis();
producer.send(message);
long end = System.currentTimeMillis();
session.commit();
System.out.println("用了:" + (end - begin) + "毫秒");
ret = true;
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
try {
session.rollback();
} catch (JMSException e1) {
e1.printStackTrace();
}
}
return ret;
}
/**
* 创建Map消息对象
*
* @param Session
* session mq会话
* @return MapMessage mq消息对象
*/
public MapMessage getMapMessage(Session session) {
MapMessage message = null;
if (session != null) {
try {
message = session.createMapMessage();
} catch (JMSException e) {
e.printStackTrace();
log.error(e.getMessage(), e);
}
} else {
log.info("session为空!");
}
return message;
}
}