OpenFeign

OpenFeifn also simplifies the development of service invocation clients by automatically encapsulating them when using Spring Cloud Ribbon compared to the Ribbon. Feign integrates with the Ribbon, which maintains the Payment service list and implements load balancing for clients through polling. Unlike the Ribbon, Feign provides elegant and simple service invocation in a declarative way by defining the service binding interface

Method of use

  • Interface + note: Micro service invocation interface + @feignClient

  • Create a new cloud-consumer-OpenFeign-Order80 consumer

  • pom

    <dependencies>
            <! --openfeign-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
            <! --eureka client-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
            <dependency><! -- Introduced a generic API package that allows you to pay Entity using Payment -->
                <groupId>com.cloud</groupId>
                <artifactId>cloud-api-commons</artifactId>
                <version>1.0 the SNAPSHOT</version>
            </dependency>
            <! --web-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            <! -- Basic General Configuration -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    Copy the code
  • The main startup class is added @enableFeignClients

  • Create the business layer interface PaymentFeignService interface and add the annotation @feignClient

    @getMapping (“/payment/get/{id}”)

    @Component
    @FeignClient(value = "CLOUD-PAYMENT-SERVICE")
    public interface OpenFeignService {
        @GetMapping("/payment/get/{id}")
        public Result<Payment> getPaymentById(@PathVariable("id") Long id);
    }
    Copy the code
  • I’m going to write Controller and I’m going to write it normally

    @RestController
    @Slf4j
    public class FeignController {
    
        @Resource
        private OpenFeignService openFeignService;
    
        @GetMapping(value = "/consumer/payment/get/{id}")
        public Result<Payment> getPaymentById(@PathVariable("id") Long id)
        {
            returnopenFeignService.getPaymentById(id); }}Copy the code
  • test

    Start – > 8001/8002 – > 80 7001

    When tested, OpenFeign comes with its own load balancing configuration because it also integrates with the Ribbon package.

OpenFeign Timeout setting

  • Deliberately let port 8001 sleep for a while

     @GetMapping(value = "/payment/feign/timeout")
        public String paymentFeignTimeOut(a)    {
            System.out.println("*****paymentFeignTimeOut from port: "+port);        // Pause the thread for a few seconds
            try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
               return port;
        }
    Copy the code
  • Test the

  • We didn’t find the interface message 404, because feign’s default request is 1 second, and we let the application fall asleep for 3 seconds. The user can’t wait until they tell him that there is no such request. If the application is really complicated, we need to manually adjust the maximum time limit.

    The timing of the ribbon is the same because Feign has integrated the ribbon

    ribbon:
      ReadTimeout: 5000 # milliseconds, same as Feign's
      ConnectTimeout: 5000 #, same as Feign's
    Copy the code
  • The next test will wait three seconds to get the data

  • Feign configuration

    feign:
    	client:
    		config:
    			default:	// The representative Service, default is any service. You can specify the service name to specify the timeout period for invoking the service
    				connectTimeout: Milliseconds: timeout period for establishing a connection. It is used only for discovering services
    				readTimeout: Millisecond time , the timeout period of the interface request
    
    Copy the code

OpenFeign logs are printed

  • Feign provides log printing, which can be configured to adjust the log level to understand the details of Http requests in Feign. To put it more plainly, it monitors and outputs the calls to Feign interfaces. Fewer interfaces now, and more interfaces in the future can be better maintained.

  • The configuration class

    @Configuration
    public class FeignConfig {
        @Bean
        Logger.Level feignLoggerLevel(a){
            returnLogger.Level.FULL; }}Copy the code
  • Yml configuration

    Logging: level: # feign level monitoring log in Which interface com. WZJ. Springcloud. Service. OpenFeignService: debugCopy the code
  • Start the test

Openfeign and feign

Feign is a lightweight RESTful HTTP service client in the Spring Cloud component. Feign has the Ribbon built in, which is used to load balance clients and invoke services in the service registry. Feign is used by using Feign’s annotations to define an interface that can be invoked to invoke the services of the service registry. OpenFeign is a Spring Cloud annotation that supports SpringMVC on top of Feign, such as @requesMapping, etc. OpenFeign’s @FeignClient can parse the interface under SpringMVC’s @RequestMapping annotation and generate implementation classes through dynamic proxy, which can perform load balancing and call other services. org.springframework.cloud spring-cloud-starter-feign org.springframework.cloud spring-cloud-starter-openfeign

Feign OpenFeign
Feign is a lightweight RESTful HTTP service client in the Spring Cloud component. The Ribbon is built into Feign to load balance clients and invoke services in the service registry. It is Spring Cloud that supports SpringMVC annotations on top of Feign, such as @requesMapping and so on.
Feign is used by using Feign’s annotations to define an interface that can be invoked to invoke the services of the service registry. OpenFeign’s @FeignClient can parse the interface under SpringMVC’s @RequestMapping annotation and generate implementation classes through dynamic proxy, which can perform load balancing and call other services.
org.springframework.cloud spring-cloud-starter-feign org.springframework.cloud spring-cloud-starter-openfeign

Why OpenFeig with the Ribbon?

Let’s make it a little bit more logical for convenience. For example, we used Ribbon+RestTemplate to get exposed ports. We did this directly in Controller, and the code was not smooth, right? And how did we write the code before? At the beginning of the class, the teacher emphasized the dao-service-controller, but if you use it, you can’t call the service. If you violate your original will, it’s not that serious. OpenFeign, which wraps the Ribbon around the interface and annotates it, makes it much easier to write. The controller interface of 8001 is the 80-end serviceImpl or DAO layer.