SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

Stella981
• 阅读 494

1. activemq

  首先引入依赖

  pom.xml文件

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

  创建一个配置队列类

  JMSConfiguration.java

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

package com.wangx.boot.util;

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.Destination; @Configuration @EnableJms public class JMSConfiguration { @Bean public Destination createDestination () { return new ActiveMQQueue("com.wangx"); } }

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

  创建一个消息生产者和消息消费者

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

package com.wangx.boot.mq;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener; import org.springframework.jms.core.JmsMessagingTemplate; import org.springframework.stereotype.Component; import javax.jms.Destination; @Component public class JMSComponent { @Autowired private JmsMessagingTemplate jmsMessagingTemplate; @Autowired private Destination destination; public void send (String message) { jmsMessagingTemplate.convertAndSend(destination, message); } @JmsListener(destination = "com.wangx") public void listener (String message) { System.out.println("接收到的消息:" + message); } }

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

  @JmsListener中的destination必须与队列配置类中定一的queue的名字相同。

   SpringBoot提供了一个默认内置的消息队列中间件,如果我们使用spring.activemq.in-memory=true时将会使用内置的消息队列,但是它也提供了我们使用外部activemq的一些配置:

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

#spring.activemq.broker-url= 
#spring.activemq.password= 
#spring.activemq.user= 
#spring.activemq.packages.trust-all=false #spring.activemq.packages.trusted= #spring.activemq.pool.configuration.*= #spring.activemq.pool.enabled=false #spring.activemq.pool.expiry-timeout=0 #spring.activemq.pool.idle-timeout=30000 #spring.activemq.pool.max-connections=1

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

  测试消息发送

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

package com.wangx.boot.controller;

import com.wangx.boot.mq.JMSComponent;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/mq") public class JMSController { @Autowired private JMSComponent jmsComponent; @RequestMapping("/send") @ResponseBody public String send(String msg) { jmsComponent.send(msg); return msg; } }

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

  当访问localhost:8080/mq/send?msg=xxx时,消费者的监听方法(带有@JmsListener注解的方法)会自动监听到消息,并打印到控制台上。

2. rabbitmq的使用

  首先引入pom.xml 

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

ps:rabbitmq和activemq的依赖不能同时存在。

  首先还是创建一个队列配置类

  AMQConfiguration.java

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

package com.wangx.boot.util;

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AMQConfiguration { @Bean public Queue queue() { return new Queue("hello", true); } }

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

  接着创建消息生产和消费组件

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

package com.wangx.boot.mq;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class AMQComponent { @Autowired private AmqpTemplate amqpTemplate; public void send(String message) { amqpTemplate.convertAndSend("hello", message); } @RabbitListener(queues = "hello") public void receiveQueue(String text) { System.out.println("接受到:" + text); } }

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

  在SpringBoot的启动类上添加@EnableRabbit表示开启rabbit消息队列。

  测试是否发送了消息

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

package com.wangx.boot.controller;

import com.wangx.boot.mq.AMQComponent;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/amq") public class AMQController { @Autowired private AMQComponent amqComponent; @RequestMapping("/send") @ResponseBody public String send(String msg) { amqComponent.send(msg); return msg; } }

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

  访问localhost:8080/amq/send?msg=xxx,在调用放松消息的方法时。监听的方法同样会收到消息,并打印到控制台上。

3. 调用rest服务

  3.1 代码实现

    首先引入依赖

    pom文件

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
</dependency>

  然后随便写一个Controller接口,如:

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

package com.wangx.boot.controller;

import com.wangx.boot.cache.CachingBook;
import com.wangx.boot.entity.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api") public class ApiController { @Autowired private CachingBook cachingBook; @RequestMapping(value = "/select", method = RequestMethod.GET) public Book get(@RequestParam(defaultValue = "遮天") String name) { Book book = cachingBook.findById(name); return book; } @RequestMapping(value = "/update", method = RequestMethod.GET) public Book update(@RequestParam(defaultValue = "遮天") String name) { Book bean = cachingBook.findById(name); bean.setAuthor("耳根"); cachingBook.updateById(bean); return bean; } @RequestMapping(value = "/del", method = RequestMethod.GET) public String del(@RequestParam(defaultValue = "遮天") String name) { return cachingBook.deleteById(name); } }

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

  启动服务,在另一个工程中使用RestTemplateBuilder来访问我们启动的服务,

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

@Autowired
    private RestTemplateBuilder restTemplateBuilder;

        /** * get请求 */ @Test public void getForObject() { //发送get请求 String res = restTemplateBuilder.build().getForObject("http://localhost:8080/api/select",String.class, "遮天"); System.out.println(res); Map<String,Object> map = new HashMap<String,Object>(); map.put("name", "遮天"); //发送post请求 res = restTemplateBuilder.build().postForObject("http://localhost:8080/api/update", map, String.class); System.out.println(res); }

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

  可以成功调用我们启动的服务的接口。

  3.2 使用代理 

    使用RestTemplate还可以自己实现代理的功能。

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

public class ProxyCustomizer implements RestTemplateCustomizer {
        @Override
        public void customize(RestTemplate restTemplate) { //http://ip.zdaye.com/ 上可以查询可用的主机和端口 String proxyHost = "59.33.46.187"; int proxyPort = 6969; HttpHost proxy = new HttpHost(proxyHost, proxyPort); HttpClient httpClient = HttpClientBuilder.create().setRoutePlanner(new DefaultProxyRoutePlanner(proxy) { @Override public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { return super.determineProxy(target, request, context); } }).build(); HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); httpComponentsClientHttpRequestFactory.setConnectTimeout(10000); httpComponentsClientHttpRequestFactory.setReadTimeout(60000); restTemplate.setRequestFactory(httpComponentsClientHttpRequestFactory); } }

SpringBoot中使用rabbitmq,activemq消息队列和rest服务的调用

  测试方式:

String result = restTemplateBuilder.additionalCustomizers(new ProxyCustomizer()).build().getForObject("http://www.baidu.com", String.class);
        System.out.println(result);
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这