在SpringCloud中使用openfeign进行服务调用

众所周知,openfeign是SpringCloud中一个很重要的用于服务间调用的组件。它大大节省了我们进行http请求的代码量,通过接口声明式的调用方式,让我们代码变得异常优雅。既然如此,我们就来使用一下好了。

在SpringCloud项目中开启Openfeign:

当然是在pom中引入依赖!同时在启动类中添加启用openfeign的注解。

1
@EnableFeignClients

声明一个服务接口类:

首先,你得定义一个用于服务调用的interface。定义这个interface也很简单,拿 Httpbin.org/get 来举例子。代码大概如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 这里省略掉了一大坨命名空间。。。

@FeignClient(value = "httpbin", url = "https://httpbin.org")
public interface HttpBinClient {

@RequestMapping(value = "/get", method = RequestMethod.GET)
@Headers({
"Accept: application/json",
"Content-Type: application/json"
})
String mGet();

@RequestMapping(value = "/post", method = RequestMethod.POST)
@Headers({
"Accept: application/json",
"Content-Type: application/json",
"Authorization: Bearer {token}"
})
String mPost(@RequestHeader String token);
}

在该调用的地方调用

比如在controller中,我们可以这样写:

1
2
3
4
5
6
7
8
9
// 这里省略掉了一大波次要代码

@GetMapping(value = "httpbin/get")
public String httpBinGet() {
String res = hBClient.mGet();
HttpBinGet get = JSONObject.parseObject(res, HttpBinGet.class);
log.info("{}", get);
return hBClient.mGet();
}

将获取到的response通过fastjson解析到实体类

上面代码中的如下行,就干了这件事情

1
HttpBinGet get = JSONObject.parseObject(res, HttpBinGet.class);

HttpBinGet 类如下:

1
2
3
4
5
@Data
public class HttpBinGet {
private String url;
private String origin;
}

好了,一气呵成。