博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
3、SpringBoot2.0与ActiveMQ整合(三)
阅读量:346 次
发布时间:2019-03-04

本文共 1627 字,大约阅读时间需要 5 分钟。

使用内嵌服务

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

org.springframework.boot
spring-boot-starter-activemq

2、在文件下创建Producter和Consumer:

在这里插入图片描述
3、生产者Producter中的代码如下:

@RestControllerpublic class Producter {    @Autowired    private JmsMessagingTemplate jmsMessagingTemplate;    @RequestMapping("/send")    public void sendMessage(String text) {        jmsMessagingTemplate.convertAndSend("xhy",text);    }}

消费者Consumer代码如下:

@Componentpublic 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

如需获取更多关于SpringBoot、SpringCloud学习资料关注下面公众号,后台回复SpringBoot关键字即可领取。

转载地址:http://csse.baihongyu.com/

你可能感兴趣的文章