spring jms同步消息处理

本文介绍了在Spring框架中使用JMSTemplate进行同步消息处理的方法,详细讲解了如何配置及利用Activemq实现消息的封装和处理。
摘要由CSDN通过智能技术生成

spring框架中直接封装了jms的处理。在处理jms消息时会更加方便。spring处理同步消息时采用的JMSTemplate的方法。

配置文件如下,封装activemq的方法:

<!-- 请求响应连接池 -->
<bean id="connectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">  
    	<property name="connectionFactory">  
        	<bean class="org.apache.activemq.ActiveMQConnectionFactory">  
            	<property name="brokerURL" value="${dld.client.service.activemq.url}" />  
            	<property name="userName" value="${dld.client.service.activemq.user}"></property>
            	<property name="password" value="${dld.client.service.activemq.password}"></property>
        	</bean>  
    	</property>
    	<property name="maxConnections" value="${dld.client.activemq.pool.maxConnections}"></property>
        <property name="maximumActive" value="${dld.client.activemq.pool.maximumActive}"></property>
        <property name="idleTimeout" value="${dld.client.activemq.pool.idleTimeout}"></property> 
</bean>  
	
<!-- 目标地址 -->
<bean id="requestDestination" class="org.apache.activemq.command.ActiveMQQueue">  
    	<constructor-arg index="0" value="${dld.client.activemq.service.request}" />  
</bean> 
	
<!-- 响应地址 -->
<bean id="replyDestination" class="org.apache.activemq.command.ActiveMQQueue">  
    	<constructor-arg index="0" value="${dld.client.activemq.service.response}" />  
</bean>  
	
<!-- 连接池模板 -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
    	<property name="connectionFactory">  
        	<ref bean="connectionFactory" />  
    	</property>  
</bean>
同步接收的代码如下,因为需要对接收到的消息进行处理,所以重写的jmsTemplate的execute方法
//序列化成String,全部通过CommMessage传递
CommMessage commMessage = new DefaultCommMessage(request.getService(), request, CommMessageType.DATA_REQUEST);
String requestText = this.requestTransformer.doTransformer(commMessage);
logger.debug(" request text [" + requestText + "]");
//响应数据
Message replyMessage = template.execute(new ProducerConsumer(requestText, this.requestDestination, this.replyDestination, this.timeout, this.timeToLive), true );
if (replyMessage == null) {
	 logger.error(" response consumer timeout ");
	 response.setReturnMessage(" web client [" + request.getService() + "] error, exception-message=request timeout !!!");
} else if (replyMessage instanceof TextMessage) {
	TextMessage objMessage = (TextMessage)replyMessage;
	if (objMessage.getText() == null || "".equals(objMessage.getText().trim())) {
		response.setReturnMessage(" response message is null ");
	} else {
}
ProducerConsumer方法如下

public class ProducerConsumer implements SessionCallback<Message> {

	private Logger logger = LoggerFactory.getLogger(ProducerConsumer.class);
	private final String serializable;
	private long timeout = 30000;
	private long timeToLive = 30000;
	//请求地址
	private final Destination requestDestination;
	//响应地址
	private final Destination replyDestination;
	
	public ProducerConsumer( final String serializable, final Destination requestDestination, final Destination replyDestination, final long timeout, final long timeToLive) {
		this.serializable = serializable;
		this.requestDestination = requestDestination;
		this.replyDestination = replyDestination;
		this.timeout = timeout;
		this.timeToLive = timeToLive;
	}
	//实现接口,响应返回消息
	public Message doInJms( final Session session ) throws JMSException {
		//接收消息
		MessageConsumer consumer = null;
		//生产消息
		MessageProducer producer = null;
		try {
			final String correlationId = InetAddress.getLocalHost().getHostName() + "-" + UUID.randomUUID().toString() ;
			//响应的目标地址
			//Destination replyDestination = session.createTemporaryQueue();
			logger.debug(" correlation id " + correlationId + " request destination " + this.requestDestination + " replay destination " + replyDestination);
			//响应消息
			consumer = session.createConsumer(replyDestination, "JMSCorrelationID = '" + correlationId + "'");
			//创建消息
			TextMessage message = session.createTextMessage();
			
			//message.setJMSReplyTo(replyDestination);
	    	message.setText(serializable);
	    	message.setJMSCorrelationID( correlationId );
	    	message.setStringProperty(CommMessageType.REQUEST_CHANNEL, "fe");
	    	message.setStringProperty(CommMessageType.REPLY_TYPE, ReplyType.STRING);
	    	//设置消息时间
	    	//message.setJMSTimestamp(System.currentTimeMillis());
	    	//message.setJMSExpiration(this.timeToLive);
	    	message.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
	    	//创建生产者
	    	producer = session.createProducer( requestDestination );
	    	//发送消息
	    	producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
	    	producer.setTimeToLive(this.timeToLive);
	    	producer.send(message);
	    	
	    	//等待响应消息
	    	return consumer.receive( this.timeout );
		} catch (Exception e) {
			logger.error("system error ", e);
			if (e instanceof JMSException) {
				throw (JMSException)e;
			}
			throw new JMSException(e.getMessage());
		} finally {
			JmsUtils.closeMessageConsumer( consumer );
			
            JmsUtils.closeMessageProducer( producer );
		}
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值