iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >@FeignClient 实现简便http请求封装方式
  • 408
分享到

@FeignClient 实现简便http请求封装方式

2024-04-02 19:04:59 408人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录@FeignClient实现Http请求封装使用流程将http请求封装为FeignClient1.配置拦截器2.注入feignClient bean3.配置pom引用4.写fei

@FeignClient实现http请求封装

我们一般在代码中调用http请求时,都是封装了http调用类,底层自己定义请求头,在写的时候,也是需要对返回的值进行JSON解析,很不方便。

  • name:name属性会作为微服务的名称,用于服务发现
  • url:host的意思,不用加http://前缀
  • decode404:当发生http 404错误时,如果该字段位true,会调用decoder进行解码,否则抛出FeignException

使用流程

(1)创建接口类(Feignapi),来统一规范需要调用的第三方接口

@FeignClient(name = "aaa", url = "localhost:8080", decode404 = true)
public interface FeignApi {
    
    @PostMapping("/api/xxxx/baiduaaa")
    ResponseResult<ResponseVo> getSomeMoneyForYourSelfAAA(@RequestBody AAAParam param);
    
    
    @GetMapping("/api/xxxx/baidubbb")
    ResponseResult<ResponseVo> getSomeMoneyForYourSelfBBB(@RequestBody AAAParam param);
}

(2)在启动类加上注解,会去扫包注册Bean

@EnableFeignClients(basePackages = {"com.aaa"})

(3)业务代码调用处:

ResponseResult<ResponseVo> response = pmsFeignApi.getSomeMoneyForYourSelfAAA(param);

将http请求封装为FeignClient

1.配置拦截器

import java.io.IOException;
import java.io.InterruptedIOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpRetryInterceptor implements Interceptor {undefined
    private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpRetryInterceptor.class);
    
    private int                 executionCount;
    
    private long                retryInterval;
    OkHttpRetryInterceptor(Builder builder) {undefined
        this.executionCount = builder.executionCount;
        this.retryInterval = builder.retryInterval;
    }
    @Override
    public Response intercept(Chain chain) throws IOException {undefined
        Request request = chain.request();
        Response response = doRequest(chain, request);
        int retryNum = 0;
        while ((response == null || !response.isSuccessful()) && retryNum <= executionCount) {undefined
            LOGGER.info("intercept Request is not successful - {}", retryNum);
            final long nextInterval = getRetryInterval();
            try {undefined
                LOGGER.info("Wait for {}", nextInterval);
                Thread.sleep(nextInterval);
            } catch (final InterruptedException e) {undefined
                Thread.currentThread().interrupt();
                throw new InterruptedIOException();
            }
            retryNum++;
            // retry the request
            response = doRequest(chain, request);
        }
        return response;
    }
    private Response doRequest(Chain chain, Request request) {undefined
        Response response = null;
        try {undefined
            response = chain.proceed(request);
        } catch (Exception e) {undefined
        }
        return response;
    }
    
    public long getRetryInterval() {undefined
        return this.retryInterval;
    }
    public static final class Builder {undefined
        private int  executionCount;
        private long retryInterval;
        public Builder() {undefined
            executionCount = 3;
            retryInterval = 1000;
        }
        public Builder executionCount(int executionCount) {undefined
            this.executionCount = executionCount;
            return this;
        }
        public Builder retryInterval(long retryInterval) {undefined
            this.retryInterval = retryInterval;
            return this;
        }
        public OkHttpRetryInterceptor build() {undefined
            return new OkHttpRetryInterceptor(this);
        }
    }
}

2.注入feignClient bean

