Feign
It is a declarative REST
client. Feign
Having pluggable annotation features pluggable encoder and decoder. Feign
The default integrated Ribbon
and and Eureka
combined, the default implementation of load balancing.
The introduction of dependence
Use Feign
, we need to introduce spring-cloud-starter-openfeign
dependence, and in order to cooperate Consul
, but also the introduction of spring-cloud-starter-consul-discovery
dependence:
<!-- 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 open function
Need to use on startup class @EnableFeignClients
notes open Feign
function. There is no need to apply (consumers) registered to the Consul
above, there is no need to use @EnableDiscoveryClient
Notes:
@SpringBootApplication
@EnableFeignClients
public class ConsulConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsulConsumerApplication.class, args);
}
}
Configure service-related information
Because Fegin
need from the Consul
service information registration of the above, you need to configure Consul
address. There are also configured for the current client context /consul-consumer-feign
, port number 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
Custom Client Interface
Fegin
It is to call the service interface by using annotations on the interface. @FeignClient
Note describes the service name to be acquired, Feign
but also with the SpringMVC
various interfaces to describe information such as path and interface parameters.
A definition of IService1
the interface:
@FeignClient("service1") // 描述要获取的服务名
@RequestMapping("/service1") // 服务上下文路径
public interface IService1 {
@GetMapping("/hello") // 接口
public String sayHello();
}
The above interface definition can be interpreted as calling http://service1-ip:sercive1-port/service1/hello
this interface.
use
Now define a AppController
injected definition IService1
and use it:
@RestController
public class AppController {
@Autowired
private IService1 service1;
@GetMapping("/callService1Hello")
public String callService1HelloInterface() {
return service1.sayHello();
}
}
Start client authentication
Start consul-consumer-feign
the client can call to verify service1
the /hello
interfaces: