springcloud (Hystrix breaker)

1. Understand Hystrix

1.1. Avalanche

  • In a scene in the movie often, do not cry at the tip of the snow should fall sound vibrations can cause small snowball, snowball with the fall may have lead to a chain reaction collapse of the entire snow-capped mountains, this is life in the avalanche, the same is true in the service inside micro, micro calling service is very complex, a request often takes a lot of micro-services through completion of the call chain throughout the micro-service, if a service fails, it will cause the entire call chain call abnormalities, and even may lead to paralysis of the entire micro-services, - this is the avalanche effect.

1.2.Hystrix Introduction

  • Hystrix foreign well-known video site Netflix are very popular open source high-availability architecture framework. Hystrix can be the perfect solution to a distributed system architecture to create a highly available service faced a series of technical problems.
  • English is the porcupine Hystrix, the Chinese translation for the fuse, the idea comes from our home insurance switch, when a short circuit occurs at home, cutout promptly cut off circuit to ensure the safety of personnel at home, its purpose is to play a protective role.
  • Simple to understand Hystrix avalanche problem can be solved by means of fusing and downgrade, it is a micro-service protection components.

The role of 1.3.Hystrix

  • Resource isolation(Limiting) include:Thread pool isolationwithSemaphore isolationRestrict call service distributed resource use, a call to a service problem does not affect other service calls.
    Here Insert Picture Description
  • Blown: When the number of requests reaches a predetermined threshold are present service failures (time-out), Hystrix service marks put the short-circuit state.

Under normal circumstances, the circuit breaker is in a closed state (Closed), if the call duration timeout error, or the circuit is opened into the blown state (the Open), all calls in a subsequent period is rejected (the FailFast), some time later, the protector We will try to enter the semi-blown state (half-Open), allowing a small amount request comes in to try, if the call fails, the return to fuse state, if the call is successful, the return to the closed circuit state;

  • Downgrade: a highly concurrent case, to ensure that some of the major services have sufficient resources not see the problem, think of the turn off some insignificant service, and then return some of the underpinning data to a user-friendly tips.

Such as closing some minor business in two-eleven Taobao, Taobao in order to allow the main business of adequate resources, will choose, such as non-refundable and can not be evaluated during the two-eleven and so on, when you go to a refund is temporarily unable to return prompt refund to you, this is service degradation mechanisms.

  • Cache: Hystrix internal cache will make the request and the request to do merge

2. order service integration Hystrix

  • Modify springcloud-order-server-1030 integrated Hystrix, the project has been integrated Ribbon
2.1. Import dependence
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2.2. Configuration class open Hystrix
  • Open fuse function by @EnableCircuitBreaker label
/**
 * @EnableEurekaServer:开启eurekaServer服务端
 * @EnableCircuitBreaker:开启Hystrix断路器注解
 */
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker //开启Hystrix熔断
public class OrderServerApplicationConfig {

    //配置一个RestTemplate ,Spring封装的一个机遇Restful风格的http客户端 工具
    //@LoadBalanced :让RestTemplate有负载均衡的功能
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(OrderServerApplicationConfig.class,args);
    }
}
2.3 Method fuse
  • By fusing method @HystrixCommand label tag, fallbackMethod specified property tag mopping method.
//订单服务
@RestController
public class OrderController {

    //需要配置成Bean
    @Autowired
    private RestTemplate restTemplate;

    //负载均衡策略
    @Bean
    public RandomRule randomRule(){
        return new RandomRule();
    }

    //浏览器调用该方法
    @RequestMapping(value = "/order/{id}",method = RequestMethod.GET)

    //方法熔断
    @HystrixCommand(fallbackMethod = "fallbackMethod")
    public User getUserId(@PathVariable("id")Long id){
        //发送http请求调用 user的服务,获取user对象 : RestTemplate
        //user的ip,user的端口,user的Controller路径
        //String url = "http://localhost:1020/user/"+id; 单个用户服务的时候
        String url = "http://user-server/user/" + id;
        return restTemplate.getForObject(url,User.class);
    }

    //断路器熔断后调用的方法
    public User fallbackMethod(@PathVariable("id")Long id) {
        return new User(-1L,"无用户","没有此用户");
    }

}

2.4. Underpinning method
//断路器熔断后调用的方法
    public User fallbackMethod(@PathVariable("id")Long id) {
        return new User(-1L,"无用户","没有此用户");
    }
2.4 Test fuse
  • Browser to access http: // localhost: 1030 / order / 1, when the customer service springcloud-user-server-1020 start properly, you can order service is accessed, the browser can receive a result, when users shut off the service, order service will trigger fuse, mopping return data.
    Here Insert Picture Description

3. Payment service integration Hystrix

  • Integrated Feign before payment service springcloud-pay-server-1040, in fact, Feign has integrated Hystrix, but is off by default, we need to open Hystrix support Feign, and to develop mopping the floor.
3.1. Turn Hystrix
feign:
  hystrix:
    enabled: true #开启熔断支持
  client:
    config:
      remote-service:           #服务名,填写default为所有服务
        connectTimeout: 10300
        readTimeout: 10300
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 10300
3.2.Fiegn Interface fuse
@FeignClient(value = "user-server",fallback = UserFeignClientFallback.class)
public interface UserFeignClient {

    //订单服务来调用这个方法      http://localhost:1020/user/10
    // @GetMapping(value = "/user/{id}" )
    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    User getById(@PathVariable("id")Long id);
}

Tip: fallback = UserFeignClientFallback.class: This class is the current interface implementation class, class is also underpinning data processing where the

3.3. Underpinning achieve
//让Spring扫描到该托底类
@Component
public class FeignClientFallBack implements UserFeignClient {
	//日志打印器
    Logger logger = LoggerFactory.getLogger(FeignClientFallBack.class);

    @Override
    public User getUser(Long id) {
        logger.info("用户服务错误!!!");
        //托底数据
        return new User(-1L,"无用户","没有此用户");
    }
}
  • Tip: Note that this class needs to Spirng underpinning management, the need to fight @Component comment on the class, drag the class needs to implement Feign interfaces, replication of which method to return data mopping the floor. When Fiegn call fails to result mopping method will return back to the user.
3.4 Start Test

Start payment services, visit: http: // localhost: 1040 / pay / 1, the test results with the same orders.

3.5.Fiegn Interface fuse - Second way
1. Turn Hystrix
feign:
  hystrix:
    enabled: true #开启熔断支持
  client:
    config:
      remote-service:           #服务名,填写default为所有服务
        connectTimeout: 10300
        readTimeout: 10300
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 10300
2. Modify Feign Interface

usefallbackFactoryProperty, specify the use of plant underpinning

@FeignClient(value = "user-server",fallbackFactory = FeignClientFallBackFactory.class)
public interface UserFeignClient {

    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    User getUser(@PathVariable("id")Long id);

}
3. Write drag the end of class
//工厂方式的 , 托底类
@Component
public class UserFeignClientFallbackFactory implements FallbackFactory<UserFeignClient>{

    //拖地方法 : throwable,异常
    @Override
    public UserFeignClient create(Throwable throwable) {
        return new UserFeignClient() {
            @Override
            public User getById(Long id) {
                //把异常信息打印到控制台
                throwable.printStackTrace();

                //真正拖地方法
                return new User(-1L,"无此用户","用户服务不可用");
            }
        };
    
Published 33 original articles · won praise 0 · Views 393

Guess you like

Origin blog.csdn.net/weixin_45737653/article/details/104987899