解决:SpringCloud中Feign支持GET请求POJO传参

在日常的开发中,当遇到一个请求需要传递多个参数时,我们习惯将参数封装到一个POJO对象中,已提高程序的可读性和简化编写。但是在使用SpringCloud时,Feign对SpringMVC注解支持并不完善,其中一点就是,当发送的GET请求携带多个参数时,不能使用POJO来封装参数,这个就比较蛋疼了。一种使之支持GET请求POJO传递参数的方法如下:

添加Maven依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>com.netflix.feign</groupId>
            <artifactId>feign-httpclient</artifactId>
            <version>8.15.1</version>
        </dependency>

        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-hystrix</artifactId>
            <version>10.2.0</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-okhttp</artifactId>
        </dependency>

application.yml

        feign:
          hystrix:
            enabled: true
          httpclient:
            enabled: true
          okhttp:
            enabled: true

添加对GET请求的拦截器


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * 拦截Fegin的get请求,使之支持get请求pojo传参
 */
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    private static final Logger log = LoggerFactory.getLogger(FeignRequestInterceptor.class);
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void apply(RequestTemplate template) {
        if (HttpMethod.GET.name().equals(template.method())
                && null != template.body()) {
            try {
                JsonNode jsonNode = objectMapper.readTree(template.body());
                template.body(null);

                Map<String, Collection<String>> queries = new HashMap<>();
                buildQuery(jsonNode, "", queries);
                template.queries(queries);
            } catch (IOException e) {
                log.error("【拦截GET请求POJO方式】-出错了:{}", JSON.toJSONString(e));
                throw new RuntimeException();
            }
        }
    }

    private void buildQuery(JsonNode jsonNode, String path, Map<String, Collection<String>> queries) {
        // 叶子节点
        if (!jsonNode.isContainerNode()) {
            if (jsonNode.isNull()) {
                return;
            }
            Collection<String> values = queries.get(path);
            if (null == values) {
                values = new ArrayList<>();
                queries.put(path, values);
            }
            values.add(jsonNode.asText());
            return;
        }
        // 数组节点
        if (jsonNode.isArray()) {
            Iterator<JsonNode> it = jsonNode.elements();
            while (it.hasNext()) {
                buildQuery(it.next(), path, queries);
            }
        } else {
            Iterator<Map.Entry<String, JsonNode>> it = jsonNode.fields();
            while (it.hasNext()) {
                Map.Entry<String, JsonNode> entry = it.next();
                if (StringUtils.hasText(path)) {
                    buildQuery(entry.getValue(), path + "." + entry.getKey(), queries);
                } else {  // 根节点
                    buildQuery(entry.getValue(), entry.getKey(), queries);
                }
            }
        }
    }

}

其他

此时你的应用程序就可以通过POJO封装参数向其他服务发起调用了。但是如果你请求的Content-Type是application/json的,那么你要需要指定请求的consumes为consumes = MediaType.APPLICATION_JSON_VALUE

原文地址:https://www.cnblogs.com/QullLee/p/10682719.html

时间: 2024-08-30 01:24:18

解决:SpringCloud中Feign支持GET请求POJO传参的相关文章

WPF ContextMenu 在MVVM模式中绑定 Command及使用CommandParameter传参

原文:WPF ContextMenu 在MVVM模式中绑定 Command及使用CommandParameter传参 ContextMenu无论定义在.cs或.xaml文件中,都不继承父级的DataContext,所以如果要绑定父级的DataContext,直接DataContext=“{Binding}”是行不通的 不能绑父级,但是能绑资源 第一步:定义一个中间类用来做资源对象 1 public class BindingProxy : Freezable 2 { 3 #region Over

解决Spring Cloud中Feign/Ribbon第一次请求失败的方法

前言 在Spring Cloud中,Feign和Ribbon在整合了Hystrix后,可能会出现首次调用失败的问题,要如何解决该问题呢? 造成该问题的原因 Hystrix默认的超时时间是1秒,如果超过这个时间尚未响应,将会进入fallback代码.而首次请求往往会比较慢(因为Spring的懒加载机制,要实例化一些类),这个响应时间可能就大于1秒了.知道原因后,我们来总结一下解决放你. 解决方案有三种,以feign为例. 方法一 ? 1 hystrix.command.default.execut

爬虫 --- 07. 全站爬取, post请求,cookie, 传参,中间件,selenium

一.全站数据的爬取 - yield scrapy.Request(url,callback):callback回调一个函数用于数据解析 # 爬取阳光热线前五页数据 import scrapy from sunLinePro.items import SunlineproItem class SunSpider(scrapy.Spider): name = 'sun' # allowed_domains = ['www.xxx.com'] start_urls = ['http://wz.sun0

9_flask中的模板渲染和模板传参及其技巧

模板传参 在使用render_template 渲染模板的时候,可以传递关键字参数, 如果你的参数过多,那么可以将所有的参数放到一个字典中,然后 传这个字典参数的时,使用两个星号,将字典打散成关键字参数 后台传参 @app.route('/') def index(): # return render_template('index.html', name='long', age=18, country='china') context = { 'name': 'long', 'age': 18

SpringCloud中Feign的适配器的实现方案

前言 最近在做微服务的项目,各个系统之间需要进行调用,然后用一个适配器来实现服务之间的feign调用,使用适配器进行统一管理. 实现方案 首先我们需要将服务的名称进行单独的配置,可以方便的进行切换和扩展,我们使用bootstrap.yml来进行配置,这样引入jar包的时候,可以将配置互补到我们本身项目的application.yml中. 在我们的bootstrap.yml中进行配置. ## 配置的服务名称 server-name: # 配置在eureka中注册的服务名称 feignDemo: d

JS ajax请求 formData传参方式

1 $("#importBtn").click(function(){ 2 if($("#conId").val() == ""){ 3 alert("请填写Id"); 4 return; 5 } 6 if($("#fromWhere").val() == ""){ 7 alert("请填写简称"); 8 return; 9 } 10 if($("#impo

Go_17:GoLang中如何使用多参数属性传参

我们常常因为传入的参数不确定而头疼不已,golang 为我们提供了接入多值参数用于解决这个问题.但是一般我们直接写已知代码即所有的值都知道一个一个塞进去就好了,但是绝大部分我们是得到用户的大量输入想通过循环传入,但是这样发现无法使用这个多值参数的功能.其实底层实现将多个参数视为传入的一个不定长数组.那么我们就有想法了:既然底层使用数组,那我们传入数组是否可以,结论是不可以的,或者这样说比较合理:数组不能直接传入,需要辅助多参数标识来指明,具体让我们看以下一个简单的测试: func TestMul

Spring MVC POJO传参方式

有两POJO类 Address.java 1 package com.proc; 2 3 public class Address { 4 5 private String province; 6 private String city; 7 public String getProvince() { 8 return province; 9 } 10 public void setProvince(String province) { 11 this.province = province;

http请求与传参

这并不算是文章,暂时只做粗略地记录,以免忘记,因此会显得杂乱无章,随便抓了几个包和对postman截图,日后有空再完善 1.get方式 只有一种方式,那就是在url后面跟参数 2.post方式 1)表单传参方式 请求头如下 POST http://localhost:8090/rest/integration/data/dictTable/add HTTP/1.1 Host: localhost:8090 Connection: keep-alive Content-Length: 37 Pos