1.创建一个springboot项目pom.xm导入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
2.application.yml
server:
port: 8080
spring:
activemq:
broker-url: tcp://192.168.200.128:61616
user: admin
password: admin
jms:
pub-sub-domain: false #false = Queue true=Topic 默认false
#自定义队列名称
myqueue: boot-activemq-queue
3.配置Ben
package com.example.activemq.config;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.jms.Queue;
@Component
public class ActiveMqConfig {
@Value("${myqueue}")
private String myqueue;
@Bean
public Queue queue(){
return new ActiveMQQueue(myqueue);
}
}
4. QueueProduce生产者
package com.example.activemq.queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.jms.Queue;
import java.util.UUID;
@Component
@EnableJms
public class QueueProduce {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Queue queue;
public void produceMsg(){
jmsMessagingTemplate.convertAndSend(queue,"****:"+UUID.randomUUID().toString().substring(0,6));
}
//定时任务 3秒
@Scheduled(fixedDelay = 3000)
public void produceMsgScheduled(){
jmsMessagingTemplate.convertAndSend(queue,"****:"+UUID.randomUUID().toString().substring(0,6));
}
}
5.QueueConsumer消费着
package com.example.activemq.queue;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import javax.jms.TextMessage;
@Component
public class QueueConsumer {
@JmsListener(destination = "${myqueue}")
public void receive(TextMessage textMessage) throws Exception{
System.out.println("*******消费者接收到消息:"+textMessage.getText());
}
}
5.测试类
先启动springboot项目,在启动测试类
package com.example.activemq;
import com.example.activemq.queue.QueueProduce;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ActivemqDemoApplicationTests {
@Autowired
private QueueProduce queueProduce;
@Test
void contextLoads() {
queueProduce.produceMsg();
}
}