Location>code7788 >text

5. Spring Cloud OpenFeign declarative WebService client ultra-detailed use of the

Popularity:668 ℃/2024-11-21 16:44:28

5. Spring Cloud OpenFeign declarative WebService client ultra-detailed use of the

@

catalogs
  • 5. Spring Cloud OpenFeign declarative WebService client ultra-detailed use of the
  • preamble
  • 1. Introduction to OpenFeign
    • 1.1 Feign and OpenFeign Differences
  • 2. Examples of OpenFeign applications
    • 2.2 Notes and details
  • 3. OpenFeign's built-in "logging configuration" operations
    • 3.1 OpenFeign Configuration Log-Application Example
  • 4. OpenFeign timeout setting operation
  • 5. Supplement: spring-boot-starter-actuator is a spring boot program monitoring system , you can realize the health check .
  • 6. Summary:
  • 7. Finally:

preamble

  • Corresponding to the previous study: 🌟🌟🌟🌟🌟🌟🌟🌟🌟🌟🌟4. Spring Cloud Ribbon to achieve "load balancing" detailed configuration_ribbon upgraded to loadbalancer-CSDN Blog
  • Corresponding to the next study: 🌟🌟🌟🌟🌟🌟🌟🌟🌟🌟🌟

1. Introduction to OpenFeign

What is OpenFeign?

  1. OpenFeign is a declarativeWebService clients, using OpenFeign makes it easier to write Web Service clients.

  2. It is usedDefine a service interface and add annotations to it.

  3. OpenFeign also supports pluggableencoderscap (a poem)codec

  4. Spring Cloud encapsulates OpenFeign so that it supports the Spring MVC annotations and theHttpMessageConverters

  5. OpenFeign can be used in combination with Eureka and Ribbon to support load balancing.

  6. OpenFeign official website address:/spring-cloud/spring-cloud-openfeign

Simply put: it is a Web Service client access, forwarding a component that can realize the communication of the Server cluster, simplifying the Web Service client.

在这里插入图片描述

1.1 Feign and OpenFeign Differences

Feign:

  • Feign is a lightweight RESTful HTTP service client for Spring Cloud components.
  • Feign has a built-in Ribbon that is used for client load balancing to invoke services from the service registry.
  • Feign is used in the following way: Define interfaces using Feign annotations to invoke services from the service registry.
  • Refer to the official documentation for annotations and usage supported by Feign./OpenFeign/feign
  • Feign itselfAnnotations for Spring MVC are not supported It has its own set of annotations, so most of the market has moved away from using Feign.
  • Introducing dependency:
<dependency>
    <groupId></groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

OpenFeign:

  • OpenFeign is Spring Cloud's first step in the development ofFeign is based on support for Spring MVC annotations, such as @RequestMapping and so on.
  • OpenFeign's @FeignClient cananalyze Interfaces under the @RequestMapping annotation in Spring MVC.
  • OpenFeign generates implementation classes by means of dynamic proxies, which do load balancing and call other services.
    Introducing dependencies.
   <!-- pull into openfeign -->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
  • In a nutshell: OpenFeign is an enhancement of Feign, and some programmers say Feign is OpenFeign for convenience.

2. Examples of OpenFeign applications

Requirements Analysis & Illustration

Schematic:

在这里插入图片描述

  1. Creating Service Consumption Modules - Remote Calls via OpenFeigen

consultation member-service-consumer-80 establish member-service-consumer-openfeign-80(a concrete step 骤consultation以前)

在这里插入图片描述

  1. exist file to import the relevant jar dependencies. In particular, here: our main characteropenFeign

在这里插入图片描述

  <!-- pull into openfeign -->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

complete Document Information:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0"
         xmlns:xsi="http:///2001/XMLSchema-instance"
         xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.">
    <parent>
        <artifactId>e-commerce-center</artifactId>
        <groupId></groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>member-service-consumer-openfeign-80</artifactId>


    <!-- Introduce relevant dependencies:We introduce the currently required dependencies,If you need anything else later,Flexibility to add more-->
    <dependencies>

        <!-- pull into openfeign -->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <!-- pull into web-starter clarification:We use version arbitration(Inherited version from parent project)-->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--1. starter-actuator bespring boot Monitoring system for the program,Health checkups are possible,info information technology
         2. interviewshttp://localhost:80/actuator Related links can be seen,You can also do related configurations-->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>


        <!-- lombok pull into-->
        <dependency>
            <groupId></groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- pull into test-starter -->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- pull into我们自己对 bean encapsulate api module content-->
        <dependency>
            <groupId></groupId>
            <artifactId>e_commerce_center-common-api</artifactId>
            <version>${}</version>
        </dependency>

        <!-- pull into eureka-client dependencies -->
        <!-- take note of:There is a starter Don't pick the wrong one.-->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

