spring boot 版本:2.2.1
activemq 版本: 5.15.10
1. pom文件
这里面的pooled-jms为了防止启动的时候出现错误:required a bean of type 'org.springframework.jms.core.JmsTemplate' that could not be found.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<!-- -->
<dependency>
<groupId>org.messaginghub</groupId>
<artifactId>pooled-jms</artifactId>
</dependency>
</dependencies>
2. 添加必要的yml 配置
spring:
activemq:
broker-url: tcp://localhost:61616
in-memory: true
pool:
enabled: true
jms:
# 默认情况下activemq提供的是queue模式,若要使用topic模式需要配置下面配置
pub-sub-domain: true
3. 添加消费者和生产者
// 消费者
@Component
public class ConsumerA {
@JmsListener(destination = "queue1")
public void queue1(String time) {
System.out.println("recive1 message from queue1 [" + time + "]");
}
}
// 生产者,放在测试类里面,方便调试
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProducerA {
/**
* 可以做更细微的控制
*/
@Autowired
private JmsTemplate jmsTemplate;
@Test
public void test1(){
for (int i = 0; i < 5; i++) {
// 使用convertAndSend发送消息
long time = System.currentTimeMillis();
System.out.println("send --> " + time);
jmsTemplate.convertAndSend("queue1", time);
}
}
}
4. 添加启动类
@SpringBootApplication
public class ActivemqDemo1 {
public static void main(String[] args) {
SpringApplication.run(ActivemqDemo1.class, args);
}
}
5. 执行测试方法运行结果
send --> 1575365397491
send --> 1575365397509
send --> 1575365397510
send --> 1575365397513
send --> 1575365397515
recive1 message from queue1 [1575365397491]
recive1 message from queue1 [1575365397509]
recive1 message from queue1 [1575365397510]
recive1 message from queue1 [1575365397513]
recive1 message from queue1 [1575365397515]