(Thirty-eight) java version of spring cloud micro Services Architecture b2b2c fault-tolerant service e-commerce platform -Hystrix

Scenarios

Distributed systems often appears one of the underlying service is unavailable cause the entire system is unavailable, a phenomenon called avalanche effect service. In order to cope with the avalanche service, a common practice is to manually service degradation. The emergence of Hystrix , it provides us with another option.

Internal processing logic Hystrix

Construction of Hystrix Command object, call the execution method.

Check Hystrix fuse switch is turned on current service, if enabled, downgrade getFallback method is performed.

When the fuse switch is off, then checks whether the current service Hystrix thread pool can receive a new request, if it exceeds the thread pool is full, downgrade getFallback method is performed.

If the thread pool to accept the request, Hystrix started calling service specific logic run method.

If the service fails, the downgrade service getFallback method, and the results reported Metrics update service health.

If the service execution timeout, the downgrade service getFallback method, and the results reported Metrics update service health.

If the service succeeds, the return to normal results.

If getFallback service degradation method is successful, the result is returned downgrade.

If the service degradation method getFallback fails, an exception is thrown.

Not much to say to configure a wave of execution

Maven

     <!--断路由,服务容错保护-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
Java Code

public class BaseService {
    @Autowired
    protected RestTemplate restTemplate;
 
 
    protected static String SERVICE_BIZ = "http://service-biz";
 
    @Bean
    @LoadBalanced
        //开启负载均衡
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
 
 
}
 
 
/**
 * Created by gaomin on 2017/12/24.
 */
@Service
public class RestTemplateServiceImp extends BaseService implements RestTemplateService {
 
    @Override
    @HystrixCommand(fallbackMethod = "getBizSerivceDataErrorBack")
    public Object getBizSerivceData() {
        String url = SERVICE_BIZ+"/index/findUserMenuList";
        Map<String,Object> uriVariables = new HashMap<>();
        return restTemplate.getForObject(url,Object.class);
    }
 
    /**
     * getBizSerivceDataErrorBack 和 getBizSerivceData 参数要一样返回类型也要一样
     * 服务降级 SERVICE_BIZ服务挂了,自动走这个方法.适用于所有第三方
     * 调用别的服务时,如果别的服务未响应,会导致本服务请求阻塞,这个可以解决断路由保护
     * 直接返回error,默认请求时间2000毫秒
     * @return
     */
    public Object getBizSerivceDataErrorBack(){
        //可以重新请求,还可以继续降级 ....
        return null;
    }
 
}

Guess you like

Origin blog.csdn.net/vvx0206/article/details/93967079