</project>
  1. In the resourse directory, create the Some configuration information is provided as follows.

在这里插入图片描述

server.
  port: 80
spring.
  name: member-service-consumer-openfeign-80
    name: member-service-consumer-openfeign-80

# Configure eureka client Note that because the module is acting as a client here, it is necessary to send the client's information to the Server.
eureka.
  eureka: client: register-with-eureka: true
    register-with-eureka: true # Registers itself with Eureka-Server.
    fetch-registry: true # means to send information to Eureka-Server
    service-url.
      # Registers itself with the eureka-server
      # defaultZone: http://localhost:9001/eureka
      # Register this microservice with multiple eureka-servers, just use comma spacing
      defaultZone: :9001/eureka/,:9002/eureka/

  1. Create the modulemember-service-consumer-openfeign-80 's main launcher class, which is the scene launcher.

In: Create Package , create a file namedMemberConsumerOpenfeignApplication80of the main startup class, as shown in the following figure:

在这里插入图片描述

package ;


import ;
import ;
import ;
import ;

@SpringBootApplication
@EnableEurekaClient // expressed as Eureka Client character
@EnableFeignClients // activate (a plan) OpenFeignClient
public class MemberConsumerOpenfeignApplication80 {


    public static void main(String[] args) {

        (, args);
    }
}

After adding the main startup class, we can test to see if the module has successfully beenmember-service-consumer-openfeign-80 registered with Eureka Server.

在这里插入图片描述

Note: The following operation is: is the core of OpenFeign.

  1. at thatmember-service-consumer-openfeign-80 module to create a package, create aMemberFeignService interface, note that it is the interfaceinterface Not a class. As shown in the figure below:

在这里插入图片描述

package ;


import ;
import ;
import ;
import ;
import ;

@Component
public interface MemberFeignService {


}

And then we need to put in which wemember-service-consumer-openfeign-80 The module exists as an Eureka Client client, here we use OpenFeign to simplify the client, we also need to set which of our OpenFeigin (a.k.a. the client, a.k.a. the Eureka Client) we want to call.provider service (server/service cluster) To handle our business, here we areservice cluster Here we have two privoid services that can handle the business we need, as shown below: respectively:

member-service-provider-10000, member-service-provider-10002 (these two services are already registered with each other and configured for service clustering)

在这里插入图片描述

Here we are atMemberFeignService interface class using the@FeignClientannotation, which OpenFeigin (a.k.a. the client, a.k.a. Eureka Client) we want to call.provider service (server/service cluster) Handling our business. This is shown in the figure below:

在这里插入图片描述

package ;


import ;
import ;
import ;
import ;
import ;

@Component
// Here, MEMBER-SERVICE-PROVIDER is the name of the Eureka Server service provider registration.
@FeignClient(value = "MEMBER-SERVICE-PROVIDER") // This value is the name of the provider we want to access.
public interface MemberFeignService {

}

At the same time we also need to be inMemberFeignService Define a method in the interface.

Note that this method must be compatible with whichever OpenFeigin (aka client, aka Eureka Client) you want to call.provider service (server/service cluster) The processing of the corresponding operations in thewhich methodthat are consistent (permission modifiers are consistent, theHttp request method (includes the corresponding request mapping path)Consistency, parameter types, number of parameters are consistent, return value types are also consistent, method names can be inconsistent (but it is strongly recommended to keep the same)), so it is strongly recommended to copy directly from the corresponding provider service when you can. The following figure shows that we are using thegetMemberById The business process of querying based on id. We just need to copy its method name.

在这里插入图片描述

package ;


import ;
import ;
import ;
import ;
import ;

@Component
// Here, MEMBER-SERVICE-PROVIDER is the name of the Eureka Server service provider registration.
@FeignClient(value = "MEMBER-SERVICE-PROVIDER") // This value is the name of the provider we want to access.
public interface MemberFeignService {



    // Note: the method defined here is the interface to be called remotely, so it's recommended to copy it.

    // The method defined here is the interface to the remote call.
    1. The remote call method is get.
    2. The url of the remote call is http://MEMBER-SERVICE-PROVIDER(the alias registered to the service)/member/get/{id}
    -SERVICE-PROVIDER is the service that is registered with Eureka Server as the service provider method.
    4. openfeign will decide to call 10000/10002 based on load balancing - default is polling
    5. The benefit of openfeign is that it supports spring mvc annotations and interface deconstruction.
    6. To use OPFeign, you need to configure the corresponding scenario launcher: @EnableFeignClients // start OpenFeignClient

     */@EnableFeignClients // Start OpenFeignClient
    @GetMapping("/member/get/{id}")
    Result getMemberById(@PathVariable("id") Long id);


}

Finally, we are in the currentmember-service-consumer-openfeign-80 module aka our OpenFeigin (aka the client, aka Eureka Client ) writes the controller in the package, write the corresponding controller. This is shown in the following figure:

