0
  • 聊天消息
  • 系統(tǒng)消息
  • 評(píng)論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫(xiě)文章/發(fā)帖/加入社區(qū)
會(huì)員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識(shí)你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

Spring Cloud Feign總結(jié)問(wèn)題,注意點(diǎn),性能調(diào)優(yōu),切換okhttp3

電子設(shè)計(jì) ? 來(lái)源:電子設(shè)計(jì) ? 作者:電子設(shè)計(jì) ? 2020-12-10 22:43 ? 次閱讀

Feign常見(jiàn)問(wèn)題總結(jié)

FeignClient接口如使用@PathVariable ,必須指定value屬性

//在一些早期版本中, @PathVariable("id") 中的 "id" ,也就是value屬性,必須指定,不能省略。
@FeignClient("microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)
  public User findById(@PathVariable("id") Long id);
  ...
}

Java代碼自定義Feign Client的注意點(diǎn)與坑

@FeignClient(name = "microservice-provider-user", configuration = UserFeignConfig.class)
public interface UserFeignClient {
  @GetMapping("/users/{id}")
  User findById(@PathVariable("id") Long id);
}

/**
 * 該Feign Client的配置類,注意:
 * 1. 該類可以獨(dú)立出去;
 * 2. 該類上也可添加@Configuration聲明是一個(gè)配置類;
 * 配置類上也可添加@Configuration注解,聲明這是一個(gè)配置類;
 * 但此時(shí)千萬(wàn)別將該放置在主應(yīng)用程序上下文@ComponentScan所掃描的包中,
 * 否則,該配置將會(huì)被所有Feign Client共享,無(wú)法實(shí)現(xiàn)細(xì)粒度配置!
 * 個(gè)人建議:像我一樣,不加@Configuration注解
 *
 * @author zhouli
 */
class UserFeignConfig {
  @Bean
  public Logger.Level logger() {
    return Logger.Level.FULL;
  }
}
  • 配置類上也可添加@Configuraiton 注解,聲明這是一個(gè)配置類;但此時(shí)千萬(wàn)別將該放置在主應(yīng)用程序上下文@ComponentScan 所掃描的包中,否則,該配置將會(huì)被所有Feign Client共享(相當(dāng)于變成了通用配置,其實(shí)本質(zhì)還是Spring父子上下文掃描包重疊導(dǎo)致的問(wèn)題),無(wú)法實(shí)現(xiàn)細(xì)粒度配置!
  • 個(gè)人建議:像我一樣,不加@Configuration注解,省得進(jìn)坑。
  • 最佳實(shí)踐:盡量用配置屬性自定義Feign的配置?。?!

@FeignClient 注解屬性

//@FeignClient(name = "microservice-provider-user")
//在早期的Spring Cloud版本中,無(wú)需提供name屬性,從Brixton版開(kāi)始,@FeignClient必須提供name屬性,否則應(yīng)用將無(wú)法正常啟動(dòng)!
//另外,name、url等屬性支持占位符。例如:
@FeignClient(name = "${feign.name}", url = "${feign.url}")

類級(jí)別的@RequestMapping會(huì)被Spring MVC加載

@RequestMapping("/users")
@FeignClient(name = "microservice-user")
public class TestFeignClient {
    // ...
}

類上的@RequestMapping 注解也會(huì)被Spring MVC加載。該問(wèn)題現(xiàn)已經(jīng)被解決,早期的版本有兩種解決方案:
方案1:不在類上加@RequestMapping 注解;
方案2:添加如下代碼:

@Configuration
@ConditionalOnClass({ Feign.class })
public class FeignMappingDefaultConfiguration {
    @Bean
    public WebMvcRegistrations feignWebRegistrations() {
        return new WebMvcRegistrationsAdapter() {
            @Override
            public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
                return new FeignFilterRequestMappingHandlerMapping();
            }
        };
    }

    private static class FeignFilterRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
        @Override
        protected boolean isHandler(Class beanType) {
            return super.isHandler(beanType) && !beanType.isInterface();
        }
    }
}

首次請(qǐng)求失敗
Ribbon的饑餓加載(eager-load)模式

