1、FeignClient註解git
FeignClient註解被@Target(ElementType.TYPE)修飾,表示FeignClient註解的做用目標在接口上github
1
2
3
4
5
|
@FeignClient(name =
"github-client"
, url =
"https://api.github.com"
, configuration = GitHubExampleConfig.
class
)
public
interface
GitHubClient {
@RequestMapping(value =
"/search/repositories"
, method = RequestMethod.GET)
String searchRepo(@RequestParam(
"q"
) String queryStr);
}
|
聲明接口以後,在代碼中經過@Resource注入以後便可使用。@FeignClient標籤的經常使用屬性以下:spring
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@FeignClient(name =
"github-client"
,
url =
"https://api.github.com"
,
configuration = GitHubExampleConfig.
class
,
fallback = GitHubClient.DefaultFallback.
class
)
public
interface
GitHubClient {
@RequestMapping(value =
"/search/repositories"
, method = RequestMethod.GET)
String searchRepo(@RequestParam(
"q"
) String queryStr);
/**
* 容錯處理類,當調用失敗時,簡單返回空字符串
*/
@Component
public
class
DefaultFallback implements GitHubClient {
@Override
public
String searchRepo(@RequestParam(
"q"
) String queryStr) {
return
""
;
}
}
}
|
在使用fallback屬性時,須要使用@Component註解,保證fallback類被Spring容器掃描到,GitHubExampleConfig內容以下:json
1
2
3
4
5
6
7
|
@Configuration
public
class
GitHubExampleConfig {
@Bean
Logger.Level feignLoggerLevel() {
return
Logger.Level.FULL;
}
}
|
在使用FeignClient時,Spring會按name建立不一樣的ApplicationContext,經過不一樣的Context來隔離FeignClient的配置信息,在使用配置類時,不能把配置類放到Spring App Component scan的路徑下,不然,配置類會對全部FeignClient生效.api
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@RestController
@RequestMapping(
"/v1/card"
)
public
class
IndexApi {
@PostMapping(
"balance"
)
@ResponseBody
public
Info index() {
Info.Builder builder =
new
Info.Builder();
builder.withDetail(
"x"
, 2);
builder.withDetail(
"y"
, 2);
return
builder.build();
}
}
|
Feign Clientapp
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@FeignClient(
name =
"card"
,
url =
"http://localhost:7913"
,
fallback = CardFeignClientFallback.
class
,
configuration = FeignClientConfiguration.
class
)
@RequestMapping(value =
"/v1/card"
)
public
interface
CardFeignClient {
@RequestMapping(value =
"/balance"
, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
Info info();
}
|
if @RequestMapping is used on class, when invoke http /v1/card/balance, like this :ide
若是 @RequestMapping註解被用在FeignClient類上,當像以下代碼請求/v1/card/balance時,注意有Accept header:微服務
1
2
3
4
|
Content-Type:application/json
Accept:application/json
POST http:
//localhost:7913/v1/card/balance
|
那麼會返回 404。ui
若是不包含Accept header時請求,則是OK:this
1
2
|
Content-Type:application/json
POST http:
//localhost:7913/v1/card/balance
|
或者像下面不在Feign Client上使用@RequestMapping註解,請求也是ok,不管是否包含Accept:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@FeignClient(
name =
"card"
,
url =
"http://localhost:7913"
,
fallback = CardFeignClientFallback.
class
,
configuration = FeignClientConfiguration.
class
)
public
interface
CardFeignClient {
@RequestMapping(value =
"/v1/card/balance"
, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
Info info();
}
|