SpringBoot e-Commerce project mall (20K + STAR) address: github.com/macrozheng/…

Abstract

Spring Cloud OpenFeign is a statement service invocation tool that integrates the Ribbon and Hystrix with load balancing and service fault tolerance. This article will explain its usage in detail.

Introduction of Feign

Feign is a declarative service invocation tool that allows you to invoke a service interface by creating an interface and configuring it with annotations, simplifying the development effort of invoking the service interface directly using the RestTemplate. Feign has pluggable annotation support, as well as support for Feign annotations, JAX-RS annotations, and SpringMvc annotations. When using Feign, Spring Cloud integrates Ribbon and Eureka to provide load-balanced service invocation and Hystrix-based service fault-tolerant protection.

Create a feign-service module

Here we create a feign-service module to demonstrate feign’s common functions.

Add related dependencies in pom.xml

<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>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code

Configure in application.yml

server:
  port: 8701
spring:
  application:
    name: feign-service
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8001/eureka/
Copy the code

Add the @enableFeignClients annotation to the startup class to enable Feign’s client functionality

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignServiceApplication {

    public static void main(String[] args) { SpringApplication.run(FeignServiceApplication.class, args); }}Copy the code

Adding the UserService interface The interface is bound to the user-service service

We implemented a Feign client with the @FeignClient annotation, where value user-service indicates that this is calling the client to the interface of the User-Service service. Recall the UserController in the User-Service, just change it to an interface and keep the original SpringMvc annotation.

/** * Created by macro on 2019/9/5. */
@FeignClient(value = "user-service")
public interface UserService {
    @PostMapping("/user/create")
    CommonResult create(@RequestBody User user);

    @GetMapping("/user/{id}")
    CommonResult<User> getUser(@PathVariable Long id);

    @GetMapping("/user/getByUsername")
    CommonResult<User> getByUsername(@RequestParam String username);

    @PostMapping("/user/update")
    CommonResult update(@RequestBody User user);

    @PostMapping("/user/delete/{id}")
    CommonResult delete(@PathVariable Long id);
}
Copy the code

Add UserFeignController to call UserService to implement the service invocation

/** * Created by macro on 2019/8/29. */
@RestController
@RequestMapping("/user")
public class UserFeignController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public CommonResult getUser(@PathVariable Long id) {
        return userService.getUser(id);
    }

    @GetMapping("/getByUsername")
    public CommonResult getByUsername(@RequestParam String username) {
        return userService.getByUsername(username);
    }

    @PostMapping("/create")
    public CommonResult create(@RequestBody User user) {
        return userService.create(user);
    }

    @PostMapping("/update")
    public CommonResult update(@RequestBody User user) {
        return userService.update(user);
    }

    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable Long id) {
        returnuserService.delete(id); }}Copy the code

Load balancing function demonstration

  • Start eureka-service, two user-service, feign-service services, and the registry displays as follows:

  • Multiple calls http://localhost:8701/user/1 for testing, can find the user run in the 8201 s and 8202 – service service alternate print the following information:
The 2019-10-04 15:15:34. 9236-829 the INFO [nio - 8201 - exec - 5] c. acro. Cloud. Controller. UserController: Obtain user information based on the ID. The user name is: Macro 15:15:35 2019-10-04. 9236-492 the INFO/IO - 8201 - exec - 10 c. acro. Cloud. Controller. UserController: Obtain user information based on the ID. The user name is: Macro 15:15:35 2019-10-04. 9236-825 the INFO [nio - 8201 - exec - 9] c. acro. Cloud. Controller. UserController: Get user information based on id. The user name is macroCopy the code

The service in Feign is degraded

Service degradation in Feign is very easy to use. Just add a service degradation implementation class to the interface defined by the Feign client. Let’s add a service degradation implementation class to the UserService interface.

Add the service degradation implementation class UserFallbackService

Note that it implements the UserService interface and implements the service degradation logic for each implementation method in the interface.

/** * Created by macro on 2019/9/5. */
@Component
public class UserFallbackService implements UserService {
    @Override
    public CommonResult create(User user) {
        User defaultUser = new User(-1L."defaultUser"."123456");
        return new CommonResult<>(defaultUser);
    }

    @Override
    public CommonResult<User> getUser(Long id) {
        User defaultUser = new User(-1L."defaultUser"."123456");
        return new CommonResult<>(defaultUser);
    }

    @Override
    public CommonResult<User> getByUsername(String username) {
        User defaultUser = new User(-1L."defaultUser"."123456");
        return new CommonResult<>(defaultUser);
    }

    @Override
    public CommonResult update(User user) {
        return new CommonResult("Call failed, service degraded".500);
    }

