Spring Boot 整合 ActiveMQ

1. ActiveMQ 部署

1.1 下载

http://www.apache.org/dyn/closer.cgi?filename=/activemq/5.15.4/apache-activemq-5.15.4-bin.tar.gz&action=download

http://www.apache.org/dyn/closer.cgi?filename=/activemq/5.15.4/apache-activemq-5.15.4-bin.zip&action=download

1.2 命令

activeMQ 目录下的 bin 文件夹执行

#前段运行
./activemq console

#后台运行
./activemq start

#前段关闭
ctrl + c

#后端关闭
./activemq stop

#访问地址
http://localhost:8161/admin

#默认账号密码
user=admin
password=admin

点击 ‘Queues‘ Tab 页
点击 ‘create‘ 创建一个队列(这里我创建了一个 queue-test 的队列)

1.3 Spring Boot 添加依赖

        <!-- mq -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-client</artifactId>
        </dependency>

1.4 配置属性

配置 activeMQ 属性,用 application.xml 和 application.yml 都可以。这里我使用的是更简洁的 application.yml。

spring:
    activemq:
      broker-url: tcp://127.0.0.1:61616
      user: admin
      password: admin
      in-memory: true

1.5 消息定义

定义 JMS 发送的消息需要实现 MessageCreator 接口,并重写其 createMessage 方法。

public class Msg implements MessageCreator {

    @Override
    public Message createMessage(Session session) throws JMSException {
        return session.createTextMessage("hello world");
    }
}

1.6 消息发送及目的地定义

注入 Spring Boot 为我们配置好的 JmsTemplate 的 Bean。

@RestController
public class MsgController {

    @Autowired
    private JmsTemplate jmsTemplate;

    @RequestMapping("/send")
    public Object sned() {
        // 设置需要发送到的队列名和要发送的消息
        // 通过 JmsTemplate 的 send 方法向 queue-test 目的地发送 Msg 的消息
        // 这里也等于在消息代理上定义了一个目的地叫 queue-test。
        jmsTemplate.send("queue-test",new Msg());
        return "success";
    }
}

1.7 消息监听

@JmsListener 是 Spring 4.1 为我们提供的一个新特性,用来简化 jms 开发。我们只需要在这个注解的属性 destination 指定要监听的目的地,即可接收该目的地发送的消息。此例监听 queue-test 目的地发送的消息。


@Component
public class Receiver {

    @JmsListener(destination = "queue-test")
    public void receiveMessage(String message) {
        System.out.println("接收到消息===》" + message);
    }
}

若博客中有错误或者说的不好,请勿介意,仅代表个人想法。
csdn博客:https://blog.csdn.net/LNView
本文地址:https://blog.csdn.net/LNView/article/details/80778181

有问题或者喜欢的欢迎评论。

转载请注明出处!!!!!!

参考资料:
《Spring Boot 实战》

猜你喜欢

转载自blog.csdn.net/LNView/article/details/80778181