Chapter 9 Detailed Explanation of Hystrix Circuit Breaker + Global Decoupling of Service Downgrade

     In Chapter 7, partial service degradation is used in both ProductController and OrderController, but it also leads to two problems. By observing two partial degradation cases, we can find:

  • Each business method corresponds to a degraded method, which will lead to code expansion
  • The business logic method is mixed with the downgrade method for handling service exceptions.

        The business logic method and the downgrade method for handling service exceptions are mixed together, which is not easy to maintain. To solve this problem, you can use the annotation @FeignClient(value = "PRODUCT-SERVICE", fallback = xxx.class) to decouple the specified service downgrade method on the interface calling the remote service, and realize the implementation class of the interface calling the remote service, and count the methods of decoupling management service downgrade in the implementation class.

       

  For global decoupling, take the order service OrderController calling the product service ProductController as an example, the process is as follows:

1. Order service and commodity service introduce dependency

     The introduction of order service depends on openfegin, and the introduction of commodity service depends on Hystrix

2. Clear all downgrade methods of OrderController and ProductController

Clear all fallback methods of OrderController

import com.hwadee.springcloud.entity.Product;
import com.hwadee.springcloud.service.IOrderFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    IOrderFeignService orderFeignService;

    @RequestMapping("/buy/{id}")
    public Product buy(@PathVariable Long id) {
        System.out.println("进入OrderController的buy方法, orderFeignService 准备调用远端接口 findById");
        Product product = orderFeignService.findOrderById(id);
        return product;
    }

    @RequestMapping(value = "/delete/{id}")
    public Product deleteOrderById(@PathVariable Long id) {
        System.out.println("进入OrderController的deleteOrderById方法, orderFeignService 准备调用远端接口deleteOrderById");
        Product product = orderFeignService.deleteOrderById(id);
        return product;
    }
}

Clear all downgraded methods of ProductController

Note that if there is a global or exclusive downgrade, you can increase it yourself. For the convenience of demonstration here, global or exclusive are not used.

import com.hwadee.springcloud.entity.Product;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;

@RestController
@RequestMapping("/product")
public class ProductController {
    //方便后面讲负载均衡,查看ip,此处获取配置中的端口号和ip
    @Value("${server.port}")
    private String port;
    @Value("${spring.cloud.client.ip-address}")
    private String ip;

    @RequestMapping("/buy/{id}")
    public Product findById(@PathVariable Long id) {
        Product product = new Product();
        product.setId(id);
        // 后面需要测试负载均衡,所以返回 ip 地址及端口号
        product.setName("当前访问服务地址:" + ip + ":" + port + "  " + "查询商品订单,订单号:" + id);
        product.setPrice(new BigDecimal(10000.0));
        System.out.println(product);

        //测试超时熔断
        try {
            Thread.sleep(5000);
            //测试并发熔断
            //Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return product;
    }

    @RequestMapping(value = "/delete/{id}")
    public Product deleteOrderById(@PathVariable Long id) {
        Product product = new Product();
        product.setId(id);
        // 后面需要测试负载均衡,所以返回 ip 地址及端口号
        product.setName("当前访问服务地址:" + ip + ":" + port + "  " + "从购物车删除订单,订单号:" + id);
        product.setPrice(new BigDecimal(10000.0));
        System.out.println(product);

        //测试异常熔断
        System.out.println(10 / 0);

        return product;
    }

}

2. Define the implementation class of the Feign interface

     Because the order service OrderController calls the product service ProductController  remotely   through the interface IOrderFeignService  and the annotation @FeignClient , when  the order service OrderController  has a timeout or exception, you can use  the implementation class OrderFeignServiceFallBack of the interface IOrderFeignService    in the order service OrderController to decouple the processing method and the downgrade method of the business logic.     

import com.hwadee.springcloud.entity.Product;
import com.hwadee.springcloud.service.IOrderFeignService;
import org.springframework.stereotype.Component;

@Component
public class OrderFeignServiceFallBack implements IOrderFeignService {
    @Override
    public Product findOrderById(Long id) {
        Product product = new Product();
        product.setId(id);
        product.setName("当前订单服务访问/order/buy/1 超时:"+id);
        return product;
    }

