SpringBoot整合MQ
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                Spring Boot整合MQ(以ActiveMQ为例),你可以使用Spring Boot的自动配置特性来简化配置过程。以下是一个基本的例子:
- 添加依赖到你的pom.xml:
<dependencies>
    <!-- Spring Boot Starter for ActiveMQ -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-activemq</artifactId>
    </dependency>
 
    <!-- Spring Boot Starter for Web (如果你需要用到Web) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>- 在application.properties或application.yml中配置ActiveMQ的连接信息:
# application.properties
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin- 创建一个配置类来发送和接收消息:
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import javax.jms.JMSException;
import javax.jms.TextMessage;
 
@Component
public class ActiveMQReceiver {
 
    @JmsListener(destination = "myQueue")
    public void receiveMessage(TextMessage message) throws JMSException {
        System.out.println("Received: " + message.getText());
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
 
@Service
public class ActiveMQSender {
 
    @Autowired
    private JmsTemplate jmsTemplate;
 
    public void sendMessage(String message) {
        jmsTemplate.convertAndSend("myQueue", message);
    }
}- 在你的启动类或者任意一个配置类中,添加@EnableJms注解启用JMS支持:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jms.annotation.EnableJms;
 
@SpringBootApplication
@EnableJms
public class MqApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(MqApplication.class, args);
    }
}- 使用ActiveMQSender发送消息,ActiveMQReceiver将会接收并打印消息。
确保ActiveMQ服务器正在运行,并且你的配置信息(如连接URL、用户名和密码)正确无误。这个例子展示了如何使用Spring Boot自动配置的JmsTemplate来发送和接收消息。
评论已关闭