如需產(chǎn)生Hystrix Stream監(jiān)控信息,需要做一些額外操作
Feign本身已經(jīng)整合了Hystrix,可直接使用@FeignClient(value = "microservice-provider-user", fallback = XXX.class) 來(lái)指定fallback類,fallback類繼承@FeignClient所標(biāo)注的接口即可。

但是假設(shè)如需使用Hystrix Stream進(jìn)行監(jiān)控,默認(rèn)情況下,訪問(wèn)http://IP:PORT/actuator/hystrix.stream 是會(huì)返回404,這是因?yàn)镕eign雖然整合了Hystrix,但并沒(méi)有整合Hystrix的監(jiān)控。如何添加監(jiān)控支持呢?需要以下幾步:

第一步:添加依賴,示例:


org.springframework.cloudspring-cloud-starter-hystrix

第二步:在啟動(dòng)類上添加@EnableCircuitBreaker 注解,示例:

@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
@EnableCircuitBreaker
public class MovieFeignHystrixApplication {
  public static void main(String[] args) {
    SpringApplication.run(MovieFeignHystrixApplication.class, args);
  }
}

第三步:在application.yml中添加如下內(nèi)容,暴露hystrix.stream端點(diǎn):

management:
  endpoints:
    web:
      exposure:
        include: 'hystrix.stream'

這樣,訪問(wèn)任意Feign Client接口的API后,再訪問(wèn)http://IP:PORT/actuator/hystrix.stream ,就會(huì)展示一大堆Hystrix監(jiān)控?cái)?shù)據(jù)了。

原文鏈接:http://www.itmuch.com/spring-...

Feign 上傳文件

加依賴

io.github.openfeign.formfeign-form3.0.3io.github.openfeign.formfeign-form-spring3.0.3

編寫(xiě)Feign Client

@FeignClient(name = "ms-content-sample", configuration = UploadFeignClient.MultipartSupportConfig.class)
public interface UploadFeignClient {
    @RequestMapping(value = "/upload", method = RequestMethod.POST,
            produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    String handleFileUpload(@RequestPart(value = "file") MultipartFile file);

    class MultipartSupportConfig {
        @Bean
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder();
        }
    }
}

如代碼所示,在這個(gè)Feign Client中,我們引用了配置類MultipartSupportConfig ,在MultipartSupportConfig 中,我們實(shí)例化了SpringFormEncoder 。這樣這個(gè)Feign Client就能夠上傳啦。
注意點(diǎn)

//RequestMapping注解中的produeces 、consumes 不能少;
@RequestMapping(value = "/upload", method = RequestMethod.POST,
            produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  • 接口定義中的注解@RequestPart(value = "file") 不能寫(xiě)成@RequestParam(value = "file") 。
  • 最好將Hystrix的超時(shí)時(shí)間設(shè)長(zhǎng)一點(diǎn),例如5秒,否則可能文件還沒(méi)上傳完,Hystrix就超時(shí)了,從而導(dǎo)致客戶端側(cè)的報(bào)錯(cuò)。

原文鏈接:http://www.itmuch.com/spring-...

Feign實(shí)現(xiàn)Form表單提交

添加依賴:

io.github.openfeign.formfeign-form3.2.2io.github.openfeign.formfeign-form-spring3.2.2

Feign Client示例:

@FeignClient(name = "xxx", url = "http://www.itmuch.com/", configuration = TestFeignClient.FormSupportConfig.class)
public interface TestFeignClient {
    @PostMapping(value = "/test",
            consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE},
            produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}
            )
    void post(Map queryParam);

    class FormSupportConfig {
        @Autowired
        private ObjectFactory messageConverters;
        // new一個(gè)form編碼器,實(shí)現(xiàn)支持form表單提交
        @Bean
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder(new SpringEncoder(messageConverters));
        }
        // 開(kāi)啟Feign的日志
        @Bean
        public Logger.Level logger() {
            return Logger.Level.FULL;
        }
    }
},>

調(diào)用示例:

