1.源码分析:
2.使用:
两个 springboot 项目分别作为消息提供者(provider)和消费者(consumer)
(1)在两个项目中的 application.properires 配置消息队列
(2)在提供者和消费者的启动类添加 @EnableJms 开启消息队列
// 1、提供者
@SpringBootApplication
@EnableJms //启动消息队列
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
// 2、消费者
@SpringBootApplication
@EnableJms //启动消息队列
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
@FunctionalInterface
public interface XAConnectionFactoryWrapper {
/**
* Wrap the specific {@link XAConnectionFactory} and enroll it with a JTA
* {@link TransactionManager}.
* @param connectionFactory the connection factory to wrap
* @return the wrapped connection factory
* @throws Exception if the connection factory cannot be wrapped
*/
ConnectionFactory wrapConnectionFactory(XAConnectionFactory connectionFactory) throws Exception;
}
3、服务提供者 provider
(1)配置类定义消息队列
import javax.jms.Queue;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JMSBean {
//定义存放消息的队列
@Bean
public Queue queue() {
return new ActiveMQQueue("activeMQQueue");
}
}
(2)ProviderController 发送消息
import javax.jms.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProviderController {
//注入存放消息的队列,用于下列方法一
@Autowired
private Queue queue;
//注入springboot封装的工具类
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@RequestMapping("send")
public void send(String name) {
//方法一:添加消息到消息队列
jmsMessagingTemplate.convertAndSend(queue, name);
//方法二:这种方式不需要手动创建queue,系统会自行创建名为test的队列
//jmsMessagingTemplate.convertAndSend("test", name);
}
}
推荐阅读:
https://blog.youkuaiyun.com/IT__learning/article/details/119868661