yangyang12138

导航

spring-cloud熔断和负载均衡

1.服务熔断,是指当前服务调用的另一个服务响应超时的时候会直接终止调用而直接调用备用的另一个方法,称为服务降级。

配置类

@Configuration
public class HystrixConfig {

    @Bean
    public ServletRegistrationBean getServlet() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }
}

服务类

@Service
@Slf4j
public class EurekaRibbonService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(
            commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1000"),
            @HystrixProperty(name = "execution.isolation.strategy",value = "THREAD")},
            fallbackMethod = "syaHelloFailure")
    public String sayHello() {
        String message;
message = restTemplate.getForObject("http://eureka-client/info", String.class); return message; } public String syaHelloFailure() {return "error"; } }

 

启动类中加入@EnableHystrix注解。

 

2.负载均衡

spring-cloud的负载均衡是在客户端完成的

负载均衡的规则:

NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #配置规则 随机
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule #配置规则 轮询
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RetryRule #配置规则 重试
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule #配置规则 响应时间权重

ribbon方式
@Configuration
public class RestTemplateConfig {

    @Bean
    @LoadBalanced //实现负载均衡
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

配置文件

eureka-client: #对应的服务client的name
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

如果是使用feign方式则只配置yml文件即可。

 

posted on 2020-04-10 03:01  杨杨09265  阅读(609)  评论(0编辑  收藏  举报