import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.netflix.feign.FeignAutoConfiguration;
import org.springframework.cloud.netflix.feign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient;
import org.springframework.cloud.netflix.ribbon.SprinGClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import feign.Client;
import feign.Feign;
import feign.ribbon.RibbonClient;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
@Configuration
@ConditionalOnMissingBean({ OkHttpClient.class, Client.class })
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class FeignClientConfig {undefined
    @Value("${feign.invoke.http.connectTimeoutMillis:3000}")
    private int connectTimeoutMillis;
    @Value("${feign.invoke.http.readTimeoutMillis:10000}")
    private int readTimeoutMillis;
    @Value("${feign.invoke.http.retryExecutionCount:3}")
    private int retryExecutionCount;
    @Value("${feign.invoke.http.retryInterval:1000}")
    private int retryInterval;
    public FeignClientConfig() {undefined
    }
    @Bean
    @ConditionalOnMissingBean({ OkHttpClient.class })
    public OkHttpClient okHttpClient() {undefined
        OkHttpRetryInterceptor okHttpRetryInterceptor = new OkHttpRetryInterceptor.Builder().executionCount(retryExecutionCount)
                                                                                            .retryInterval(retryInterval)
                                                                                            .build();
        return new OkHttpClient.Builder().retryOnConnectionFailure(true)
                                         .addInterceptor(okHttpRetryInterceptor)
                                         .connectionPool(new ConnectionPool())
                                         .connectTimeout(connectTimeoutMillis, TimeUnit.MILLISECONDS)
                                         .readTimeout(readTimeoutMillis, TimeUnit.MILLISECONDS)
                                         .build();
    }
    @Bean
    @ConditionalOnMissingBean({ Client.class })
    public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory, SpringClientFactory clientFactory) {undefined
        if (cachingFactory == null) {undefined
            RibbonClient.Builder builder = RibbonClient.builder();
            builder.delegate(new feign.okhttp.OkHttpClient(this.okHttpClient()));
            return builder.build();
        } else {undefined
            return new LoadBalancerFeignClient(new feign.okhttp.OkHttpClient(this.okHttpClient()), cachingFactory,
                                               clientFactory);
        }
    }
}

3.配置pom引用

 <dependency>
 <groupId>io.GitHub.openfeign</groupId>
 <artifactId>feign-ribbon</artifactId>
 <version>9.0.0</version>
 </dependency>

4.写feignClient

@FeignClient(name = "xxxApi", url = "${xxx.url}")
public interface xxxClient {
     @RequestMapping(method = RequestMethod.POST)
     public String createLink(@RequestHeader(name = "accessKey", defaultValue = "xx") String accessKey,
         @RequestHeader(name = "accessSecret") String accessSecret, @RequestBody String linkConfig);
}

