SpringBoot2.0与ActiveMQ整合(三)

Deadly 提交于 2019-11-27 16:00:18

使用内嵌服务

1、在pom.xml文件中引入以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-activemq</artifactId>
</dependency>

2、在文件下创建Producter和Consumer:
在这里插入图片描述
3、生产者Producter中的代码如下:

@RestController
public class Producter {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @RequestMapping("/send")
    public void sendMessage(String text) {
        jmsMessagingTemplate.convertAndSend("xhy",text);
    }
}

消费者Consumer代码如下:

@Component
public class Consumer {

    @JmsListener(destination = "xhy")
    public void receiveMessage(String text) {
        System.out.println("接收到消息"+text);
    }
}

4、测试:启动服务后,在浏览器执行如下:

http://localhost:8081/send?text=aaaa

使用外部服务

1、需要在操作系统上安装ActiveMQ,本次测试使用wind版,首先下载MQ的安装包:

http://activemq.apache.org/download.html

启动activeMq:我们用windows命令行模式启动,window + R,输入cmd打开命令窗口,进入到bin目录,然后运行如下启动命令:

activemq start

关闭:

 activemq stop

然后浏览器地址栏输入

http://localhost:8161/admin

默认用户名密码为admin、admin,这个用户名密码可以再conf/users.properties中自行修改配置;

2、启动成功后,在application.properties配置文件中配置如下内容:

spring.activemq.broker-url=tcp://localhost:61616

3、然后Producter中添加如下方法:

   @RequestMapping("/sendMap")
    public void sendMap() {
        Map map = new HashMap<>();
        map.put("name","xhy");
        map.put("content","恭喜获得10元代金券");
        jmsMessagingTemplate.convertAndSend("xhy_map",map);
    }

Consumer中添加如下方法:

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

4、浏览器输入以下内容:

http://localhost:8081/sendMap

在amq中可以查看到消息消费的信息:
在这里插入图片描述
代码已上传至GitHub上,请复制下面链接下载:

https://github.com/xhy12306/SpringBoot2.0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!