ActiveMQ结合Spring开发

                                      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开发最佳实践和建议

  1. Camel框架支持大量的企业集成模式,可以大大简化集成组件间的大量服务和复杂的消息流。而Spring框架更注重简单性,仅仅支持基本的最佳实践。
  2. Spring消息发送的核心架构是JmsTemplate,隔离了像打开、关闭Session和Producer的繁琐操作,因此应用开发人员仅仅需要关注实际的业务逻辑。但是JmsTemplate损害了ActiveMQ的PooledConnectionFactory对session和消息producer的缓存机制而带来的性能提升。
  3. 新的Spring里面,可以设置CachingConnectionFactory的sessionCacheSize ,或者干脆使用ActiveMQ的PooledConnectionFactory。
  4. 不建议使用JmsTemplate的receive()调用,因为在JmsTemplate上的所有调用都是同步的,这意味着调用线程需要被阻塞,直到方法返回,这对性能影响很大。
  5. 请使用DefaultMessageListenerContainer,它允许异步接收消息并缓存session和消息consumer,而且还可以根据消息数量动态的增加或缩减监听器的数量。
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值