背景
实际开发中我们经常会面临在同一个eureka注册中心下的各个微服务之间互相调用彼此的接口来获取预期的数据。通过Spring Cloud Feign,我们只需要创建一个接口并用注解的方式来配置它,即可完成对服务提供方的接口绑定。
被调用服务及接口: hello-service服务的/hello接口。返回 hello world.
主微服务:feign-consumer
步骤
修改pom.xml
创建spring boot工程feign-comsumer,在pom.xml中引入spring-cloud-starter-eureka和spring-cloud-starter-feign
- 1
2 3 4 5 6 7 8 9
| - <dependency>
<groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> <version>1.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
|
修改主类
修改应用主类ConsumerApplication,并通过@EnableFeignClients注解开启Spring Cloud Feign的支持功能。
- 1
2 3 4 5 6
| - @EnableFeignClients
@EnableDiscoveryClient @SpringBootApplication public class ConsumerApplication { … }
|
创建接口
定义HelloService接口,通过@FeignClient注解指定服务名来绑定服务,然后再使用Spring MVC的注解来绑定具体该服务提供的REST接口。
- 1
2 3 4 5
| - @FeignClient(“hello-service”)
public interface HelloService{ @RequestMapping(“/hello”) String hello(); }
|
创建controller
接着创建一个controller来实现对Feign客户端的调用。使用@Autowired直接注入上面定义的HelloService实例,并在helloConsumer函数中调用这个便规定了hello-service服务接口的客户端来向该服务发起/hello接口调用。
- 1
2 3 4 5 6 7 8 9 10
| - @RestController
public class ConsumerController{ @Autowired HelloService helloService;
@RequestMapping(value=”/feign-consumer“,method=RequestMethod.GET) public String helloConsumer(){ return helloService.hello(); } }
|
参数绑定
上面的例子中我们实现的是一个不带参数的REST服务绑定。然而现实系统中的各种业务接口要比它复杂的多,我们会在HTTP的各个位置传入各种不同类型的参数,并且在返回请求响应的时候也可能是一个复杂的对象结构。
修改接口声明
- 1
2 3 4 5 6 7 8 9 10 11 12 13 14 15
| - @FeignClient(“hello-service”)
public interface HelloService{
@RequestMapping(“/hello”) String hello(); @RequestMapping(value=“/hello1”,method-RequestMethod.GET) String hello(@RequestParam(“name”) String name);
@RequestMapping(value=“/hello2”,method-RequestMethod.GET) User hello(@RequestHeader(“name”) String name);
@RequestMapping(value=“/hello3”,method-RequestMethod.GET) String hello(@RequestBody User user); }
|
注意:在定义各参数绑定时,@RequestParam, @RequestHeader 等可以指定参数名称的注解,它们的value千万不能少。在springmvc程序中,这些注解会根据参数名来作为默认值,但是Feign中绑定参数必须通过value属性来指明具体的参数名,否则会抛出IllegalStateException异常,value属性不能为空
还没有评论,来说两句吧...