Spring boot 整合 ActiveMQ 详细案例

一、搭建最基本的Spring Boot环境

二、添加依赖ActiveMQ依赖

xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.5.6.RELEASEversion>
    parent>


    <groupId>it.hehegroupId>
    <artifactId>itcate-spring-bootartifactId>
    <version>1.0-SNAPSHOTversion>

    
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-activemqartifactId>
        dependency>
    dependencies>
project>

三、设置 Broker

\src\main\resources\application.properties

添加 activeMQ 的配置项

# 配置 activeMQ 服务器信息
spring.activemq.broker-url=tcp://192.168.125.125:61616
四、发送消息创建MQController.java

package it.hehe.boot.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Author : H.Hai
 */
@RequestMapping("/mq")
@RestController
public class MQController {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @GetMapping("/send")
    public String sendMapMsg(){

        Map map=new HashMap<>();
        map.put("name","大壮");
        map.put("age","22");
        jmsMessagingTemplate.convertAndSend("spring_boot_map_queue",map);
        return "发送消息成功!";
    }
}

五、接收消息创建MessageListener.java

package it.hehe.boot.listener;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Author : H.Hai
 */
/*把普通pojo实例化到spring容器中,相当于配置文件中的*/
@Component
public class MessageListener {

    @JmsListener(destination = "spring_boot_map_queue")
    public void receiveMsg(Map map){
        System.out.println(map);
    }
}

六、运行测试

Spring boot 整合 ActiveMQ 详细案例_第1张图片

你可能感兴趣的:(Demo)