SpringCloud's declarative service call based on Ribbon and Hystrix

The role and use of each component of SpringCloud

Profile

Feign is a declarative service calling tool. We only need to create an interface and configure it with annotations to call a certain service interface, which simplifies the development of directly using RestTemplate to call the service interface. Feign has pluggable annotation support, and supports Feign annotations, JAX-RS annotations and SpringMvc annotations. When using Feign, Spring Cloud integrates Ribbon and Eureka to provide load-balanced service calls and Hystrix-based service fault-tolerant protection.

Create a feign-service module

  • Add related dependencies in pom.xml
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <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.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            <version>2.2.10.RELEASE</version>
        </dependency>
  • 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/
  • Add the @EnableFeignClients annotation to the startup class to enable Feign's client functionality
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class FeignServiceApplication {
    
    

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

}
  • Add the UserService interface to complete the interface binding to the user-service service

We implemented a Feign client through the @FeignClient annotation, where the value is user-service, indicating that this is an interface call client for the user-service service. We can recall the UserController in user-service, just change it to an interface and keep the original SpringMvc annotations.

@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);
}
  • Add UserFeignController to call UserService to implement service calls
@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) {
    
    
        return userService.delete(id);
    }
}

Demonstration of load balancing function

  • Start eureka-service, two user-services, and feign-service services. After startup, the registration center is displayed as follows:
    insert image description here
  • Call http://localhost:8701/user/1 multiple times to test, and you can find that the user-service running on 8201 and 8202 prints alternately.

Service downgrade in Feign

The service downgrade in Feign is very convenient to use. You only need to add a service downgrade implementation class to the interface defined by the Feign client. Next, we add a service downgrade implementation class for the UserService interface.

  • Add service degradation implementation class UserFallbackService

It should be noted that it implements the UserService interface, and implements the service degradation logic for each implementation method in the interface.

@Service
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("调用失败,服务被降级",500);
    }

    @Override
    public CommonResult delete(Long id) {
    
    
        return new CommonResult("调用失败,服务被降级",500);
    }
}
  • Modify the UserService interface and set the service downgrade processing class to UserFallbackService

Modify the parameters in the @FeignClient annotation and set fallback to UserFallbackService.class.

@FeignClient(value = "user-service",fallback = UserFallbackService.class)
public interface UserService {
    
    
}
  • Modify application.yml to enable Hystrix function
server:
  port: 8701
spring:
  application:
    name: feign-service
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8001/eureka/

feign:
  circuitbreaker:
    enabled: true

Demo of service downgrade function

  • Close the two user-service services and restart feign-service;
  • Call http://localhost:8701/user/1 to test, and you can find that the service degradation information is returned.
    insert image description here

Log printing function

log level

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

Enable more detailed logging through configuration

We enable Feign to print the most detailed Http request log information through java configuration.

@Configuration
public class FeignConfig {
    
    
    @Bean
    Logger.Level feignLoggerLevel() {
    
    
        return Logger.Level.FULL;
    }
}
  • Configure the Feign client that needs to open the log in application.yml

Configure the log level of UserService to debug.

logging:
  level:
    com.wl.cloud.service.UserService: debug

Feign's common configuration

feign:
  hystrix:
    enabled: true #在Feign中开启Hystrix
  compression:
    request:
      enabled: false #是否对请求进行GZIP压缩
      mime-types: text/xml,application/xml,application/json #指定压缩的请求数据类型
      min-request-size: 2048 #超过该大小的请求会被压缩
    response:
      enabled: false #是否对响应进行GZIP压缩
logging:
  level: #修改日志级别
    com.macro.cloud.service.UserService: debug

Guess you like

Origin blog.csdn.net/zhang0305/article/details/125470594