ActiveMQ结合Spring开发
Spring提供了对JMS的支持,需要添加Spring支持jms的包,如下:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.9.0</version>
</dependency>
在Spring的配置文件中,配置jmsTemplate,示例如下:
<bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
<property name="connectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>tcp://192.168.1.106:61679</value>
</property>
</bean>
</property>
<property name="maxConnections" value="100"></property>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="jmsFactory" />
<property name="defaultDestination" ref="destination" />
<property name="messageConverter">
<bean class="org.springframework.jms.support.converter.SimpleMessageConverter" />
</property>
</bean>
<bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg index="0" value="spring-queue" />
</bean>
queue消息发送:
@Autowired
private JmsTemplate jt = null;
public static void main(String[] args) {
ApplicationContext ctx = new
ClassPathXmlApplicationContext("applicationContext.xml");
SpringJMSClient ct = (SpringJMSClient)ctx.getBean("springJMSClient");
ct.jt.send(new MessageCreator() {
public Message createMessage(Session s) throws JMSException {
TextMessage msg = s.createTextMessage("Spring msg===");
return msg;
}
});
}
queue消息接收:
@Autowired
private JmsTemplate jt = null;
public static void main(String[] args) throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
SpringJMSReceiverClient ct =
(SpringJMSReceiverClient)ctx.getBean("springJMSReceiverClient");
String msg = (String)ct.jt.receiveAndConvert();
System.out.println("msg==="+msg);
}
ActiveMQ结合Spring开发最佳实践和建议
- Camel框架支持大量的企业集成模式,可以大大简化集成组件间的大量服务和复杂的消息流。而Spring框架更注重简单性,仅仅支持基本的最佳实践。
- Spring消息发送的核心架构是JmsTemplate,隔离了像打开、关闭Session和Producer的繁琐操作,因此应用开发人员仅仅需要关注实际的业务逻辑。但是JmsTemplate损害了ActiveMQ的PooledConnectionFactory对session和消息producer的缓存机制而带来的性能提升。
- 新的Spring里面,可以设置CachingConnectionFactory的sessionCacheSize ,或者干脆使用ActiveMQ的PooledConnectionFactory。
- 不建议使用JmsTemplate的receive()调用,因为在JmsTemplate上的所有调用都是同步的,这意味着调用线程需要被阻塞,直到方法返回,这对性能影响很大。
- 请使用DefaultMessageListenerContainer,它允许异步接收消息并缓存session和消息consumer,而且还可以根据消息数量动态的增加或缩减监听器的数量。