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
接口: