- 使用Feign的第1步是在项目的pom.xml文件中添加Feign依赖:
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-openfeignartifactId>
dependency>
- 使用Feign的第2步是在主函数的类上添加@EnableFeignClient,在客户端启动Feign:
package com.crazymaker.springcloud.user.info.start;
...
@EnableFeignClients(basePackages = { "com.crazymaker.springcloud.seckill.remote.client"}, defaultConfiguration = {TokenFeignConfiguration.class} )
public class UserCloudApplication {
public static void main(String[] args) {
SpringApplication.run(UserCloudApplication.class, args);
}
}
- 使用Feign的第3步是编写声明式接口。这一步将远程服务抽象成一个声明式的FeignClient客户端,示例如下:
package com.crazymaker.springcloud.seckill.remote.client;
...
@FeignClient(value = "seckill-provider", path = "/api/demo/")
public interface DemoClient {
@GetMapping("/hello/v1")
Result<JSONObject> hello();
@RequestMapping(value = "/echo/{word}/v1", method = RequestMethod.GET)
Result<JSONObject> echo( @PathVariable(value = "word") String word);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
在上面接口的@FeignClient注解配置中,使用value指定了需要绑定的服务,使用path指定了接口的URL前缀。然后使用@GetMapping和@RequestMapping两个方法级别的注解分别声明了两个远程调用接口。 - 使用Feign的第4步是调用声明式接口。
package com.crazymaker.springcloud.user.info.controller;
...
@Api(value = "基础学习DEMO", tags = {"基础学习DEMO"})
@RestController
@RequestMapping("/api/demo")
public class DemoController {
@Resource
DemoClient demoClient;
@GetMapping("/say/hello/v1")
@ApiOperation(value = "Feign远程调用")
public Result<JSONObject> hello() {
Result<JSONObject> result = demoClient.hello();
JSONObject data = new JSONObject();
data.put("remote", result);
return Result.success(data).setMsg("操作成功");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20