@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
  HashMap param = Maps.newHashMap();
  param.put("username","zhangsan");
  param.put("password","pwd");
  this.testFeignClient.post(param);
  return new User();
},>

日志:

...[TestFeignClient#post] ---> POST http://www.baidu.com/test HTTP/1.1
...[TestFeignClient#post] Accept: application/json;charset=UTF-8
...[TestFeignClient#post] Content-Type: application/x-www-form-urlencoded; charset=UTF-8
...[TestFeignClient#post] Content-Length: 30
...[TestFeignClient#post] 
...[TestFeignClient#post] password=pwd&username=zhangsan
...[TestFeignClient#post] ---> END HTTP (30-byte body)

由日志可知,此時(shí)Feign已能使用Form表單方式提交數(shù)據(jù)。

原文鏈接:http://www.itmuch.com/spring-...

Feign GET請(qǐng)求如何構(gòu)造多參數(shù)

假設(shè)需請(qǐng)求的URL包含多個(gè)參數(shù),例如http://microservice-provider-... ,該如何使用Feign構(gòu)造呢?
我們知道,Spring Cloud為Feign添加了Spring MVC的注解支持,那么我們不妨按照Spring MVC的寫(xiě)法嘗試一下:

@FeignClient("microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public User get0(User user);
}

然而,這種寫(xiě)法并不正確,控制臺(tái)會(huì)輸出類似如下的異常。

feign.FeignException: status 405 reading UserFeignClient#get0(User); content:
{"timestamp":1482676142940,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/get"}

由異??芍?,盡管我們指定了GET方法,F(xiàn)eign依然會(huì)使用POST方法發(fā)送請(qǐng)求。于是導(dǎo)致了異常。正確寫(xiě)法如下

方法一[推薦]
注意:使用該方法無(wú)法使用Fegin的繼承模式

@FeignClient("microservice-provider-user")
public interface UserFeignClient {
  @GetMapping("/get")
  public User get0(@SpringQueryMap User user);
}

方法二[推薦]

@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public User get1(@RequestParam("id") Long id, @RequestParam("username") String username);
}

這是最為直觀的方式,URL有幾個(gè)參數(shù),F(xiàn)eign接口中的方法就有幾個(gè)參數(shù)。使用@RequestParam注解指定請(qǐng)求的參數(shù)是什么。

方法三[不推薦]
多參數(shù)的URL也可使用Map來(lái)構(gòu)建。當(dāng)目標(biāo)URL參數(shù)非常多的時(shí)候,可使用這種方式簡(jiǎn)化Feign接口的編寫(xiě)。

@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public User get2(@RequestParam Map map);
},>

在調(diào)用時(shí),可使用類似以下的代碼。

public User get(String username, String password) {
  HashMap map = Maps.newHashMap();
  map.put("id", "1");
  map.put("username", "張三");
  return this.userFeignClient.get2(map);
},>

注意:這種方式不建議使用。主要是因?yàn)榭勺x性不好,而且如果參數(shù)為空的時(shí)候會(huì)有一些問(wèn)題,例如map.put("username", null); 會(huì)導(dǎo)致服務(wù)調(diào)用方(消費(fèi)者服務(wù))接收到的username是"" ,而不是null。

原文鏈接:http://www.itmuch.com/spring-...

切換為 Okhttp3 提升 QPS 性能優(yōu)化

加依賴引入okhttp3

io.github.openfeignfeign-okhttp${version}

寫(xiě)配置

feign:
  # feign啟用hystrix,才能熔斷、降級(jí)
  # hystrix:
  # enabled: true
  # 啟用 okhttp 關(guān)閉默認(rèn) httpclient
  httpclient:
    enabled: false #關(guān)閉httpclient
    # 配置連接池
    max-connections: 200 #feign的最大連接數(shù)
    max-connections-per-route: 50 #fegin單個(gè)路徑的最大連接數(shù)
  okhttp:
    enabled: true
  # 請(qǐng)求與響應(yīng)的壓縮以提高通信效率
  compression:
    request:
      enabled: true
      min-request-size: 2048
      mime-types: text/xml,application/xml,application/json
    response:
      enabled: true

參數(shù)配置

/**
 * 配置 okhttp 與連接池
 * ConnectionPool 默認(rèn)創(chuàng)建5個(gè)線程,保持5分鐘長(zhǎng)連接
 */
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class) //SpringBoot自動(dòng)配置
public class OkHttpConfig {

    // 默認(rèn)老外留給你彩蛋中文亂碼,加上它就 OK
    @Bean
    public Encoder encoder() {
        return new FormEncoder();
    }

    @Bean
    public okhttp3.OkHttpClient okHttpClient() {
        return new okhttp3.OkHttpClient.Builder()
                //設(shè)置連接超時(shí)
                .connectTimeout(10, TimeUnit.SECONDS)
                //設(shè)置讀超時(shí)
                .readTimeout(10, TimeUnit.SECONDS)
                //設(shè)置寫(xiě)超時(shí)
                .writeTimeout(10, TimeUnit.SECONDS)
                //是否自動(dòng)重連
                .retryOnConnectionFailure(true)
                .connectionPool(new ConnectionPool(10, 5L, TimeUnit.MINUTES))
                .build();
    }
}

來(lái)源:趙小胖個(gè)人博客

審核編輯 黃昊宇

聲明:本文內(nèi)容及配圖由入駐作者撰寫(xiě)或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點(diǎn)僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場(chǎng)。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問(wèn)題,請(qǐng)聯(lián)系本站處理。 舉報(bào)投訴
  • Linux
    +關(guān)注

    關(guān)注

    87

    文章

    11126

    瀏覽量

    207950
  • JAVA
    +關(guān)注

    關(guān)注

    19

    文章

    2944

    瀏覽量

    104118
  • 數(shù)據(jù)庫(kù)
    +關(guān)注

    關(guān)注

    7

    文章

    3714

    瀏覽量

    64033
  • python
    +關(guān)注

    關(guān)注

    53

    文章

    4753

    瀏覽量

    84092
收藏 人收藏

    評(píng)論

    相關(guān)推薦

    史上最全性能調(diào)優(yōu)總結(jié)

    在說(shuō)什么是性能調(diào)優(yōu)之前,我們先來(lái)說(shuō)一下,計(jì)算機(jī)的體系結(jié)構(gòu)。
    的頭像 發(fā)表于 05-13 08:57 ?6194次閱讀
    史上最全<b class='flag-5'>性能</b><b class='flag-5'>調(diào)</b><b class='flag-5'>優(yōu)</b><b class='flag-5'>總結(jié)</b>

    EDAS再升級(jí)!全面支持Spring Cloud應(yīng)用

    摘要: 近日,阿里中間件(Aliware)的企業(yè)級(jí)分布式應(yīng)用服務(wù)EDAS宣布再次升級(jí),全面支持Spring Cloud應(yīng)用。點(diǎn)此查看原文:[url=]http://click.aliyun.com
    發(fā)表于 02-02 15:20

    HBase性能調(diào)優(yōu)概述

    HBase性能調(diào)優(yōu)
    發(fā)表于 07-03 11:35

    Spring Cloud Config公共配置解決方案

    Spring Cloud Config 多服務(wù)公共配置
    發(fā)表于 08-30 09:05

    基于全HDD aarch64服務(wù)器的Ceph性能調(diào)優(yōu)實(shí)踐總結(jié)

    和成本之間實(shí)現(xiàn)了最佳平衡,可以作為基于arm服務(wù)器來(lái)部署存儲(chǔ)的參考設(shè)計(jì)。2 Ceph架構(gòu)3 測(cè)試集群硬件配置:3臺(tái)arm服務(wù)器每臺(tái)arm服務(wù)器:軟件配置性能測(cè)試工具4 調(diào)
    發(fā)表于 07-05 14:26

    infosphere CDC性能調(diào)優(yōu)的文檔

    infosphere CDC性能調(diào)優(yōu)的文檔
    發(fā)表于 09-07 09:30 ?7次下載
    infosphere CDC<b class='flag-5'>性能</b><b class='flag-5'>調(diào)</b><b class='flag-5'>優(yōu)</b>的文檔

    架構(gòu)分析高效HTTP客戶端OkHttp有什么優(yōu)勢(shì)

    OkHttp3中,其靈活性很大程度上體現(xiàn)在,可以攔截其任意一個(gè)環(huán)節(jié),而這個(gè)優(yōu)勢(shì)便是okhttp3整個(gè)請(qǐng)求響應(yīng)架構(gòu)體系的精髓所在:
    的頭像 發(fā)表于 05-05 23:13 ?3772次閱讀
    架構(gòu)分析高效HTTP客戶端<b class='flag-5'>OkHttp</b>有什么優(yōu)勢(shì)

    Spring Cloud Feign性能優(yōu)化

    首先,把 tomcat 換成 undertow,這個(gè)性能在 Jmeter 的壓測(cè)下,undertow 比 tomcat 高一倍第一步,pom 修改去除tomcat
    的頭像 發(fā)表于 12-10 22:43 ?451次閱讀

    基于SharedPreferences的OkHttp3的持久CookieJar實(shí)現(xiàn)

    介紹 基于 SharedPreferences 的 OkHttp3 的持久 CookieJar 實(shí)現(xiàn)。該庫(kù)通常用于存儲(chǔ)從 http url 獲取的 cookie。如果我們?cè)俅吸c(diǎn)擊 url 并獲取
    發(fā)表于 04-12 10:37 ?3次下載

    Spring Cloud Tencent發(fā)布最新匹配版本!

    Cloud 2022。此篇文章詳細(xì)講述了 Spring Cloud Tencent 從 2021 版本升級(jí)到 2022 版本的改動(dòng)點(diǎn)。
    的頭像 發(fā)表于 12-09 15:34 ?997次閱讀

    Spring Cloud 2022.0.0正式發(fā)布

    由于 Spring 現(xiàn)在提供了他們自己實(shí)現(xiàn)的接口 HTTP 客戶端解決方案,因此從 2022.0.0 開(kāi)始,Spring Cloud OpenFeign 已到達(dá)特性完成狀態(tài)。這意味著 Spri
    的頭像 發(fā)表于 12-22 10:39 ?642次閱讀

    dubbo和spring cloud區(qū)別

    Dubbo和Spring Cloud是兩個(gè)非常流行的微服務(wù)框架,各有自己的特點(diǎn)和優(yōu)勢(shì)。在本文中,我們將詳細(xì)介紹Dubbo和Spring Cloud的區(qū)別。 1.架構(gòu)設(shè)計(jì): Dubbo是
    的頭像 發(fā)表于 12-04 14:47 ?1343次閱讀

    鴻蒙開(kāi)發(fā)實(shí)戰(zhàn):【性能調(diào)優(yōu)組件】

    性能調(diào)優(yōu)組件包含系統(tǒng)和應(yīng)用調(diào)優(yōu)框架,旨在為開(kāi)發(fā)者提供一套性能
    的頭像 發(fā)表于 03-13 15:12 ?314次閱讀
    鴻蒙開(kāi)發(fā)實(shí)戰(zhàn):【<b class='flag-5'>性能</b><b class='flag-5'>調(diào)</b><b class='flag-5'>優(yōu)</b>組件】

    鴻蒙OS封裝【axios 網(wǎng)絡(luò)請(qǐng)求】(類似Android的Okhttp3

    HarmonyOS 封裝 axios 網(wǎng)絡(luò)請(qǐng)求 包含 token 類似Android Okhttp3
    的頭像 發(fā)表于 03-26 21:14 ?2381次閱讀

    Spring Cloud Gateway網(wǎng)關(guān)框架

    SpringCloud Gateway功能特征如下: (1) 基于Spring Framework 5, Project Reactor 和 Spring Boot 2.0 進(jìn)行構(gòu)建; (2) 動(dòng)態(tài)路由:能夠匹配任何請(qǐng)求屬性; (3
    的頭像 發(fā)表于 08-22 09:58 ?294次閱讀
    <b class='flag-5'>Spring</b> <b class='flag-5'>Cloud</b> Gateway網(wǎng)關(guān)框架