springcloud集成hystrix 实现服务的隔离,熔断,降级

2023-11-06

一、pom引入依赖

<!-- hystrix断路器 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
		</dependency>

二、app类添加注解@EnableHystrix

package com.wangcj;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
//将当前服务注册到eureka上
@EnableEurekaClient
@EnableFeignClients
@EnableHystrix
public class OrderApp {

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

三、在需要使用的方法上加上注解@HystrixCommand,如下 getUserInfoFallBack 即为服务降级的回调函数

package com.wangcj.api.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.wangcj.api.entity.UserEntity;
import com.wangcj.api.feign.MemberService;
import com.wangcj.api.service.IOrderService;
import com.wangcj.base.BaseApiService;
import com.wangcj.base.ResponseBase;

@RestController
public class OrderServiceImpl extends BaseApiService implements IOrderService {

	@Autowired
	private MemberService memberService;
	
	@Override
	@RequestMapping("/getMember")
	public String getOrderToMember(@RequestParam("name") String name) {
		UserEntity member = memberService.getMember(name);
		return member.toString();
	}

	public ResponseBase getUserInfoFallBack() {
		return setResultSuccess("服务器繁忙,请稍后再试!");
	}
	
	@Override
	//fallbackMethod 方法在服务降级的时候使用,即返回友好的提示
	//@HystrixCommand 默认开启服务隔离--线程池隔离方式,服务熔断,服务降级
	@HystrixCommand(fallbackMethod = "getUserInfoFallBack")
	@RequestMapping("/getUserInfo")
	public ResponseBase getOrderToMemberSleep() {
		return memberService.getUserInfo();
	}

}

四、yml文件添加配置

###开启Hystrix断路器
feign: 
  hystrix:
    enabled: true
#### hystrix禁止服务超时时间
#hystrix:  
# command: 
#   default: 
#      execution:
#       timeout: 
#        enabled: false

五、服务降级、熔断执行过程

Hystrix 熔断机制,当失败的情况达到预定的阈值(5秒失败20次),会打开断路器,拒绝所有请求,直到服务恢复正常为止。

 当达到阈值时,会打开断路器,拒绝所有请求,经过5s后服务会半开尝试请求调用,如果失败情况未达到阈值,则服务恢复正常。

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

springcloud集成hystrix 实现服务的隔离,熔断,降级 的相关文章

随机推荐