springcloud-熔断器(Hystrix)

Hystrix在cloud有两种使用方式,我感觉有三种。

1、Hystrix+ribbon;

2、Hystrix+feign;

3、zuul(集成的降级处理机制)-后面zuul会提到;

首先创建一个hystrix模块。

再创建hystrixribbon、hystrixfeign模块。

一、hystrix配合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 https://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.3.2.RELEASE</version>
	</parent>
	<groupId>com.cloud</groupId>
	<artifactId>hystrixribbon</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>hystrixribbon</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Hoxton.SR9</spring-cloud.version>
		<spring-cloud-alibaba.version>2.2.6.RELEASE</spring-cloud-alibaba.version>
	</properties>
	<dependencies>
		<!--eureka客户端-->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
			<version>1.4.6.RELEASE</version>
		</dependency>
		<!--熔断器-->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
			<version>1.4.4.RELEASE</version>
		</dependency>

	</dependencies>
	<!--指定下载源和使用springcloud的版本-->
	<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>

			<dependency>
				<groupId>com.alibaba.cloud</groupId>
				<artifactId>spring-cloud-alibaba-dependencies</artifactId>
				<version>${spring-cloud-alibaba.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>

</project>

application.yml

spring:
  application:
    name: service-ribbon-hystrix  #服务应用名称
server:
  port: 8088 #服务端口号

eureka:
  client:
    healthcheck:
      enabled: false #启动服务健康状态的检查
    serviceUrl:
      defaultZone:  http://localhost:8090/eureka #注册服务组件的url
  instance:
    prefer-ip-address: true #使用ip前缀



hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000 #熔断的超时时间
HystrixribbonApplication.java(作为客户端注册到注册中心。增加熔断器注解@EnableCircuitBreaker)
package com.cloud.hystrixribbon;

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

@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class HystrixribbonApplication {

	@Bean
	@LoadBalanced
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}

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

}

TestController

package com.cloud.hystrixribbon.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * <B>技术支持:</B> (c)
 *
 * @author lx.w
 * @version 1.0
 * @since JDK1.8
 */
@RestController
@RequestMapping("/hystrix/ribbon")
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/test")
    @HystrixCommand(fallbackMethod = "fallTest")
    public String test(@RequestParam String s) {
        String str = restTemplate.postForObject("http://client-service/client/hello/world?str=" + s, null, String.class);
        System.out.println("hystrixRibbon");
        return str + " hystrixRibbon";
    }

    /**
     * @desc: 熔断降级方法
     * @author: lx.w
     * @params: params
     */
    private String fallTest(String s) {
        System.out.println("进入熔断降级方法");
        return "no Service" + s;
    }

}

注意看这个TestController的test方法,在头部增加了熔断器的注解@HystrixCommand(fallbackMethod = "fallTest"),通过该注解,当调用的下游服务不可用时,请求会回调到fallbackMethod指定的方法中。

postman直接访问hystrixribbon服务的test接口

当下游服务正常运行时

当下游服务停止时(此时配置在@HystrixCommand(fallbackMethod = "fallTest")中方法fallTest设置的返回值返回)

二、hystrix配合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 https://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.3.2.RELEASE</version>
    </parent>
    <groupId>com.cloud</groupId>
    <artifactId>hystrixfeign</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hystrixfeign</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
        <spring-cloud-alibaba.version>2.2.6.RELEASE</spring-cloud-alibaba.version>
    </properties>
    <dependencies>
        <!--eureka客户端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--熔断器-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.4.RELEASE</version>
        </dependency>
        <!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>
    <!--指定下载源和使用springcloud的版本-->
    <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>

            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.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>

</project>

application.yml(比hystrix+ribbon多了一个feign.hystrix.enabled=true feign熔断器开启的配置)

spring:
  application:
    name: service-feign-hystrix  #服务应用名称
server:
  port: 8087 #服务端口号

eureka:
  client:
    healthcheck:
      enabled: false #启动服务健康状态的检查
    serviceUrl:
      defaultZone:  http://localhost:8090/eureka #注册服务组件的url
  instance:
    prefer-ip-address: true #使用ip前缀
##开启feign的熔断器hystrix
feign:
  hystrix:
    enabled: true

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000 #熔断的超时时间

 

HystrixfeignApplication.java

package com.cloud.hystrixfeign;

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

/**
 * <B>技术支持:</B>  (c)
 *
 * @author lx.w
 * @version 1.0
 * @since JDK1.8
 */
@EnableFeignClients
@EnableDiscoveryClient
@EnableCircuitBreaker
@SpringBootApplication
public class HystrixfeignApplication {

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

}

 在FeignService中添加的注解

@FeignClient中有属性fallbackFactory作为熔断降级属性,也可以使用fallback作为熔断降级属性。即存在两种熔断降级的配置方法。
package com.cloud.hystrixfeign.feign;

import com.cloud.hystrixfeign.feign.fallback.HystrixClientFallBack;
import com.cloud.hystrixfeign.feign.fallback.HystrixClientFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * <B>技术支持:</B>  (c)
 *
 * @author lx.w
 * @version 1.0
 * @since JDK1.8
 */
