jms连接方法及相关代码

1.队列信息配置

activemq.brokerurl=failover:(tcp://127.0.0.1:9418,tcp://127.0.0.1:9420,tcp://127.0.0.1:9422)?initialReconnectDelay=3000&timeout=3000&jms.connectResponseTimeout=3000&randomize=true
activemq.user=admin
activemq.pwsswd=admin

destination.queue=Consumer.im.VirtualTopic.SOA.TOPIC_DISTTASKENTRUSTSRV_SOA?consumer.prefetchSize=10

2.创建连接

package org.activemq.example;

import javax.jms.ConnectionFactory;
import javax.jms.Destination;

import org.activemq.example.listener.MQMessageListener;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
@Configuration
public class MQConfig {
	@Autowired
    private ApplicationContext appContext;
    @Value("${activemq.brokerurl}")
    private String brokerUrl;
    @Value("${activemq.user}")
    private String userName;
    @Value("${activemq.pwsswd}")
    private String passwd;
    @Value("${destination.queue}")
    private String queue;

    @Bean(name="demoQueueConnectionFactory")
    public ConnectionFactory demoQueueConnectionFactory() {
    	ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, passwd, brokerUrl);
    	return connectionFactory;
    }

    @Bean(name="demoQueueListenerContainer")
    public DefaultMessageListenerContainer demoQueueListenerContainer() {

    	DefaultMessageListenerContainer container =new DefaultMessageListenerContainer();
    	//连接工厂
    	ConnectionFactory connectionFactory = (ConnectionFactory) appContext.getBean("demoQueueConnectionFactory");
    	container.setConnectionFactory(connectionFactory);
    	//创建目的地
		Destination destination = new ActiveMQQueue(queue);

//        ActiveMQTopic activeMQTopic = new ActiveMQTopic(queue);

        container.setDestination(destination);
		//注册监听器
		container.setMessageListener(new MQMessageListener());
		return container;
    }


    public String getBrokerUrl() {
        return brokerUrl;
    }
    public void setBrokerUrl(String brokerUrl) {
        this.brokerUrl = brokerUrl;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }



}

3.监听文件

package org.activemq.example.listener;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JMS消息监听器
 * 通过consumer向activemq注册监听器,
 * 当有消息到达的时候,会回调onMessage()方法
 * @author houyongchuan
 *
 */
public class MQMessageListener implements MessageListener {
	private static final Logger logger = LoggerFactory.getLogger(MQMessageListener.class);

	@Override
	public void onMessage(Message message) {
		// 实例ID
		String instanceId = null;
		// 是否是重传消息,第一次收到消息为false,第二次收到为true
		boolean redelivered = false;
		// 重传次数,第一次收到消息为1
		int deliveryCount = 0;
		if (message != null) {
			try {
				// 实例号
				instanceId = message.getStringProperty("INSTANCE_ID");
				redelivered = message.getJMSRedelivered();
				// 传输次数
				deliveryCount = message.getIntProperty("JMSXDeliveryCount");
				// 消息创建时间
				long jmsTimestamp = message.getJMSTimestamp();
				long receiver = System.currentTimeMillis();
				long delay = receiver - jmsTimestamp;
				if (message instanceof TextMessage) {
					TextMessage textMsg = (TextMessage) message;
					String payload = textMsg.getText();
					logger.info(
							"接收到消息({}):\nINSTANCE_ID:{}\ndelay:{}ms\nredelivered:{}\ndeliveryCount:{}\npayload:{}",
							new Object[] {message.getJMSMessageID(), instanceId, delay, redelivered,
									deliveryCount, payload });
					// TODO 业务处理
					// .........
					//
//					 throw new RuntimeException("测试异常");
				} else {
					logger.warn("instanceId:{}, not a text message.", instanceId);
				}
			} catch (Exception e) {
				logger.error("instanceId:" + instanceId + ",错误信息:" + e.getMessage(), e);
				// TODO 异常处理
				// .........
				//
				// 如果需要该消息重传
				// DefaultMessageListenerContainer自动确认模式下,抛出异常,Container会自动确认,
				// DefaultMessageListenerContainer 客户端确认模式,抛出异常会重复消费
				// 抛出异常请慎重,抛出异常,消息会重传,如果该消息的一直处理异常,消息会一直重复消费
				// 可通过redelivered和deliveryCount属性值进行最大次数设置,如
				if (deliveryCount < 10) {
					throw new RuntimeException(e);
				} else {
					logger.error("retry {} times end.", deliveryCount);
				}
			}
		}

	}

}

:多跨域可能导致连接不上需要配置vm options(-Djava.net.preferIPv4Stack=true)

你可能感兴趣的:(java,服务器,开发语言)