Service call Feign

Service call Feign Getting Started:

  In learning ribbon, used RestTemplate implement REST API calls, the code is as follows:

/ ** 
     * By order system, calls Goods Services product information based on the query id 
     * @param id 
     * @return 
     * / 
    @GetMapping ( "/ Buy / {id}" )
     public Product findById (@PathVariable ( "id" ) Long id ) {
         return restTemplate.getForObject ( "HTTP: // Product-Service-/ Product /" + ID, Product. class ); 
    }

  From the code, we are constructing a URL using string concatenation way, the URL is only one parameter. However, in reality, URL often contain multiple parameters. If this time we also construct the URL in this way, it will be very painful.

  Feign profile:

    Feign Netflix is ​​developed declarative, template-based HTTP client, inspired Retrofit, JAXRS-2.0 and WebSocket

    Feign can help us be more convenient and elegant calling HTTP API.
    In SpringCloud using Feign very simple - to create an interface, and add some notes on the interface, the code is complete.
    Feign supports multiple annotations, e.g. Feign own annotations annotations JAX-RS or the like.
    SpringCloud to Feign has been enhanced to support the Feign SpringMVC notes, and the integration of Ribbon and Eureka, in order to make use Feign more convenient.
  Based on a service call Feign:

    1. dependence introduction

      order_service add Fegin dependent on consumer services

<!-- springCloud整合openFeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

    2. Start the class to add support Feign

      By @EnableFeignClients comment open Spring Cloud Feign support functions, RestTemplate not need to use, and can be removed

@SpringBootApplication
@EntityScan("com.fgy.common.domain")
// 激活feign
@EnableFeignClients
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class,args);
    }
}

    3. Start class activation FeignClient

      Create a Feign interface that is invoked in the micro-service core interfaces in Feign

      order_service add a ProductFeginClient interface service consumer

/ ** 
 * The name of the service need to call the statement 
 * @FeignClient 
 * name: the service provider's service name 
 * / 
@FeignClient (name = "Service-Product" )
 public  interface ProductFeignClient { 

    / ** 
     * Configuration micro-service interface needs to call 
     * / 
    @GetMapping (value = "/ Product / {ID}" )
     public Product the findById (@PathVariable ( "ID" ) Long ID); 
}

      When the definition of each parameter binding, @ PathVariable, @ RequestParam, @ RequestHeader can specify parameters such as property, bind arguments in Feign must be indicated by a specific parameter name attribute value, otherwise it will throw an exception
      @FeignClient: Notes designated by name the name of the micro-services need to call for creating Ribbon load balancer. So Ribbon will resolve product-service center for the registration of service.
    4. Configuration Request provider call interface

      Modify OrderController, add ProductFeginClient automatic injection, injection RestTemplate delete, and use the micro ProductFeginClient complete service calls in the method needs to be called in

/ ** 
 * Order Control layer 
 * / 
@RestController 
@ RequestMapping ( "/ the Order" )
 public  class OrderController { 

    @Autowired 
    Private ProductFeignClient productFeignClient; 

    / ** 
     * By order system, calls Goods Services product information based on the query id 
     * @param id 
     * @return 
     * / 
    @GetMapping ( "/ Buy / {ID}" )
     public Product the findById (@PathVariable ( "ID" ) Long ID) {
         return productFeignClient.findById (ID); 
    } 
}

    5. Test results

      

 

 Feign and Ribbon contact:

  Ribbon is a tool based load balancing HTTP and TCP clients. It can be configured in the client RibbonServerList (server list), or using HttpClient RestTemplate analog http request, steps, is rather cumbersome.
  Feign is an improvement on the basis of the Ribbon, it is more convenient to use a HTTP client. By way of an interface, only you need to create an interface, then you can add annotations above, the method will need to call other services is defined as abstract methods, do not need to build their own http request. Then call the method itself works like a calling, and feel is to call a remote method, the client makes writing very easy.
Load Balancing:

  Feign itself has been integrated in the Ribbon dependency and auto-configuration, and therefore we do not need to introduce additional dependent, you do not need to re-register RestTemplate object.
  In addition, we can be like configuration as Ribbon, the global configuration performed by ribbon.xx, .ribbon.xx can also be configured for load balancing policy designated service by service name.

Service call Feign Advanced:

  Feign configuration

    Starting Spring Cloud Edgware version, Feign supports the use of custom properties Feign, Feign supports the following configuration items:

Feign: 
Client: 
 config: 
  feignName: # define FeginClient name 
   connectTimeout: 5000   # long established timeout connection 
   ReadTimeout: 5000    # read timeout durations 
    # Configure Feign log level, corresponding to the code arrangement in Logger 
   loggerLevel: Full 
    # Feign error decoder 
   errorDecoder: com.example.SimpleErrorDecoder 
    # retries to 
   retryer: com.example.SimpleRetryer 
    # configuration request interceptor 
   requestInterceptors:
     - com.example.FooRequestInterceptor
     - com.example.BarRequestInterceptor 
  # configure fuse 404 does not handle the exception    decode404:
false

  Compression request

    Spring Cloud Feign support GZIP compression requests and responses, in order to reduce performance losses during communication. By the following parameters to open request and response compression:

Feign: 
 compression: 
  Request: 
   Enabled: to true # Compression Open Request 
  Response: 
   Enabled: to true # Open response compaction

    At the same time, it can also be provided to the requested data type, the compressed size and the lower limit triggers (much smaller than is not compressed):

Feign: 
 compression: 
  Request: 
   Enabled: to true # turn requests the compaction 
   MIME -types: text / HTML, file application / XML, file application / JSON compressed data type # Set 
   min Minimum size # 2048 set the trigger compression: -request-size

      NOTE: The above data type, the compressed size lower limit are the default values.

  Log Level

    In the development phase or run often want to see the logging Feign request process, Feign By default, the log is not open.
    To attribute a configuration to achieve the effect of the log, simply add the following to the application.yml in:

feign:
 client:
  config:
   product-service:
    loggerLevel: FULL
logging:
 level:
  com.fgy.order.fegin.ProductFeginClient: debug

      logging.level.xx: debug: Feign log will only respond debug log level of

      feign.client.config.product-service.loggerLevel: There are four log configuration Feign

        Log Level:

          [NONE best performance for production]: not any log record (default)
          BASIC [tracing for a production environment]: Only requests recording method, URL, and the response status code execution time
          HEADERS: BASIC level on the basis of recording , and in response to the recording request header.
          [FULL more suitable for the development and test environment Orientation]: record header, body, and metadata requests and responses.

Guess you like

Origin www.cnblogs.com/roadlandscape/p/12497626.html
Recommended