spring jms异步消息处理

spring JMS对于异步消息处理基本上只需配置下就能进行高效的处理。其核心就是消息侦听器容器,常用的类就是DefaultMessageListenerContainer。该容器可配置侦听器的并发数量,以及配合MessageListenerAdapter使用消息驱动POJO进行消息处理。且消息驱动POJO是放入TaskExecutor中进行处理,进一步提高性能,减少侦听器的阻塞。具体配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
						   http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-2.5.xsd">

	<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>failover:(tcp://192.168.6.2:61616)</value>
				</property>
			</bean>
		</property>
	</bean>
	
	<bean id="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
		<property name="corePoolSize" value="5"/>
		<property name="maxPoolSize" value="20"/>
		<property name="queueCapacity" value="1000"/>
		<property name="threadNamePrefix" value="jmsTaskExecutor-"/>
		<property name="allowCoreThreadTimeOut" value="true"></property>
	</bean>
	
	<bean id ="testMessageListener" class="org.springframework.jms.listener.adapter.MessageListenerAdapter">
		<constructor-arg>
			<bean class="com.test.jms.TestMessageListener"/>
		</constructor-arg>
	</bean>

	<jms:listener-container concurrency="5-20" task-executor="threadPoolTaskExecutor" >
		<jms:listener destination="testqueue" ref="testMessageListener"/>
	</jms:listener-container>
	
	
	<bean id="jmsDestination" class="org.apache.activemq.command.ActiveMQQueue">
		<constructor-arg index="0" value="testqueue"></constructor-arg>
	</bean>
	
	<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
		<property name="connectionFactory" ref="connectionFactory"></property>
		<property name="defaultDestination" ref="jmsDestination"></property>
	</bean>
	
</beans>

而开发人员只要实现com.test.jms.TestMessageListener即可,且TestMessageListener可以是一个POJO(不过方法名参照MessageListener接口)。代码如下:
public class TestMessageListener {
	public void handleMessage(String message){
		System.out.println("text message:"+message);
	}
	
	public void handleMessage(Object message){
		System.out.println("object message:"+message+","+Thread.currentThread().getName());
	}
}

你可能感兴趣的:(jms)