使用Feign调用服务接口
Feign是一个声明式的REST客户端。Feign具有可插拔的注解特性,支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
引入依赖
使用Feign,需要引入spring-cloud-starter-openfeign依赖,同时为了配合 Consul,还要引入spring-cloud-starter-consul-discovery依赖:
<!-- spring cloud openfeign依赖 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!-- spring cloud consul依赖 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency>
开启Feign的功能
需要在启动类上使用@EnableFeignClients注解开启Feign功能。这里不需要将应用(消费者)注册到Consul上面,因此不需要使用@EnableDiscoveryClient注解:
@SpringBootApplication @EnableFeignClients public class ConsulConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsulConsumerApplication.class, args); } }
配置服务相关信息
因为Fegin需要从Consul上面获取注册的服务信息,所以需要配置Consul的地址。这里还配置了当前客户端上下文为/consul-consumer-feign,端口号为8757。
server: address: 169.254.186.87 port: 8757 servlet: context-path: /${spring.application.name} spring: application: name: consul-consumer-feign cloud: consul: host: 192.168.232.129 port: 8900
定义客户端接口
Fegin是通过在接口上使用注解来调用服务接口的。@FeignClient注解描述要获取的服务名,Feign还可以配合SpringMVC的各种接口来描述接口的路径和参数等信息。
定义一个IService1接口:
@FeignClient("service1") // 描述要获取的服务名 @RequestMapping("/service1") // 服务上下文路径 public interface IService1 { @GetMapping("/hello") // 接口 public String sayHello(); }
上面的接口定义可以理解为调用 http://service1-ip:sercive1-port/service1/hello这个接口。
使用
现在定义一个AppController,注入定义的IService1,并使用它:
@RestController public class AppController { @Autowired private IService1 service1; @GetMapping("/callService1Hello") public String callService1HelloInterface() { return service1.sayHello(); } }
启动客户端验证
启动consul-consumer-feign客户端验证是否能够调用service1的/hello接口: