activeMQ 使用

IDEA 创建 SpringBoot 项目,因为 SpringBoot 已经内置了对 ActiveMQ 的支持,所以直接引入依赖 spring-boot-starter-activemq 就行。

1.引入依赖

<!--activeMq 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<!--消息队列连接池-->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>5.15.0</version>
</dependency>

2.配置yaml文件

spring:
  # activeMq 配置
  activemq:
    broker-url: tcp://localhost:61616
    user: admin
    password: admin
    pool:
      # 使用flase,此处改为true报错,不清楚什么原因
      enabled: false
      max-connections: 10
#配置队列名
queueName: publish.queue
topicName: publish.topic

3.定义jms消息发送配置类,该类主要用于配置队列信息

ActiveMQConfig

package com.ry.bill.sys.config;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;

import javax.jms.Queue;
/**
 * @author CKFuture
 * @since 2021-01-02 15:45
 * @descrption ActiveMQ 配置类
 */
@EnableJms
@Configuration
public class ActiveMQConfig {
    @Bean
    public Queue queue() {
        return new ActiveMQQueue("sms.queue");
    }
}

 4.生产者

@Component
public class Producer {
    @Resource
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Resource
    private Queue queue;
    public void sendMsg(String msg) {
        System.out.println("发送消息内容 :" + msg);
        this.jmsMessagingTemplate.convertAndSend(this.queue, msg);
    }
}

5.消费者

@Component
public class Consumer {
    @JmsListener(destination = "sms.queue")
    public void receiveMsg(String text) {
        System.out.println("接收到消息 : "+text);
    }
}

6.测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class ActiveMqTests {
    @Autowired
    private Producer producer;    @Test
    public void sendSimpleQueueMessage() {        this.producer.sendMsg("提现200.00元");
    }
}

 

posted @ 2021-08-02 14:55  创客未来  阅读(154)  评论(0编辑  收藏  举报