由于在项目中要用于MQ,但是如果独立安装一下MQ不太适合服务的迁移,因此决定采用内嵌的方式进行整全ACTIVEMQ
具体步骤如下:
1、在新建的SpringBoot项目中的POM文件下引入如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-spring</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-kahadb-store</artifactId>
</dependency>
2、在资源(resources)目录下加入activemq.xml配置文件。配置文件内容如下
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">
<broker xmlns="http://activemq.apache.org/schema/core"
brokerName="mybroker" useJmx="true">
<!--指定持久化 -->
<persistenceAdapter>
<kahaDB directory="./kahadb" />
</persistenceAdapter>
<!--指定连接 -->
<transportConnectors>
<transportConnector name="openwire"
uri="tcp://0.0.0.0:61616?maximumConnections=1000&wireFormat.maxFrameSize=104857600" />
</transportConnectors>
</broker>
</beans>
3、编写ACTIVEMQ相关代码。在启动类中加入如下代码
@Bean
public BrokerFactoryBean activemq() throws Exception {
BrokerFactoryBean broker = new BrokerFactoryBean();
ClassPathResource res = new ClassPathResource("activemq.xml");
broker.setConfig(res);
broker.setStart(true);
return broker;
}
在具体业务中使用如下代码:
@Autowired
private JmsTemplate jmsTemplate;
// 生产者,启动应用后自动发送10条消息
@Bean
public CommandLineRunner testSend() {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
for (int i = 0; i < 10; ++i) {
jmsTemplate.convertAndSend("test", "message");
}
}
};
}
// 消费者1
@JmsListener(destination = "test")
public void receive1(String message) {
System.out.println("One Receive: " + message);
}
// 消费者2
@JmsListener(destination = "test")
public void receive2(String message) {
System.out.println("Two Receive: " + message);
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}