在这里插入图片描述

在这里插入图片描述

package ;


import ;
import ;
import ;
import ;
import ;

import ;

@RestController
public class MemberConsumerFeignController {

    // mountingMemberFeignService
    @Resource
    private MemberFeignService memberFeignService;

    @GetMapping("/member/consumer/openfeign/get/{id}")
    public Result getMemberById(@PathVariable("id") Long id) {
        // Calling a method in an interface
        return (id);

    }
}

  • In particular, because our OpenFeign is a program that is passed through theinterface + annotatedThe way as a Eureka Client client, call which the Service Server
  • Characteristics of the use of Openfeign:Microservice Interface + @FeignClient , decoupled using interfaces (simply put: the use of interfaces to call the corresponding provider to provide services to the cluster)

Test, start server

Browser input.http://localhost/member/consumer/openfeign/get/1

Observe that the service on port 10000/10002 is polled for accesses

在这里插入图片描述

2.2 Notes and details

  • @FeignClient(value = "MEMBER-SERVICE-PROVIDER") // The value value is the name of the provider we want to access, so be careful not to misspell the name of the registered provider.

在这里插入图片描述

  • The : value on the interface method is not to be messed with, and the url of the remote call is : an alias/name that corresponds to the name of the provider you want to call.http://MEMBER-SERVICE-PROVIDER/member/get/{id}; methods on the interface, which must also be compatible with calls to the The methods in the provider are consistent with the following.

在这里插入图片描述

3. OpenFeign's built-in "logging configuration" operations

This section describes how OpenFeign provides a log printing feature that can be configured to adjust the logging level for monitoring and outputting calls to OpenFeign interfaces from the front.

Log Level:

  1. NONE: default, does not show any logs
  2. BASIC: Records only the request method, URL, response status code and execution time.
  3. HEADERS: request and response headers in addition to those defined in BASIC
  4. FULL: The body of the request and response and metadata in addition to the information defined in HEADERS

There are five common logging levels, namely error, warn, info, debug, and trace.

  1. error: error log, refers to the more serious errors, the normal business has an impact on the need for operation and maintenance configuration monitoring;
  2. warn: warning logs, general errors, not much impact on the business, but requires development attention;
  3. info: information log, record the key information to troubleshoot the problem, such as call time, outgoing and incoming parameters and so on;
  4. debug: used to develop DEBUG, the runtime data inside the key logic;
  5. trace: the most detailed information, usually this information is only recorded to the log file.

3.1 OpenFeign Configuration Log-Application Example

existmember-service-consumer-openfeign-80 establish resemble

在这里插入图片描述

package ;


import ;
import ;
import ;

@Configuration
public class OpenFeignConfig {


    @Bean
    public loggerLever() {
        // /The log level is specified as FULL
        return ;
    }
}

existmember-service-consumer-openfeign-80 Modifications in the module To configure which class we are logging to print the information, and to print the configured logging information for the(military) rank

在这里插入图片描述


logging.
  level: # Printing information on MemberFeignService interface calls - Debug.
    # Print messages for MemberFeignService interface calls - Debug
    : debug


server.
  port: 80
spring.
  name: member-service-consumer-openfeign-80
    name: member-service-consumer-openfeign-80

# Configure eureka client Note that because the module is acting as a client here, it is necessary to send the client's information to the Server.
eureka.
  eureka: client: register-with-eureka: true
    register-with-eureka: true # Registers itself with Eureka-Server.
    fetch-registry: true # means to send information to Eureka-Server
    service-url.
      # Registers itself with the eureka-server
      # defaultZone: http://localhost:9001/eureka
      # Register this microservice with multiple eureka-servers, just use comma spacing
      defaultZone: :9001/eureka/,:9002/eureka/

defaultZone: :9001/eureka/,:9002/eureka/
  :9001/eureka/,:9002/eureka/ logging.
    # Print messages for MemberFeignService interface calls - Debug
    : debug

test (machinery etc)
Browser.http://localhost/member/consumer/openfeign/get/1

IDEA backend to view the printed displayed log messages:

在这里插入图片描述

4. OpenFeign timeout setting operation

OpenFeign timeout: Let's look at the following question first:

We simulate network anomalies inmember-service-provider-10000 respond in singingmember-service-provider-10002 of the two service providersgetMemberById method, which simulates a timeout, is paused for 5 seconds.

   // Simulate a timeout, here pause for 5 seconds.
        try {
            (5); } catch (Exception e) {
        } catch (Exception e) {
            (); } catch (Exception e) {
        }

在这里插入图片描述

browser accesshttp://localhost/member/consumer/openfeign/get/1

Test Results.

browser display: Read timed out executing GEThttp://MEMBER-SERVICE-PROVIDER/member/get/1
IDEA backend shows: : Read timed out
() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is : Read timed out executing GET http://MEMBER-SERVICE-PROVIDER/member/get/1] with root cause

