Hystrix基础以及如果配合Feign使用Hystrix

Hystrix

1.Hystrix 是什么?

在分布式的环境下,在访问一些服务的时候不可避免的会有失败的情况.比如其中一些服务器宕机了导致该服务器的的服务无法访问.Hystrix就是一个帮助在服务与服务之间交互的时候添加延迟和容错逻辑的一个组件.

2.Hystrix 用来做什么?

  1. 为使用第三方工具访问依赖服务(通常是通过网络的访问)提供失败和延迟保护
  2. 阻止在复杂的分布是环境中由于某个或者几个服务不可用而导致整个服务瘫痪(服务雪崩)
  3. 快速失败与快速恢复
  4. 提供接近真实时间的监控和报警

3.怎么使用Hystrix,以及Hystrix的配置属性详情

  1. 怎么使用原生Hystrix
  2. Hystrix的配置属性详情

4.使用Feign集成Hystrix

Feign集成Hystrix在SpringCloud项目可以很简单的实现,我们唯一需要注意的是在Feign中使用Hystrix, groupKey,commandKey,ThreadPoolKey 分别为serviceId(Eureka服务注册Id),类名#方法名(方法参数类型),serviceId.意味着他们同一个FeignClient下公用同一个ThreadPool但是有独立的熔断器,和其他配置信息.下面附上一些代码:

使用的cloud的版本为Edgware.SR5

<parent>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-parent</artifactId>
		<version>Edgware.SR5</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<!--Eureka-->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>

		<!--Feign-->
		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>

		<!--Ribbon-->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-ribbon</artifactId>
		</dependency>

		<!-- hystrix断路器组件依赖 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
		</dependency>

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

		<!--测试-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

	</dependencies>


	<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>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>

启动类

package com.example.hystrix;

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.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

@SpringBootApplication
@EnableCircuitBreaker
@EnableDiscoveryClient
@EnableFeignClients
@EnableHystrixDashboard
public class DemoApplication {

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

FeignClient 类

package com.example.hystrix;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@FeignClient(name = "USERMANAGEMENT-SERVICE", fallback = UserClientFallback.class)
public interface UserClient {

    @HystrixCommand(fallbackMethod = "findUserByUsername")
    @RequestMapping(value = "/users/{username}", method = RequestMethod.GET)
    public User findUserByUsername(@PathVariable("username") String username);

    @HystrixCommand(ignoreExceptions = {RuntimeException.class})
    @RequestMapping(value = "/users/id/{id}", method = RequestMethod.GET)
    public User findUserById(@PathVariable("id") Integer id);


}

Fallback 类

package com.example.hystrix;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Component
public class UserClientFallback implements UserClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserClientFallback.class);

    @Override
    public User findUserByUsername(String username) {
        System.out.println("enter fallback method...");
        return new User(username, 1);
    }

    @Override
    public User findUserById(Integer id) {
        System.out.println("enter fallback method...");
        return new User("normal", 1);
    }

}

配置文件

server:
  port: 8089

spring:
  application:
    name: learn-hystrix

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
    registerWithEureka: true
  instance:
    preferIpAddress: true
    instance-id: ${spring.cloud.client.ipAddress}:${server.port}


feign:
  hystrix:
    enabled: true

hystrix:
  command:
    "UserClient#findUserByUsername(String)":
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 5000
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 10000
  threadpool:
    default:
      coreSize: 100

ribbon:
  ConnectTimeout: 50000
  ReadTimeout: 30000

配置文件中单独配置了findUserByUsername的Timeout时间,其他配置可以仿照这种方式,但是要注意的是每一个Feign client对应的是一个threadPool所以不能针对每个command配置不同的threadPool.但是Threadpool.default.coreSize中的default可以改成serviceId,如果有多个服务的话可以配置不一样的threadPool.

5.Hystrix dashboard, Hystrix turbine

在使用turbine中的时候需要单独起一个服务,并且使用@EnableTurbine开启.需要注意的点是使用的cloud版本最好和微服务中的cloud一致,因为较早版本使用url /hystrix.stream 收集信息,而较新的版本使用/actuator/hystrix.stream收集信息.如果两边不一致的话会导致404错误.下面附上代码:

pom:

<?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>

	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<spring-cloud.version>Edgware.SR5</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-hystrix-dashboard</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-turbine</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-netflix-eureka-client</artifactId>
			<version>1.3.0.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</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>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>


</project>

启动类:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.cloud.netflix.turbine.EnableTurbine;

@SpringBootApplication
@EnableHystrixDashboard
@EnableTurbine
@EnableDiscoveryClient
public class DemoApplication {

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

配置文件:

spring:
  application:
    name: turbine

server:
  port: 9090


eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
    registerWithEureka: true
  instance:
    preferIpAddress: true
    instance-id: ${spring.cloud.client.ipAddress}:${server.port}
turbine:
  aggregator:
    clusterConfig: LEARN-HYSTRIX
  appConfig: learn-hystrix

注意:

  1. 微服务注册到Eureka中的时候最好的Instance-id为Ip+端口号,否则在收集信息的时候会有错误
  2. appConfig为服务列表多个用逗号连接
  3. clusterConfig: 为监控聚合的url,多个话用逗号连接,举个例子:http://localhost:9090/turbine.stream?cluster=LEARN-HYSTRIX
  4. 进入dashboard url http://localhost:{port}/hystrix
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值