preface

OpenFeign integrates the Ribbon with Hystrix and simplifies service invocation, making it easy to use.

Start the configuration

Importing dependent dependencies

  • SpringCloud version: Hoxton.sr1
  • SpringBoot version: 2.2.4.release

The new version of SpringCloud has some changes to OpenFeign. Use the old version first, and then fill in the holes when you figure it out.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<! You must import a web dependency or you will not be able to start.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code

Start class annotations

Add @enableeurekaclient and @EnableFeignClients annotations

@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
public class FeignConsumerApplication {
    public static void main(String[] args) { SpringApplication.run(FeignConsumerApplication.class, args); }}Copy the code

Service provider

The service provider has three interfaces to test Json parameters, object parameters, and normal parameters

@RestController
public class Controller {
    @RequestMapping("/getUser3")
    public User getUser3(@RequestBody User user) throws InterruptedException {
        return user;
    }

    @RequestMapping("/getUser2")
    public User getUser2(User user) throws InterruptedException {
        return user;
    }

    @RequestMapping("/getUsers")
    public String[] getUsers(String ids) throws InterruptedException {
        return ids.split(","); }}Copy the code

Implementing service invocation

OpenFeign is very simple to implement the service invocation

  • Creating an interface
  • add@FeignClient("provider")Note that provider is the name of the service
  • Writing interface methods

The interface methods are basically the same as the service provider’s Controller code, but the parameter bindings are a little different, see the code comments

  • Define the request mode
  • Define the parameters
  • Defining return values
@FeignClient"provider")
public interface Service {
    // The @requestParam annotation must be used otherwise the provider will not receive it
    @GetMapping("/getUsers")
    String[] get(@RequestParam("ids") String ids);

    // Pass object parameters with @springQueryMap annotations
    @GetMapping("/getUser2")
    User get2(@SpringQueryMap User user);

    // Pass Json parameters with the @requestBody annotation
    @GetMapping("/getUser3")
    User get3(@RequestBody User user);
}
Copy the code

Once the interface is defined, it can be used directly, without the need for an implementation class, and is called by the Controller layer below

// Inject the interface defined above
@Autowired
private Service service;

/ / Controller layer method
@GetMapping("/getUsers")
public String[] getUsers(String ids){
    // Call the interface's methods
    return service.get(ids);
}
Copy the code

Ribbon configuration

OpenFeign is integrated with the Ribbon. See the SpringCloud Ribbon tutorial in this article for Ribbon configuration

Hystrix configuration

OpenFeign is integrated with Hystrix, which is turned off by default and needs to be enabled first

feign:
  hystrix:
    enabled: true
Copy the code

Hystrix configuration is consistent with this article SpringCloud Hystrix tutorial

Define service degradation logic

OpenFeign’s service degradation configuration is a little different

  • Create a class that implements the Service interface defined above. This class is the Service degradation handling class
  • Assemble this class into the Spring container and use@Componentannotations
@Component
public class ServiceFallback implements Service{
    @Override
    public String[] get(String ids) {
        System.out.println("Downgrade");
        return new String[0];
    }

    @Override
    public User get2(User user) {
        System.out.println("Downgrade");
        return null;
    }

    @Override
    public User get3(User user) {
        System.out.println("Downgrade");
        return null; }}Copy the code
  • Add annotations on the Service interfacefallback = ServiceFallback.classSpecifies the degradation handling class
@FeignClient(value = "provider",fallback = ServiceFallback.class)
public interface Service {
    @GetMapping("/getUsers")
    String[] get(@RequestParam("ids") String ids);

    @GetMapping("/getUser2")
    User get2(@SpringQueryMap User user);

    @GetMapping("/getUser3")
    User get3(@RequestBody User user);
}
Copy the code

OpenFeign configuration

The compression

feign:
  Enable request compression and response compression
  compression:
    request:
      enabled: true
      Which types to compress
      mime-types: text/xml,application/xml,application/json
      Compress when you exceed this size
      min-request-size: 2048
    response:
      enabled: true
      # GZIP compression
      useGzipDecoder: true
Copy the code

The log

OpenFeign logging level, which defines which information to log

  • NONE: No information is recorded.
  • BASIC: Records only the request method, URL, and response status code and execution time.
  • HEADERS: In addition to BASIC level information, request and response HEADERS are recorded.
  • FULL: Records details of all requests and responses, including header information, request body, and metadata.

Start the class to add logging configuration

@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
public class FeignConsumerApplication {

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

    /** * feign log *@return* /
    @Bean
    Logger.Level feignLoggerLevel(a) {
        returnLogger.Level.FULL; }}Copy the code

The log level is defined in the configuration file. The log level here is different from the previous one. Feign logging only responds to the debug level

# log level
logging:
  level:
    com:
      example:
        feignconsumer:
            Service: debug
Copy the code

Access interface can see console output log

The 16:29:02 2021-02-03. 17308-817 the DEBUG [trix - the provider - 1] com. Example. Feignconsumer. Service: [Service#get2] <-- HTTP/1.1 200 (554ms) 2021-02-03 16:29:02.817 DEBUG 17308 -- [trix-provider-1] com.example.feignconsumer.Service : [Service#get2] connection: Keep - alive 16:29:02 2021-02-03. 17308-817 the DEBUG com [trix - the provider - 1]. The example. Feignconsumer. Service: [Service#get2] content-type: Application/json 16:29:02 2021-02-03. 17308-817 the DEBUG com [trix - the provider - 1]. The example. Feignconsumer. Service: [Service#get2] date: Wed, 3 Feb 2021 08:29:02 GMT 16:29:02 2021-02-03. 17308-818 the DEBUG com [trix - the provider - 1]. The example. Feignconsumer. Service: [Service#get2] keep-alive: Timeout = 60 16:29:02 2021-02-03. 17308-818 the DEBUG com [trix - the provider - 1]. The example. Feignconsumer. Service: [Service#get2] transfer-encoding: Chunked 16:29:02 2021-02-03. 17308-818 the DEBUG com [trix - the provider - 1]. The example. Feignconsumer. Service: [Service# get2] 16:29:02 2021-02-03. 17308-822 the DEBUG com [trix - the provider - 1]. The example. Feignconsumer. Service: [Service#get2] {" ID ": NULL,"name":"1","password":"2"} 2021-02-03 16:29:02.822 DEBUG 17308 - [trix-provider-1] com.example.feignconsumer.Service : [Service#get2] <--- END HTTP (37-byte body)Copy the code