    @Override
    public Product deleteOrderById(Long id) {
        Product product = new Product();
        product.setId(id);
        product.setName("当前订单服务访问/order/delete/1 10/0异常:"+id);
        return product;
    }
}

3. Modify  the IOrderFeignService  code to specify the class OrderFeignServiceFallBack for service decoupling in  the annotation @FeignClient of 
     the interface IOrderFeignService  .

@Component // 让 spring 可以识别,不加也行,但是在注入的时候 IDEA 会报错,不会影响运行,但有条红线让自己不舒服
@FeignClient(value = "PRODUCT-SERVICE",fallback = OrderFeignServiceFallBack.class)
public interface IOrderFeignService {
    @RequestMapping(value = "/product/buy/{id}")
    Product findOrderById(@PathVariable Long id);

    @RequestMapping(value = "/product/delete/{id}")
    Product deleteOrderById(@PathVariable Long id);
}

4. Define the main startup class of order service and commodity service

     Since the dependencies introduced in the order service  spring-cloud-starter-openfeign have been integrated  feign-hystrixand have support for Hystrix, there is no need to introduce additional dependencies. If you need to enable the order server  hystrix服务,只需要configuration feign-hystrix in the configuration file of the order service to activate Hystrix, there is no need to add the annotation @EnableHystrix or @EnableHystrix to the main startup class to enable the Hystrix service. The order service and commodity service main startup classes are as follows:

Order service main startup class OrderServerApplication 

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient// 启动 eureka 客户端
@EnableFeignClients  // 启动 feign
public class OrderServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderServerApplication.class, args);
    }
}

Product service main startup class ProductServerApplication 

@SpringBootApplication
@EnableEurekaClient// 启动 eureka 客户端
public class ProductServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProductServerApplication.class, args);
    }
}

4. Turn on openfeign and enable hystrix support in the process of calling the service

 Since the previously introduced  spring-cloud-starter-openfeign dependencies have been integrated  feign-hystrixand have support for Hystrix, there is no need to introduce additional dependencies. You only need to enable openfeign in the application.yml configuration file of the order service and enable hystrix support in the process of calling the service.

server:
  port: 9000
spring:
  application:
    name: order-service # Name the current order service as order-service

# Configure eureka client information
eureka:
  client:
    service-url:
      # Configure the registration address of eureka client service order-service, which must be consistent with the exposed address in eureka-server
      defaultZone: http://localhost:8000/eureka/
  instance:
    prefer-ip-address: true # Whether to use the IP address to register, the default is false
    # instance-id: order-service # Instance id, the unique identifier of the service, will automatically find the ip and port of the order-service
    instance-id: ${spring.cloud.client.ip-address}:${server.port} # If you want to see the service address and port on the control page, you can configure instance-id like this

feign:
  hystrix:
    enabled: true

5. Modify the order service configuration file

      Since the dependencies introduced in the order service  spring-cloud-starter-openfeign have been integrated  feign-hystrixand have support for Hystrix, there is no need to introduce additional dependencies. If you need to enable the order server  hystrix服务,只需要to configure feign-hystrix in the configuration file of the order service to activate Hystrix, modify the application.yml as follows:

server:
  port: 9000
spring:
  application:
    name: order-service # Name the current order service as order-service

# Configure eureka client information
eureka:
  client:
    service-url:
      # Configure the registration address of eureka client service order-service, which must be consistent with the exposed address in eureka-server defaultZone: http://
      localhost:8000/eureka/
  instance:
    prefer-ip-address: true # Whether to use IP address registration, default false #
    instance-id: order-service # Instance id, the unique identifier of the service, will be found automatically The ip and port of order-service instance-id: ${spring.cloud.client.ip-address}:${server.port} # If you want to see the service address and port on the control page, you can configure instance-id like
    this

feign:
  hystrix:
    enabled: true

 

6. Test

     Visit  http://localhost:9000/order/buy/1    and  http://localhost:9000/order/delete/1    respectively to view the browser results as follows:

Chapter 8: Detailed Explanation of Hystrix Circuit Breaker - Global Service Downgrade of Service Downgrade

Chapter 10: Detailed Explanation of Hystrix Circuit Breaker + Service Fuse

Guess you like

Origin blog.csdn.net/qq_41946216/article/details/127371415