Hystrix服务容错处理实践

过程笔记:在微服务调用过程中,为了避免因个别服务提供者出错而出现的级联错误(上层服务消费者线程堵塞),采取hystrix工具进行容错处理,并借助hystrixdashboard工具监控服务消费者的运行状况。

服务提供者侧(user-service):

在某个controller接口中,加入大延时,模拟接口失效,并启动工程。

服务消费者侧(api-gateway):

1、加入hystrix和actuator依赖,前者提供hystrix工具库,后者提供url的访问接口。

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

2、approperties文件中加入以下配置。其中management.server.port表示服务消费者的actuator信息端口,原有的actuator信息端口就是工程的server.port,因为工程需要将actuator信息端口暴露给外部,所以原有方案会将工程端口暴露给外部,会遗留安全问题,所以才将工程端口与actuator信息端口分开;第二条配置表示,在actuator信息端口中暴露hystrix的监控信息。

management.server.port=8023
management.endpoints.web.exposure.include=hystrix.stream

3、继续在approperties文件中添加hystrix配置,这里不做详细说明,具体参数作用可以去hystrix的Github项目中查找,hystrix参数官方文档链接

hystrix.threadpool.default.coreSize=5
hystrix.threadpool.default.maxQueueSize=1
hystrix.threadpool.default.maximumSize=10
hystrix.threadpool.default.allowMaximumSizeToDivergeFromCoreSize=true

hystrix.command.default.circuitBreaker.errorThresholdPercentage=10
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds=10000

3、在服务提供者加入时延的特定接口所对应的服务消费者方法所在repository类上添加注解,并在方法上添加注解,添加降级方法。

@Repository
@DefaultProperties(groupKey="userDao",
commandProperties={@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000")},
threadPoolProperties={@HystrixProperty(name="coreSize",value="10")
,@HystrixProperty(name="maxQueueSize",value="1000")},
threadPoolKey="userDao")
public class UserDao {
    public User getUserByTokenFb(String token){
        return new User();
    }
    @HystrixCommand(fallbackMethod="getUserByTokenFb")
    public User getUserByToken(String token) {}
}

4、服务消费者启动类添加注解

@EnableCircuitBreaker
public class ApiGatewayApplication {}

5、启动工程

dashboard侧(hystrix-dashboard):

1、添加hystrix、hystrix-dashboard、actuator依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<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>

2、approperties文件添加端口信息

server.port=9097

3、启动类加注解

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

4、启动dashboard工程之后,访问http://127.0.0.1:9097/hystrix,之后输入监控地址
http://127.0.0.1:8023/actuator/hyxtrix.stream,即可看到监控内容。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容