spring消息发送的核心架构是JmsTemplate,隔离了像打开,关闭Session和Producer的繁琐操作,因此应用开发人员仅仅需要关注实际的业务逻辑。
不建议使用JmsTemplate的receive()调用,因为在JmsTemplate上的所有调用都是同步的,这意味着调用线程需要被阻塞,直到方法返回,这对性能影响很大。
建议使用监听器来做消息的接收,这个是异步的。
具体是使用DefalutMessageListenerContainer,它允许异步接收消息并缓存session和消息consumer,而且还可以根据消息数量动态的增加或者缩减监听器的数量。
增加maven依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.activemq/activemq-pool -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.9.0</version>
</dependency>
搞一下spring配置
<!--工厂类,jms规范第一步-->
<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://hadoop2:61616</value>
</property>
</bean>
</property>
<!--连接池的最大连接数-->
<property name="maxConnections" value="100"></property>
</bean>
<!--sping默认自己搞了个queue,后面的配置会用到-->
<bean id="defaultDestination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg index="0" value="spring-queue"></constructor-arg>
</bean>
<!--jmsTemplate-->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="jmsFactory"></property>
<property name="defaultDestination" ref="defaultDestination" />
<property name="messageConverter" >
<bean class="org.springframework.jms.support.converter.SimpleMessageConverter"></bean>
</property>
</bean>
写个producer
@Component("producerSpring")
public class ProducerSpring {
@Resource
JmsTemplate jmsTemplate;
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
ProducerSpring producer = (ProducerSpring)context.getBean("producerSpring");
producer.jmsTemplate.send(new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
TextMessage textMessage = session.createTextMessage();
textMessage.setText("hello spring-jms");
return textMessage;
}
});
}
}
写个consumer
@Component("consumerSpring")
public class ConsumerSpring {
@Resource
private JmsTemplate jmsTemplate;
public static void main(String[] args) throws JMSException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
ConsumerSpring consumer = (ConsumerSpring) context.getBean("consumerSpring");
while (true) {
//consumer.jmsTemplate.setReceiveTimeout(500);
Message message = consumer.jmsTemplate.receive("spring-queue");
if (message == null) break;
TextMessage textMessage = (TextMessage) message;
System.out.println("===" + textMessage.getText());
}
}
}
一般来说,不用直接写consumer,这个是同步的。要用异步的listener更好,代码以后补上。