快速使用 Feign, 无需在本项目中定义一个接口去与目标接口进行匹配
使用方法
1. 创建 SpringCloud 项目并加入依赖
- <dependency>
- <groupId>cn.gjing</groupId>
- <artifactId>tools-starter-feign</artifactId>
- <version>1.0.0</version>
- </dependency>
2. 启动类标注 @EnableFeignUtil 注解
- @SpringBootApplication
- @EnableEurekaClient
- @EnableFeignUtil
- public class FeignApplication {
- public static void main(String[] args) {
- SpringApplication.run(FeignApplication.class, args);
- }
- }
3. 使用案例
- @RestController
- public class TestController {
- @GetMapping("/test1")
- @ApiOperation(value = "测试 1", httpMethod = "GET")
- public ResponseEntity test1() throws URISyntaxException {
- Map<String, String> map = new HashMap<>(16);
- map.put("a", "参数 a");
- // 使用 URL 访问, 自定义返回值类型
- String result = FeignClientUtil.of(String.class, RouteType.URL, "http://127.0.0.1:8090/")
- .execute(HttpMethod.POST, map, null, "/method1")
- .getResult();
- return ResponseEntity.ok(result);
- }
- @GetMapping("/test2")
- public ResponseEntity test2() throws URISyntaxException {
- Map<String, String> map = new HashMap<>(16);
- map.put("a", "参数 a");
- map.put("b", "参数 b");
- // 使用服务名访问, 带负载均衡功能, 自定义返回值类型
- String result = FeignClientUtil.of(String.class, RouteType.NAME, "http://demo")
- .execute(HttpMethod.POST, map, null, "/method2")
- .getResult();
- return ResponseEntity.ok(result);
- }
- @GetMapping("/test3")
- public ResponseEntity test3() throws URISyntaxException {
- // 使用服务名访问, 带负载均衡功能, 默认返回值类型(String)
- String result = FeignClientUtil.defaultByName("http://demo")
- .execute(HttpMethod.GET, null, null, "/method3/123")
- .getResult();
- return ResponseEntity.ok(result);
- }
- @GetMapping("/test4")
- public ResponseEntity test4() throws URISyntaxException {
- // 使用 URL 访问, 默认返回值类型(String)
- String result = FeignClientUtil.defaultByUrl("http://127.0.0.1:8080")
- .execute(HttpMethod.GET, null, null, "/method")
- .getResult();
- return ResponseEntity.ok(result);
- }
- }
- tip:
以上案例中 demo 为注册到 eureka 的服务名, method 为目标方法的请求路径, 如果类上标有 @RequestMapping, 也需要和其路径一同拼接;
使用 URL 请求时, 可请求与当前服务不在同一个 Eureka 注册中心下的其他服务接口;
使用 Name 请求时, 会带负载均衡功能, 必须与当前服务在同一个 Eureka 注册中心下;
FeignClientUtil 中的方法 :
1. 生成实例
of (responseType, routeType, targetAddress): 生成自定义返回类型和路由类型的 FeignClientUtil 实例
defaultByName (targetAddress): 生成默认返回类型 (String) 的服务名路由请求类型的 FeignClientUtil 实例, 必须在同一个 Eureka 注册中心下的其他服务;
defaultByUrl (targetAddress): 生成默认返回类型 (String) 的 URL 请求类型的 FeignClientUtil 实例, 可以访问与当前服务不在同一个 Eureka 中心下的其他服务;
2. 发起请求
execute (method, queryMap, body, methodPath): 发起请求
3. 获取请求结果
getResult (): 获取返回结果
方法中的参数:
responseType: 返回值类型( 必填 ), 否则 NPE;
routeType: 路由类型( 必填 ),URL 或者 NAME;
targetAddress: 目标地址( 必填 ), 如果是 NAME 路由则需要协议 + 服务名, 如: http://serve , 如果为 URL 路由, 需要协议 + IP + 端口, 如: http://127.0.0.1:8080
methodPath: 接口路径( 必填 ), 如: /method/test;
queryMap: 参数, 无参可传 null;
body: post 发送 JSON 时使用, 目标方法使用 @RequestBody 接收参数时使用, 不需要时可以传 null;
更多信息可前往 GitHub:tools-starter-feign, 希望各位小伙伴帮忙点个喜欢和关注哦!
来源: http://www.jianshu.com/p/680a1244e3cd