Spring Cloud(Greenwich.SR1) - 服务熔断Hystrix

前言

hystrix是netflix开源的服务熔断组件,在Spring Cloud中整合进来,形成Spring Cloud的熔断降级体系。服务降级主要是为了服务雪崩,造成下游的服务不可用,可用性是分布式服务的必须要求。

1. ribbon服务

在上一章的ribbon服务,仅需添加netflix的组件,加入注解即可,下面来改造ribbon-consumer项目,熔断是服务调用方执行。

pom修改,加入

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  </dependency>

要开启服务,需要在main类上注上@EnableHystrix

package com.spring.cloud.ribbon.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;

@EnableDiscoveryClient
@SpringBootApplication
@EnableHystrix
public class RibbonConsumerMain {
    public static void main(String[] args) {
        SpringApplication.run(RibbonConsumerMain.class, args);
    }
}

同样,熔断后需要如何处理,需要调用方写处理逻辑。需要在服务方法上加上@HystrixCommand注解

package com.spring.cloud.ribbon.consumer.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class ConsumerService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "consumerMarkError")
    public Map consumerMark() {
        return restTemplate.getForObject("http://RIBBON-SERVICE/mark",Map.class);
    }
    
    @HystrixCommand(defaultFallback = "consumerMarkError")
    public Map consumerMark2() {
        return restTemplate.getForObject("http://RIBBON-SERVICE/mark",Map.class);
    }

    public Map consumerMarkError() {
        Map<String, String> map = new HashMap<>();
        map.put("error", "service is not used");
        return map;
    }
}

设置熔断后处理逻辑,可设置默认fallback。访问http://localhost:8205/consumer/,服务正常。

当我们停掉8203端口,spring.profiles=r2的服务出现熔断

再次刷新,由于ribbon轮训服务又可以访问,下次刷新,又出现熔断

 

总结

服务熔断是Spring Cloud集成netflix的hystrix模块实现的,并用ribbon项目做实现,但这样会很麻烦,这两种功能都需要配置,Spring Cloud为了处理这些不方便,将这两种常用的功能集成进来,就是feign。

 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值