JMS用于系统间的异步通信,在将系统功能进行纵向拆分时,是很好的解决方案,通过消息驱动来实现业务分离。
消息中间件有很多,开源的有Apache的ActiveMQ,商业的有IBM MQ等,以下是基于ActiveMQ的spring配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:amq="http://activemq.apache.org/schema/core"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.2.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 将ActiveMQ内嵌到应用程序中
<amq:broker useJmx="false" persistent="true">
<amq:transportConnectors>
<amq:transportConnector uri="tcp://localhost:61616"/>
</amq:transportConnectors>
</amq:broker>
-->
<!-- 定义消息队列 -->
<amq:queue id="indexChannel" physicalName="SOLR.INDEX"/>
<!-- 定义连接工厂 -->
<amq:connectionFactory id="connectionFactory" brokerURL="tcp://localhost:61616"/>
<!--
<bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="maxConnections" value="100"/>
</bean>
-->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
<!-- 消息发送者 -->
<bean id="messageSender" class="org.chen.jms.MessageSender">
<property name="jmsTemplate">
<ref bean="jmsTemplate"/>
</property>
<property name="destination">
<ref bean="indexChannel"/>
</property>
</bean>
<!-- 定义消息监听器 -->
<bean id="indexListener" class="org.chen.jms.IndexListener"/>
<jms:listener-container concurrency="10" > <!-- concurrency指定最多可并发开启10个监听器 -->
<jms:listener id="listener" destination="SOLR.INDEX" ref="indexListener" />
</jms:listener-container>
</beans>
消息生产者代码如下:
public class MessageSender {
private JmsTemplate jmsTemplate;
private Destination destination;
public void send(Object message){
jmsTemplate.setDeliveryMode(DeliveryMode.PERSISTENT);
jmsTemplate.convertAndSend(destination,message);
}
public JmsTemplate getJmsTemplate() {
return jmsTemplate;
}
public void setJmsTemplate(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}
public Destination getDestination() {
return destination;
}
public void setDestination(Destination destination) {
this.destination = destination;
}
}
消息监听器代码如下:
public class IndexListener implements MessageListener {
@Override
public void onMessage(Message msg) {
ObjectMessage objMsg=(ObjectMessage) msg;
try {
Serializable obj=objMsg.getObject();
System.out.println(obj);
//TODO 处理独立出去的业务逻辑
} catch (JMSException e) {
e.printStackTrace();
}
}
}