Call service interface using Feign

FeignIt is a declarative RESTclient. FeignHaving pluggable annotation features pluggable encoder and decoder. FeignThe default integrated Ribbonand and Eurekacombined, the default implementation of load balancing.

The introduction of dependence

Use Feign, we need to introduce spring-cloud-starter-openfeigndependence, and in order to cooperate Consul, but also the introduction of spring-cloud-starter-consul-discoverydependence:

<!-- 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 @EnableFeignClientsnotes open Feignfunction. There is no need to apply (consumers) registered to the Consulabove, there is no need to use @EnableDiscoveryClientNotes:

@SpringBootApplication
@EnableFeignClients
public class ConsulConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsulConsumerApplication.class, args);
    }
}

Configure service-related information

Because Feginneed from the Consulservice information registration of the above, you need to configure Consuladdress. 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

FeginIt is to call the service interface by using annotations on the interface. @FeignClientNote describes the service name to be acquired, Feignbut also with the SpringMVCvarious interfaces to describe information such as path and interface parameters.

A definition of IService1the 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/hellothis interface.

use

Now define a AppControllerinjected definition IService1and use it:

@RestController
public class AppController {

    @Autowired
    private IService1 service1;

    @GetMapping("/callService1Hello")
    public String callService1HelloInterface() {
        return service1.sayHello();
    }
}

Start client authentication

Start consul-consumer-feignthe client can call to verify service1the /hellointerfaces:

Here Insert Picture Description

Published 178 original articles · won praise 152 · views 610 000 +

Guess you like

Origin blog.csdn.net/hbtj_1216/article/details/104244519