1.maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency>
2.properties.yml配置
spring: activemq: broker-url: tcp://ip:61616 user: admin password: admin queue: queue_name
3.创建一个队列
/** * 创建一个队列 */ @Configuration public class QueueConfig { @Value("${queue}") private String queueName; @Bean public Queue queue(){ return new ActiveMQQueue(queueName); } }
4.创建生产者
/** * 生产者 */ @Component @EnableScheduling public class Producer { @Autowired JmsMessagingTemplate jmsMessagingTemplate; @Autowired private Queue queue; private int i = 0; //定时器每隔5秒向activmq服务器发送一条消息 @Scheduled(fixedDelay = 5000) public void send(){ i ++; jmsMessagingTemplate.convertAndSend(queue, "第"+i+"条数据"); } }
5.创建消费者
/** * 消费者 */ @Component public class Consumer { @JmsListener(destination = "${queue}") public void receive(String msg){ System.out.println("消费者"+msg); } }
6.运行程序即可在控制台看到数据接收记录