@FeignClient(value = "client-service", fallbackFactory = HystrixClientFallbackFactory.class)
public interface FeignService {

    @PostMapping("/client/hello/world")
    String helloWorld(@RequestParam("str") String str);

}

TestController.java

package com.cloud.hystrixfeign.controller;

import com.cloud.hystrixfeign.feign.FeignService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <B>技术支持:</B> (c)
 *
 * @author lx.w
 * @version 1.0
 * @since JDK1.8
 */
@RestController
@RequestMapping("/hystrix/feign")
public class TestController {

    @Autowired
    private FeignService feignService;

    @PostMapping("/test")
    public String test(@RequestParam String s) {
        System.out.println("hystrixFeign");
        return feignService.helloWorld(s) + " hystrixFeign";
    }


}

接下来是关键点了,在FeignService中有两种熔断降级的配置方法。首先先讲第一种fallbackFactory。在FeignService的类中,注解@FeignClient(value = "client-service", fallbackFactory = HystrixClientFallbackFactory.class) 使用到的属性为fallbackFactory。

同时需要配置以下两个配置类:

1、HystrixClientWithFallbackFactory

package com.cloud.hystrixfeign.feign.fallback;

import com.cloud.hystrixfeign.feign.FeignService;

public interface HystrixClientWithFallbackFactory extends FeignService {

}

2、HystrixClientFallbackFactory

package com.cloud.hystrixfeign.feign.fallback;

import com.cloud.hystrixfeign.feign.FeignService;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

@Component
public class HystrixClientFallbackFactory implements FallbackFactory<FeignService> {

    @Override
    public FeignService create(Throwable arg0) {
        // TODO Auto-generated method stub
        return new HystrixClientWithFallbackFactory() {

            @Override
            public String helloWorld(String str) {
                return "error client ";
            }
        };
    }

}

使用postman直接访问接口http://localhost:8087/hystrix/feign/test

当调用下游服务正常运行时

 

当调用下游服务异常时(此时配置在HystrixClientFallbackFactory类中降级返回的参数返回)

 

第二种配置@FeignClient(value = "client-service", fallback = HystrixClientFallBack.class)使用到的属性为fallback(需要将第一种配置类HystrixClientFallbackFactory的配置注解@Component注释下)

配置类HystrixClientFallBack.java 

package com.cloud.hystrixfeign.feign.fallback;

import com.cloud.hystrixfeign.feign.FeignService;
import org.springframework.stereotype.Component;

/**
 * <B>技术支持:</B>  (c)
 *
 * @author lx.w
 * @version 1.0
 * @since JDK1.8
 */
@Component
public class HystrixClientFallBack implements FeignService {

    @Override
    public String helloWorld(String str) {
        System.out.println("进入熔断降级");
        return "error client " + str;
    }
}

 使用postman直接访问接口http://localhost:8087/hystrix/feign/test

当调用下游服务正常运行时

当调用下游服务异常时(此时配置在HystrixClientFallbackFactory类中降级返回的参数返回)

思考一下,hystrix+ribbon与hystrix+feign两种组合,第一种组合个人觉得好像不怎么适用,他涉及到服务自己去做熔断降级的措施,我理解在微服务中熔断降级应该统一管理(如果想法不对请在评论区留言讨论)。第二种 hystrix+feign在配置面上好像简单了很多,但是感觉还是有点个性化了。面对再对阿里的sentinel熔断器作深入探讨

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud中,熔断器(Circuit Breaker)是一种用于处理分布式系统中故障和延迟的机制。它的作用是在服务之间进行通信时,当某个服务出现故障或响应过慢时,可以快速失败并返回一个预设的错误响应或备用数据,以保证系统的可用性和稳定性。 熔断器的作用主要体现在以下几个方面: 1. 故障快速失败:当调用的服务出现故障或超时时,熔断器能够快速失败,而不是一直等待超时或者长时间无响应。这样可以减少等待时间,提高系统的响应速度。 2. 服务降级:在高负载或故障情况下,熔断器可以暂时屏蔽一些非核心或可选功能,以保证核心功能的稳定运行。当服务降级被触发时,请求会被重定向到一个备用的处理逻辑,返回一个预先定义的响应,这样可以减轻系统负载并提高响应速度。 3. 故障隔离:熔断器能够通过断开与故障服务的连接,将故障隔离在一定范围内,防止故障在整个系统中蔓延。这样可以保护系统的稳定性,避免故障服务对其他服务的影响。 4. 自动恢复:熔断器能够监控服务的状态,并根据一定的策略自动进行恢复。当故障服务恢复正常时,熔断器会逐渐恢复对该服务的调用,保证系统的平稳过渡。 通过熔断器的作用,可以保护系统免受故障和延迟的影响,提高系统的可用性和稳定性。在Spring Cloud中,常见的熔断器实现包括Netflix Hystrix和Resilience4j等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值