Feign常用的代码、注解、Http请求调用

Feign常用的注解:

  • name/value:指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现
  • contextId:指定beanID
  • url: url一般用于调试,可以手动指定@FeignClient调用的地址
  • decode404:当发生http 404错误时,如果该字段位true,会调用decoder进行解码,否则抛出FeignException
  • configuration: Feign配置类,可以自定义Feign的Encoder、Decoder、LogLevel、Contract
  • fallback: 定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口
  • fallbackFactory: 工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑,减少重复的代码
  • path: 定义当前FeignClient的统一前缀/上下文

Feign调用 http的 post 请求:

如果不需要 head参数,就不用加 @RequestHeader。

在做服务调用时,一般不会用到 url属性。my.url 是配置的值,后面的: 是默认值。

示例如下:

@FeignClient(name = "myFeignService", 
        url = "${my.url:http://ip:端口/}")
public interface MyFeignService {

    @PostMapping(value = "具体的url路径")
    @ResponseBody
    MyResponse post(@RequestBody MyBody myBody,
              @RequestHeader(name = "headParam1", required = true) String headParam1);

}

或者是:

    @RequestMapping(value = "/v1/xx/xxx", method = RequestMethod.POST,
            headers = {"userName={userName}",  "userId={userId}" }
    )
    Response<User> getUser(@RequestParam("userName") String userName,
                                     @RequestParam("userId") String userId);

Feign调用 http的 Get 请求:

在做服务调用时,一般不会用到 url属性。my.url 是配置的值,后面的: 是默认值。

示例如下:

    @FeignClient(name = "myFeignService", 
        url = "${my.url:http://ip:端口/}")
public interface MyFeignService {
    @GetMapping(value = "具体的url路径")
    @ResponseBody
    MyResponse get(@RequestParam (value = "param1") String param1,
		@RequestParam (value = "param2") String param2);
}

Feign 配置

可以在 application.yml 中, 添加关于 feign 的 配置:

feign:
  okhttp:
    # 是否使用okhttp client
    enabled: true
  # 连接超时时间
  connectTimeout: 2000
  # 读取超时时间
  readTimeOut: 8000
  # hystrix 熔断
  hystrix:
    # 是否开启 hystrix
    enabled: true
  client:
    config:
      # 针对特殊的 feignClient 设置超时时间
      myFeignService:
        connectTimeout: 3000
        readTimeout: 8000

参考资料:

https://cloud.tencent.com/developer/article/2000153

posted on   乐之者v  阅读(244)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2022-05-04 java8 日期Date、LocalDate、LocalDateTime、字符串String的转换
2022-05-04 每月摘录--2022年4月
2020-05-04 《Kafka权威指南》读书笔记
2018-05-04 IntelliJ Idea解决Could not autowire. No beans of 'xxxx' type found的错误提示
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示