在这里插入图片描述

在这里插入图片描述

Cause Analysis: OpenFeign defaults to a timeout of 1 second, i.e., 1 second to wait for the result to be returned.If the time exceeds 1 second, an error will be reported.

Setting the timeout period

Explanation: In some cases, a service call may take longer than 1 second and the timeout needs to be reset.

Here we set the timeout to be set to:8 seconds.While we simulated 5 seconds, 5 seconds is less than 8 seconds and can still be accessed within the timeout period.

For the OpenFeign timeout, we need to set the timeout in the file to configure it. As shown in the figure below:

# OpenFeign timeout
ribbon.
# # Sets the feign client timeout (openFeign supports ribbon by default) # # The time it takes to read available resources from the server after a connection is established.
# # Time in milliseconds
  ReadTimeout: 8000
# # refers to the time taken to establish a connection, which applies if the network conditions are normal, # # the time taken for both ends to connect, # # in milliseconds.
# # The time it takes for both ends to connect
  ConnectTimeout: 8000

在这里插入图片描述

server.
  port: 80
spring.
  name: member-service-consumer-openfeign-80
    name: member-service-consumer-openfeign-80

# Configure eureka client Note that because the module is acting as a client here, it is necessary to send the client's information to the Server.
eureka.
  eureka: client: register-with-eureka: true
    register-with-eureka: true # Registers itself with Eureka-Server.
    fetch-registry: true # means to send information to Eureka-Server
    service-url.
      # Registers itself with the eureka-server
      # defaultZone: http://localhost:9001/eureka
      # Register this microservice with multiple eureka-servers, just use comma spacing
      defaultZone: :9001/eureka/,:9002/eureka/

defaultZone: :9001/eureka/,:9002/eureka/
  :9001/eureka/,:9002/eureka/ logging.
    # Print messages for MemberFeignService interface calls - Debug
    : debug

# OpenFeign timeout
ribbon: # Set the feign client timeout (openFeign supports ribbon by default)
# # Sets the feign client timeout (openFeign supports ribbon by default) # # The time it takes to read available resources from the server after a connection is established.
# # Time in milliseconds
  ReadTimeout: 8000
# # The time it takes to establish a connection, if the network conditions are normal, # # the time it takes for both ends to connect.
# # The time it takes for both ends to connect
  ConnectTimeout: 8000

Browser output.http://localhost/member/consumer/openfeign/get/1, no timeout occurs, accesses are polled 10000/10002

在这里插入图片描述

5. Supplement: spring-boot-starter-actuator is a spring boot program monitoring system , you can realize the health check .

When we're in the Among them is the addition of thespring-boot-starter-actuator dependency jar, you will be able to use the monitoring system. No additional configuration is required

spring-boot-starter-actuator is a spring boot program monitoring system , you can realize the health check , info information and so on.

Visit http://localhost:80/actuator to see the links and also to do the configuration.

spring-boot-starter-actuator Accessed syntax links:url address + corresponding port number of its own module/actuator

在这里插入图片描述

6. Summary:

  1. OpenFeign is a declarativeWebService clients, using OpenFeign makes it easier to write Web Service clients.
  2. Feign vs OpenFeign
  3. Characteristics of the use of Openfeign:Microservice Interface + @FeignClient , decoupled using interfaces (simply put: the use of interfaces to call the corresponding provider to provide services to the cluster)
  4. Notes and details on OpenFeign operational configuration:
    1. Characteristics of the use of Openfeign:Microservice Interface + @FeignClient , decoupled using interfaces (simply put: the use of interfaces to call the corresponding provider to provide services to the cluster)
    2. You can't mess with: value on interface methods. The url for remote calls is: an alias/name that corresponds to the name of the provider you want to call.http://MEMBER-SERVICE-PROVIDER/member/get/{id}; methods on the interface, which must also be compatible with calls to the The methods in the provider are consistent with the following.
  5. OpenFeign's built-in "Logging Configuration": OpenFeign provides a log printing feature that can be configured to adjust the logging level for monitoring and outputting calls to OpenFeign interfaces.
  6. OpenFeign timeout setting operation
  7. spring-boot-starter-actuator is a spring boot program monitoring system , you can achieve health checks , spring-boot-starter-actuator is a spring boot program monitoring system , you can achieve health checks , info information and so on.

spring-boot-starter-actuator Accessed syntax links:url address + corresponding port number of its own module/actuator

7. Finally:

"In this final chapter, I would like to express my gratitude to each and every one of my readers. Your attention and responses have been a source of motivation for me to create, and I have drawn endless inspiration and courage from you. I will keep your encouragement in my heart and continue to struggle in other areas. Thanks to you all, we will always meet again at some point."

在这里插入图片描述