SpringCloud - (五)熔断器Hystrix

熔断器

服务雪崩效应

在微服务架构中通常会有多个服务层调用,基础服务的故障可能会导致级联故障,进而造成整个系统不可用的情况,这种现象被称为服务雪崩效应。服务雪崩效应是一种因“服务提供者”的不可用导致“服务消费者”的不可用,并将不可用逐渐放大的过程。

在这里插入图片描述

Hystrix

在微服务架构中,我们将系统拆分为很多个服务,各个服务之间通过注册与订阅的方式相互依赖,由于各个服务都是在各自的进程中运行,就有可能由于网络原因或者服务自身的问题导致调用故障或延迟,随着服务的积压,可能会导致服务崩溃。为了解决这一系列的问题,断路器等一系列服务保护机制出现了。

断路器本身是一种开关保护机制,用于在电路上保护线路过载,当线路中有电器发生短路时,断路器能够及时切断故障电路,防止发生过载、发热甚至起火等严重后果。

在分布式架构中,断路器模式的作用也是类似的。

针对上述问题,Spring Cloud Hystrix 实现了断路器、线路隔离等一系列服务保护功能。它也是基于 Netflix 的开源框架 Hystrix 实现的,该框架的目标在于通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。Hystrix 具备服务降级、服务熔断、线程和信号隔离、请求缓存、请求合并以及服务监控等强大功能。

项目总览

在这里插入图片描述
spring-cloud-hystrix:一个maven项目
eureka-server:提供服务注册和发现
eureka-service-provider:服务提供方
eureka-consumer-ribbon:ribbon方式消费服务
eureka-consumer-feign:feign方式消费服务

示例代码会放到github上,在文章结尾。

关于项目的搭建这里不多说了,之前有写过
搭建项目:
服务注册发现中心和服务提供搭建点这里
消费服务搭建点这里

Feign + Hystrix

eureka-consumer-feign的结构如下:
在这里插入图片描述
eureka-consumer-feign的pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wy</groupId>
    <artifactId>eureka-consumer-feign</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>eureka-consumer-feign</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RC2</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

</project>

application.yml

# 配置服务器端口
server:
  port: 8921
spring:
  application:
    name: eureka-consumer-feign
# 注册服务
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8000/eureka/
# 配置启动断路器
feign:
  hystrix:
    enabled: true

启动类EurekaConsumerFeignApplication加@EnableDiscoveryClient和@EnableFeignClients注解

package com.wy.eurekaconsumerfeign;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class EurekaConsumerFeignApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaConsumerFeignApplication.class, args);
    }

}


在HelloRemote接口的注解中加上fallback的指定类就行了:

package com.wy.eurekaconsumerfeign.remote;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(name= "eureka-service-provider",fallback = HelloRemoteHystrix.class)
public interface HelloRemote {
    @RequestMapping(value = "/hello/index")
    public String hello(@RequestParam(value = "name") String name);
}


HelloRemoteHystrix需要实现HelloRemote接口,并注入到Ioc容器中,代码如下:

package com.wy.eurekaconsumerfeign.remote;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

@Component
public class HelloRemoteHystrix implements HelloRemote{

    @Override
    public String hello(@RequestParam(value = "name") String name) {
        return "hello  " +name+", this messge send failed ";
    }
}

测试类TestController代码如下:

package com.wy.eurekaconsumerfeign.controller;


import com.wy.eurekaconsumerfeign.remote.HelloRemote;
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("/feign")
public class TestController {

    @Autowired
    private HelloRemote helloRemote;

    @RequestMapping("/index/{name}")
    public  String index(@PathVariable("name") String name){
        return helloRemote.hello(name);
    }
}

依次启动eureka-server,eureka-service-provider,eureka-consumer-feign
访问http://localhost:8921/feign/index/wy
在这里插入图片描述说明访问服务成功。停止eureka-service-provider,再访问http://localhost:8921/feign/index/wy
在这里插入图片描述说明Hystrix生效了。

接下来重新启动eureka-service-provider,再访问http://localhost:8921/feign/index/wy
在这里插入图片描述又可以访问服务了。

Ribbon + Hystrix

eureka-consumer-ribbon项目总览:
在这里插入图片描述
eureka-consumer-ribbon的pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wy</groupId>
    <artifactId>eureka-consumer-ribbon</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>eureka-consumer-ribbon</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RC2</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

</project>

eureka-consumer-ribbon的application.yml如下:

# 配置服务器端口
server:
  port: 8920
spring:
  application:
    name: eureka-consumer-ribbon
# 注册服务
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8000/eureka/


启动类EurekaConsumerRibbonApplication加@EnableDiscoveryClient和@EnableHystrix,注入restTemplate, 并且开启负载均衡,代码如下:

package com.wy.eurekaconsumerribbon;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class EurekaConsumerRibbonApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaConsumerRibbonApplication.class, args);
    }

    /**
     * 注入restTemplate, 并且开启负载均衡
     */
    @Bean
    @LoadBalanced
    public RestTemplate createRestTemplate() {
        return new RestTemplate();
    }
}


HelloService接口代码如下:

package com.wy.eurekaconsumerribbon.service;

public interface HelloService {

    String hello(String name);
}

HelloServiceImpl实现HelloService 接口,并用**@HystrixCommand**指定fallbackMethod方法,代码如下:

package com.wy.eurekaconsumerribbon.service.impl;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.wy.eurekaconsumerribbon.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

@Service
public class HelloServiceImpl implements HelloService {

    @Autowired
    private RestTemplate restTemplate;


    @HystrixCommand(fallbackMethod = "handleError")
    @Override
    public String hello(String name) {
        return restTemplate.getForObject("http://eureka-service-provider/hello/index?name="+name, String.class);
    }

    /**
     * @description: 断路器方法
     * @return
     */
    public String handleError(String name) {
        return "hello  "+name +",I am so sorry,Server has error";
    }

}

测试类TestController代码如下:

package com.wy.eurekaconsumerribbon.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.wy.eurekaconsumerribbon.service.HelloService;
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("/ribbon")
public class TestController {

    @Autowired
    private HelloService helloService;


    @RequestMapping(value = "/hello/{name}")
    public String hello(@PathVariable("name") String name) {
        return helloService.hello(name);
    }


}

依次启动eureka-server,eureka-service-provider,eureka-consumer-ribbon
访问http://localhost:8920/ribbon/hello/wy
在这里插入图片描述说明访问服务成功。停止eureka-service-provider,再访问http://localhost:8920/ribbon/hello/wy

在这里插入图片描述说明Hystrix生效了。

接下来重新启动eureka-service-provider,再访问
http://localhost:8920/ribbon/hello/wy
在这里插入图片描述又可以访问服务了。


ps:
@EnableDiscoveryClient向服务中心注册
@EnableFeignClients注解开启Spring Cloud Feign的支持功能。

实例代码–github

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值