5.写熔断器

    @Autowired
    private xxxClient xxClient;
    @HystrixCommand(commandKey = "xxxLink", fallbackMethod = "xxxError", commandProperties = { @HystrixProperty(name = "requestCache.enabled", value = "true"),
                                                                                                                           @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000") })
    public String xxLink(String accessKey, String accessSecret, String linkConfig) {
        LOG.info("[xxLink]  LinkConfig is {}", linkConfig);
        String resp = xxxClient.createLink(accessKey, accessSecret, linkConfig);
        LOG.info("[xxxLink] response : {}", resp);
        return resp;
    }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: @FeignClient 实现简便http请求封装方式

本文链接: https://www.lsjlt.com/news/141970.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • @FeignClient 实现简便http请求封装方式
    目录@FeignClient实现http请求封装使用流程将http请求封装为FeignClient1.配置拦截器2.注入feignClient bean3.配置pom引用4.写fei...
    99+
    2024-04-02
  • 微信小程序中如何实现http请求封装
    这篇文章将为大家详细讲解有关微信小程序中如何实现http请求封装,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。微信小程序  http请求封装示例代码wx.req...
    99+
    2024-04-02
  • java使用RestTemplate封装post请求方式
    目录使用RestTemplate封装post请求RestTemplate使用封装1、SpringBoot使用RestTemplate(使用apache的httpclient)2、使用...
    99+
    2024-04-02
  • uniapp封装发送请求方式是什么
    随着前端开发的不断发展,前端框架也越来越丰富多样。而其中,uni-app框架的崛起引起了前端开发者的广泛关注。因为它具有了很多原生开发中才有的功能,如无需反复打包、多端发布等。在uni-app开发过程中,我们常常需要进行网络请求。而为了方便...
    99+
    2023-05-14
  • Java 实现HTTP请求的四种方式总结
    前言 在日常工作和学习中,有很多地方都需要发送HTTP请求,本文以Java为例,总结发送HTTP请求的多种方式 HTTP请求实现过程 GET ▶️①、创建远程连接 ▶️②、设置连接方式(get、post、put…) ▶️③、设置连接超时...
    99+
    2023-08-17
    java http restful
  • React hook实现简单的websocket封装方式
    目录React hook实现websocket封装react自定义hook解决websocket连接,useWebSocket1、描述2、代码React hook实现websocke...
    99+
    2024-04-02
  • android实现okHttp的get和post请求的简单封装与使用
    由于Android课程项目需要,特地查阅了okHttp的使用,发现网上找的大多和自己的需求不一样。所以就着团队项目需要,自己简单封装了一个okHttp的get和post请求。 话不多...
    99+
    2024-04-02
  • 实现HTTP请求的方法有哪些
    本篇文章为大家展示了实现HTTP请求的方法有哪些,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。一、HTTP的请求与响应HTTP协议(HyperText Transfer Protocol,超文本传输...
    99+
    2023-05-31
    http请求 请求
  • Go语言实现关闭http请求的方式总结
    目录写在前面方式一:设置请求变量的 Close 字段值为 true方式二:设置 Header 请求头部选项 Connection: close方式三:自定义配置的 HTTP tran...
    99+
    2023-02-26
    Go关闭http请求 Go关闭http Go http
  • 微信小程序开发中如何封装HTTP请求方法
    这篇文章主要介绍微信小程序开发中如何封装HTTP请求方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!HTTP请求方法的封装在小程序中http请求是很频繁的,但每次都打出wx.req...
    99+
    2024-04-02
  • 如何实现JavaScript原生封装ajax请求和Jquery中的ajax请求
    小编给大家分享一下如何实现JavaScript原生封装ajax请求和Jquery中的ajax请求,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!1、原生ajax(1)html前端代码get请...
    99+
    2024-04-02
  • C++中封装的含义和简单实现方式
    目录封装实现封装属性class 封装其实封装并不是编程中的一个思想,对于很多领域来说都是这样。对于电子器件来说,我们不关心其内部的结构,只在乎该器件能够实现什么样的功能。这样对于顾客...
    99+
    2024-04-02
  • Vue使用axios发送请求并实现简单封装的示例详解
    目录一、安装axios二、简单使用1.配置2.发送请求三、封装使用1.创建js封装类2.配置3.发送请求一、安装axios npm install axios --save 二、简单...
    99+
    2024-04-02
  • Feign如何实现第三方的HTTP请求
    目录Feign调用的简单实现1. 默认模式,不使用配置类,作用于服务内部调用而非三方请求接口2.自定义配置类3.自定义配置类法2 4. @FeignClient参数说明5....
    99+
    2022-11-13
    Feign HTTP请求 第三方HTTP请求 Feign第三方HTTP请求
  • 使用注解+RequestBodyAdvice实现http请求内容加解密方式
    注解主要用来指定那些需要加解密的controller方法 实现比较简单 @Target({ElementType.METHOD}) @Retention(RetentionPol...
    99+
    2024-04-02
  • Java 实现 HTTP 请求的四种方式,你都学会了么?
    前言 在日常工作和学习中,有很多地方都需要发送HTTP请求,本文以Java为例,总结发送HTTP请求的多种方式 HTTP请求实现过程 GET 创建远程连接 设置连接方式(get、post、put…) 设置连接超时时间 设置响应读取时...
    99+
    2023-09-20
    java http 开发语言
  • AngularJS中$http模块POST请求的实现方法
    小编给大家分享一下AngularJS中$http模块POST请求的实现方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!一、代码...
    99+
    2024-04-02
  • 怎么用注解+RequestBodyAdvice实现http请求内容加解密方式
    这篇文章主要介绍“怎么用注解+RequestBodyAdvice实现http请求内容加解密方式”,在日常操作中,相信很多人在怎么用注解+RequestBodyAdvice实现http请求内容加解密方式问题上存在疑惑,小编查阅了各式资料,整理...
    99+
    2023-06-20
  • Vue3+TypeScript封装axios并进行请求调用的实现
    不是吧,不是吧,原来真的有人都2021年了,连TypeScript都没听说过吧?在项目中使用TypeScript虽然短期内会增加一些开发成本,但是对于其需要长期维护的项目,TypeS...
    99+
    2024-04-02
  • axios请求响应数据加解密封装实现详解
    目录安装依赖封装基础axios封装加密方法封装解密方法封装请求方法使用封装方法结尾安装依赖 在前端开发中,我们经常需要向后端发送请求获取数据。为了保证数据的安全性,在发送请求时需要...
    99+
    2023-03-13
    封装axios请求响应数据 axios数据加解密
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作