Introduction to the

Feign makes writing Java HTTP Clients Easier Official document

Integration of Feign

  • And rely on
<! - the version defined by the parent project - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>Copy the code
  • Write notes
@EnableFeignClients
Copy the code
  • Write the configuration
There is noCopy the code

use

package com.virgo.user.feignclient; import com.virgo.entity.TblCar; import com.virgo.user.configuration.GlobalFeignConfiguration; import com.virgo.user.feignclient.fallbackFactory.LockCenterFeignClientFallbackFactory; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; /** * @author zhaozha * @date 2019/10/11 12:52 PM */ @feignClient (name ="lock-center". configuration = GlobalFeignConfiguration.class,fallbackFactory = LockCenterFeignClientFallbackFactory.class) public Interface LockCenterFeignClient {// Automatic build http://lock-center/lock/test/{id}
    @GetMapping("/lock/test/{id}")
    TblCar findById(@PathVariable(value="id") Long id); } // Controller ... private final LockCenterFeignClient lockCenterFeignClient; . TblCar tblCar = lockCenterFeignClient.findById(4000002L); .Copy the code

composition

interface role The default value
Feign.Builder The entrance to Feign Feign.Builder
Client What does the Feign layer use to request LoadBalancerFeignClient(integrated Ribbon)/ fengn.client.default (unintegrated Ribbon)
Contract Contract, annotation support SpringMvcContract
Encoder Encoder for converting an object into the body of an HTTP request message SpringEncoder
Decoder Decoder that converts the body of the response message into an object ResponseEntityDecoder
Logger Log manager Slf4jLogger
RequestInterceptor Used to add common logic for each request There is no

The level of logging

level Print the content
NONE(default) No logs are recorded
BASIC Record only the method /URL/ response status code/execution time of the request
HEADERS BASIC+ Headers for request and response
FULL Document header/body/ metadata for the request and response

The log configuration

  • Fine-grained code

    • yml
    Feign log level set (code) logging: level: com. Virgo. User. Feignclient. LockCenterFeignClient: debugCopy the code
    • code
    package com.virgo.user.feignclient; import com.virgo.entity.TblCar; import com.virgo.user.configuration.GlobalFeignConfiguration; import com.virgo.user.feignclient.fallbackFactory.LockCenterFeignClientFallbackFactory; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; /** * @author zhaozha * @date 2019/10/11 12:52 PM */ @feignClient (name ="lock-center". configuration = GlobalFeignConfiguration.class,fallbackFactory = LockCenterFeignClientFallbackFactory.class) public interface LockCenterFeignClient { @GetMapping("/lock/test/{id}")
        TblCar findById(@PathVariable(value="id") Long id);
    }
    
    GlobalFeignConfiguration.class
    package com.virgo.user.configuration;
    
    import feign.Logger;
    import org.springframework.context.annotation.Bean;
    
    /**
     * @author zhaozha
     * @date 2019/10/11 下午1:18
     */
    public class GlobalFeignConfiguration {
        @Bean
        public Logger.Level level(){// have Feign print the details of all requestsreturnLogger.Level.FULL; }}Copy the code
  • Fine-grained configuration

feign:
  client:
    config:
      lock-center:
        loggerLevel: FULL
Copy the code
  • Global code
@EnableFeignClients(defaultConfiguration = GlobalFeignConfiguration.class)
Copy the code
  • Global configuration
feign:
  client:
    config:
      default:
        loggerLevel: FULL
Copy the code

Configuration items

code

Configuration items role
Logger.Level Specifying a log Level
Retryer Specifying a retry policy
ErrorDecoder Specifies the error decoder
Request.Options timeout
Collection The interceptor
SetterFactory Hystrix related

configuration

feign:
  client:
    config:
      # global
      default:
        # log level
        loggerLevel:
        Connection timeout
        connectTimeout:
        Read timeout
        readTimeout:
        Error decoder
        errorDecoder:
        Retry policy
        retryer:
        # interceptor
        requestInterceptors:
        # 404 Error code decoding
        decode404:
        # encoder
        encoder:
        # decoder
        decoder:
        # contract
        contract:
Copy the code

inheritance

todo

multi-parameter

@GetMapping("/lock/car/{carId}/user/{userId}")
TblCar findById(@PathVariable(value="carId") Long carId,@PathVariable(value="userId") Long userId);
Copy the code

Out of the ribbon

@FeignClient(name="",url="")
Copy the code

feign & restTemplate

  • Performance: the restTemplate
  • Readability: Feign

To optimize the

feign:
  httpclient:
    # let feign use Apache HttpClient for requests. Instead of the default URlConnection
    enabled: true
    # feign maximum number of connections
    max-connections: 200
    # feign Specifies the maximum number of connections for a single path
    max-connections-per-route: 50
Copy the code

fallback & fallbackFactory

  • fallback
// 1 Annotation @feignClient (.... , fallback = XXX. Class) / / 2 code package com. Virgo. User. Feignclient. Fallback; import com.virgo.entity.TblCar; import com.virgo.user.feignclient.LockCenterFeignClient; import org.springframework.stereotype.Component; / * * * @ author zhaozha * @ date "* / 2019/10/16 afternoon @ Component public class LockCenterFeignClientFallback implements LockCenterFeignClient { @Override public TblCar findById(Long id,Long userId) {return TblCar.builder().level(1).build();
    }

    @Override
    public TblCar testPost(String params) {
        returnnull; }}Copy the code
  • FallbackFactory (stronger than Fallback, can print exceptions)
// 1 Annotation @feignClient (.... , fallbackFactory = XXX. Class) / / 2 code package com. Virgo. User. Feignclient. FallbackFactory; import com.virgo.entity.TblCar; import com.virgo.user.feignclient.LockCenterFeignClient; import feign.hystrix.FallbackFactory; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; / * * * @ author zhaozha 4:02 * / * @ date 2019/10/16 afternoon @ Component @ Slf4j public class LockCenterFeignClientFallbackFactory implements FallbackFactory<LockCenterFeignClient> { @Override public LockCenterFeignClient create(Throwable throwable) {return new LockCenterFeignClient() {
            @Override
            public TblCar findById(Long id,Long userId) {
                log.info("Current limiting/degradation",throwable);
                return TblCar.builder().level(1).build();
            }

            @Override
            public TblCar testPost(String params) {
                returnnull; }}; }}Copy the code