转载请注明出处:http://blog.csdn.net/l1028386804/article/details/69046395
解决使用activemq时抛出的异常:javax.j ms.JMSException: Could not connect to broker URL
我使用的是spring jms和activemq结合,在配置文件中定义了普通的connectionFactory的bean,如下所示:
- <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
- <description>JMS连接工厂</description>
- <property name="brokerURL" value="tcp://192.168.50.131:61616" />
- </bean>
定义了上面的文件之后,在使用spring jms的JmsTemplate发送jms消息时,如果发送大量消息的话,有时候会抛出如下异常:org.springframework.jms.UncategorizedJmsException: Uncategorized exception occured during JMS
processing; nested exception is javax.jms.JMSException: Could not connect to broker
URL: tcp://192.168.50.131:61616. Reason: java.net.BindException: Address already in use: connect
at org.springframework.jms.support.JmsUtils.convertJmsAccessException(JmsUtils.java:316)
at org.springframework.jms.support.JmsAccessor.convertJmsAccessException(JmsAccessor.java:168)
at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:469)
at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:534)
at net.kentop.astoam.device.MG800DeviceService.excute(MG800DeviceService.java:423)
at net.kentop.astoam.device.MG800DeviceService$HandlerReceiveMessage.
handlerUdpData(MG800DeviceService.java:936)
at net.kentop.mon4mg.monitor.UDPReceiverThread.run(UDPReceiverThread.java:51)
Caused by: javax.jms.JMSException: Could not connect to broker URL: tcp://192.168.20.23:61616.
Reason: java.net.BindException: Address already in use: connect
at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:35)
at org.apache.activemq.ActiveMQConnectionFactory.
createActiveMQConnection(ActiveMQConnectionFactory.java:286)
at org.apache.activemq.ActiveMQConnectionFactory.
createActiveMQConnection(ActiveMQConnectionFactory.java:230)
at org.apache.activemq.ActiveMQConnectionFactory.
createConnection(ActiveMQConnectionFactory.java:178)
at org.springframework.jms.support.JmsAccessor.createConnection(JmsAccessor.java:184)
at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:456)
... 4 more
而且在运行的时候会增加很多activemq的线程,使得整个程序运行起来比较慢。通过观察,猜测主要原因是连接activemq时,没有使用池连接,导致每次发送jms消息时,用的不是同一个连接,而是创建一个新的连接,所以耗费很多系统资源,并且因为整个项目是多线程的,所以就会抛出如上面的异常。解决方法是将activemq的连接的bean定义为activemq的池连接定义,将配置文件中的connectionFactory的bean定义改为如下内容:- <bean id="connectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
- <property name="connectionFactory">
- <bean class="org.apache.activemq.ActiveMQConnectionFactory">
- <property name="brokerURL" value="tcp://192.168.50.131:61616" />
- </bean>
- </property>
- </bean>
修改之后重新运行程序,再测试。果然没有占用那么多资源,而且也不会抛出上面的异常了。注意:要使用activemq的池连接,必须在classpath中包含有activemq-pool.jar