Spring Boot的JMS发送和接收队列消息,基于ActiveMQ
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import javax.jms.JMSException;
import javax.jms.TextMessage;
@Component
public class JMSReceiver {
@JmsListener(destination = "your.queue.name", containerFactory = "jmsListenerContainerFactory")
public void receiveMessage(TextMessage message) throws JMSException {
System.out.println("Received message: " + message.getText());
}
}
在上述代码中,我们定义了一个JMSReceiver
组件,它使用@JmsListener
注解来监听指定的队列。每当有消息到达该队列时,receiveMessage
方法将被自动调用,并打印出接收到的消息内容。
确保在application.properties
或application.yml
中配置了ActiveMQ的连接信息,例如:
# application.properties
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin
或者在YAML格式的配置文件中:
# application.yml
spring:
activemq:
broker-url: tcp://localhost:61616
user: admin
password: admin
以及JMS监听容器工厂配置:
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
@Configuration
public class JMSConfig {
@Bean
public ActiveMQConnectionFactory connectionFactory() {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
connectionFactory.setBrokerURL("tcp://localhost:61616");
connectionFactory.setUserName("admin");
connectionFactory.setPassword("admin");
return connectionFactory;
}
@Bean
public JmsListenerContainerFactory<?> jmsListenerContainerFactory(ActiveMQConnectionFactory connectionFactory) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setConcurrency("1-10");
return factory;
}
}
在这个配置中,我们定义了一个JmsListenerContainerFactory
,它使用了我们提供的ActiveMQ连接工厂。这样,我们就可以在@JmsListener
注解中引用这个工厂来配置消息监听器了。
评论已关闭