Spring注解之@FeignClient注解使用方法

声明接口时在代码中通过@Resource注入容器之后即可使用。@FeignClient注解的常用属性如下:

  • value/name:value和name的作用一样,用于指定FeignClient的名称;如果没有配置url,而且项目使用了Eurekanacos或者ribbon,name属性会作为微服务的名称,用于服务发现。反之,只是一个名称。此属性和 spring.application.name 对应。
  • url:一般用于调试,作用是指定@FeignClient调用的API地址,而非从服务中心获取。

url和name都可以使用占位符,比如:@FeignClient(name = “your.feign.name",url="${your.feign.url}”);

  • decode404:当发生http 404错误时,如果该字段为true,会调用decoder进行解码;否则,抛出FeignException。
  • configuration:Feign配置类,作用是自定义Feign的Encoder、Decoder、LogLevel、Contract。
  • fallback:定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口。
  • fallbackFactory:工厂类,用于生成fallback类实例,实现每个接口通用的容错逻辑,减少重复的代码。
  • path:定义当前FeignClient的统一前缀。
  • contextId:为某个接口设置单独的超时,与与config里的属性对应。

添加依赖和启动注解

spring-boot-starter-parent版本是2.5.0,需要添加的maven坐标:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>3.0.4-SNAPSHOT</version>
</dependency>

添加启动注解:

@SpringBootApplication
@EnableFeignClients//添加这个注解
public class XXXXApplication {
  public static void main(String[] args) {
    SpringApplication.run(XXXXApplication.class, args);
  }
}

沙场秋点兵

首先,在yaml文件中配置常量self.github.url=https://api.github.com,然后,创建接口类,此接口类定义了需要调用的目标服务中的方法,用Feign官方文档中调用GitHub服务的例子来举例。

import com.swagger.demo.bean.Contributor;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

//@FeignClient(name = "github", url = "https://api.github.com")
@FeignClient(name = "github", url = "${self.github.url}",
        fallback = GithubFeignClient.MyDefaultFallback.class)
public interface GithubFeignClient {

    @GetMapping(value = "/repos/{owner}/{repo}/contributors")
    ResponseEntity<List<Contributor>> listContributors(
            @PathVariable("owner") String owner,
            @PathVariable("repo") String repo);
    /**
     * 容错处理类,当调用失败时,简单返回空list
     */
    @Component
    class MyDefaultFallback implements GithubFeignClient {
        @Override
        public ResponseEntity<List<Contributor>> listContributors(
                @PathVariable("owner") String owner,
                @PathVariable("repo") String repo) {
            return new ResponseEntity(new ArrayList<>(), HttpStatus.BAD_REQUEST);
        }
    }
}

// --------- 新增实体类 -----------
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Setter
@Getter
@ToString
public class Contributor {

    /**
     * 作者
     */
    private String login;
    /**
     * 贡献次数
     */
    private int contributions;
}

上述被注释的、使用注解@FeignClient的方法也可以使用。MyDefaultFallback类是容错类。下面创建一个controller:

import com.swagger.demo.bean.Contributor;
import com.swagger.demo.bean.GithubDTO;
import com.swagger.demo.service.GithubFeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/github")
public class GithubClientController {

    @Resource
    private GithubFeignClient githubFeignClient;

    @PostMapping("/listContributors")
    public ResponseEntity<List<Contributor>> listContributors(@RequestBody GithubDTO githubDTO) {

        return githubFeignClient.listContributors(githubDTO.getOwner(), githubDTO.getFeign());
    }
}

创建idea http类型的测试用例:

### 查询github 贡献者信息
POST http://localhost:8087/wiener/github/listContributors
Content-Type: application/json

{
  "owner": "openFeign",
  "feign": "feign"
}

启动服务,执行如上测试用例,执行结果如下所示,说明服务调用成功:

last-modified: Tue, 01 Feb 2022 03:52:53 GMT
link: <https://api.github.com/repositories/10981994/contributors?page=2>; rel="next", <https://api.github.com/repositories/10981994/contributors?page=6>; rel="last"


[
  {
    "login": "adriancole",
    "contributions": 135
  },
  {
    "login": "velo",
    "contributions": 126
  },
  {
    "login": "kdavisk6",
    "contributions": 121
  },
  {
    "login": "snyk-bot",
    "contributions": 45
  },
  {
    "login": "quidryan",
    "contributions": 43
  },
  {
    "login": "rspieldenner",
    "contributions": 14
  },
  {
    "login": "davidmc24",
    "contributions": 12
  },
  {
    "login": "radio-rogal",
    "contributions": 12
  },
  {
    "login": "ahus1",
    "contributions": 6
  },
  {
    "login": "spencergibb",
    "contributions": 5
  },
  {
    "login": "ashleyfrieze",
    "contributions": 5
  },
  {
    "login": "allenxwang",
    "contributions": 5
  },
  {
    "login": "gimbimloki",
    "contributions": 4
  },
  {
    "login": "jkschneider",
    "contributions": 4
  },
  {
    "login": "nmiyake",
    "contributions": 4
  },
  {
    "login": "rfalke",
    "contributions": 4
  },
  {
    "login": "SimY4",
    "contributions": 3
  },
  {
    "login": "bstick12",
    "contributions": 3
  },
  {
    "login": "mstrYoda",
    "contributions": 3
  },
  {
    "login": "jacob-meacham",
    "contributions": 3
  },
  {
    "login": "pnepywoda",
    "contributions": 3
  },
  {
    "login": "santhosh-tekuri",
    "contributions": 3
  },
  {
    "login": "jerzykrlk",
    "contributions": 3
  },
  {
    "login": "Augustine-C",
    "contributions": 2
  },
  {
    "login": "benmanbs",
    "contributions": 2
  },
  {
    "login": "schlosna",
    "contributions": 2
  },
  {
    "login": "dharmeshjogadia",
    "contributions": 2
  },
  {
    "login": "edio",
    "contributions": 2
  },
  {
    "login": "androidfred",
    "contributions": 2
  },
  {
    "login": "stromnet",
    "contributions": 2
  }
]

小结

  以上就是这篇文章的全部内容了,希望本文对大家的学习或者工作具有一定的参考和学习价值;如果有疑问,大家可以在评论区留言交流,也希望大家多多点赞关注。谢谢大家对楼兰胡杨的支持!

Reference

posted @ 2021-12-25 21:18  楼兰胡杨  阅读(12168)  评论(0编辑  收藏  举报