    @Override
    public CommonResult delete(Long id) {
        return new CommonResult("Call failed, service degraded".500); }}Copy the code

Example Modify the UserService interface and set the service degradation processing class to UserFallbackService

Modify the @ FeignClient the parameter annotation, set the fallback to UserFallbackService. Class.

@FeignClient(value = "user-service",fallback = UserFallbackService.class)
public interface UserService {}Copy the code

Modify application.yml to enable the Hystrix function

feign:
  hystrix:
    enabled: true # Enable Hystrix in Feign
Copy the code

Service degradation function demonstration

  • Stop the two user-services and restart ign-service.

  • Call http://localhost:8701/user/1 for testing, can be found that returned to the information service degradation.

Log Printing function

Feign provides log printing, which can be configured to adjust the log level to understand the details of Http requests in Feign.

The level of logging

  • NONE: By default, no logs are displayed.
  • BASIC: only request method, URL, response status code and execution time are recorded;
  • HEADERS: Request and response HEADERS in addition to the information defined in BASIC;
  • FULL: In addition to the information defined in HEADERS, there is the body and metadata of the request and response.

Enable detailed logging through configuration

We configured Feign with Java to print the most detailed Http request log information.

/** * Created by macro on 2019/9/5. */
@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLevel(a) {
        returnLogger.Level.FULL; }}Copy the code

Configure the Feign client to enable logging in application.yml

Set the log level of UserService to DEBUG.

logging:
  level:
    com.macro.cloud.service.UserService: debug
Copy the code

See the log

Call http://localhost:8701/user/1 for testing, you can see the log below.

The 2019-10-04 15:44:03. 5204-248 the DEBUG [- user - service - 2] com. Macro. Cloud. Service. UserService: [UserService#getUser] --> GET http://user-service/user/1 HTTP/1.1The 2019-10-04 15:44:03. 5204-248 the DEBUG [- user - service - 2] com. Macro. Cloud. Service. UserService: [UserService#getUser] ---> END HTTP (0-byte body)The 2019-10-04 15:44:03. 5204-257 the DEBUG [- user - service - 2] com. Macro. Cloud. Service. UserService: [UserService#getUser] <-- HTTP/1.1 200 (9ms)The 2019-10-04 15:44:03. 5204-257 the DEBUG [- user - service - 2] com. Macro. Cloud. Service. UserService: [UserService#getUser] content-type: application/json; charset=UTF-8The 2019-10-04 15:44:03. 5204-258 the DEBUG [- user - service - 2] com. Macro. Cloud. Service. UserService: [UserService#getUser] date: Fri, 04 Oct 2019 07:44:03 GMTThe 2019-10-04 15:44:03. 5204-258 the DEBUG [- user - service - 2] com. Macro. Cloud. Service. UserService: [UserService#getUser] transfer-encoding: chunkedThe 2019-10-04 15:44:03. 5204-258 the DEBUG [- user - service - 2] com. Macro. Cloud. Service. UserService: [UserService#getUser] The 2019-10-04 15:44:03. 5204-258 the DEBUG [- user - service - 2] com. Macro. Cloud. Service. UserService: [UserService# getUser] {" data ": {" id" : 1, "username" : "macro", "password" : "123456"}, "message" : "successful", "code" : 200}The 2019-10-04 15:44:03. 5204-258 the DEBUG [- user - service - 2] com. Macro. Cloud. Service. UserService: [UserService#getUser] <--- END HTTP (92-byte body)
Copy the code

Common configurations of Feign

Feign’s own configuration

feign:
  hystrix:
    enabled: true # Enable Hystrix in Feign
  compression:
    request:
      enabled: false # Whether to GZIP the request
      mime-types: text/xml,application/xml,application/json # specify the request data type to compress
      min-request-size: 2048 Requests larger than this size will be compressed
    response:
      enabled: false # Whether to GZIP the response
logging:
  level: # Change the log level
    com.macro.cloud.service.UserService: debug
Copy the code

Feign Ribbon configuration

To configure the Ribbon in Feign, you can use the Ribbon configuration directly. For details, see Spring Cloud Ribbon: Load Balancing Service Invocation.

Hystrix configuration in Feign

To configure Hystrix in Feign, you can use the Hystrix configuration directly. For details, see Spring Cloud Hystrix: Service Fault Tolerance Protection.

The module used

Springcloud - learning ├ ─ ─ eureka - server-- Eureka Registry├ ─ ─ the user - service-- a service that provides the User object CRUD interface└ ─ ─ feign - service-- Feign service calls the test service
Copy the code

Project source code address

Github.com/macrozheng/…

The public,

Mall project full set of learning tutorials serialized, attention to the public number the first time access.