Spring Cloud引入Hystrix服务调用

Hystrix是熔断机制,类似电路中的保险丝,防止服务出现雪崩效应。服务雪崩效应是一种因“服务提供者”的不可用,导致“服务消费者”的不可用,并将“不可用”服务逐渐放大的过程,最终导致系统崩溃。
Hystrix特性之一服务降级处理,实现fallback方法,当请求服务出现异常的时候,可以使用fallback方法返回本地信息,不再与远端服务器交互。
为了说明关键点,以下代码是增量,其他代码参见上篇:Spring Cloud引入Feign服务调用

1、服务提供者降级处理(Hystrix)

使用Hystrix规范编写fallbackMethod方法
pom.xml 引入hystrix包

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-hystrix</artifactId>
	<version>1.4.6.RELEASE</version>
</dependency>

HelloController.java 增加Fallback方法,当出现错误时进行熔断
本方法假设入口参数为空时,引发熔断

@RestController
public class HelloController {    
    @RequestMapping("/hello")
    @HystrixCommand(fallbackMethod="helloFallback")
    // 如果当前方法出现错误,则执行helloFallback进行熔断
    public Object hello(@RequestParam String name) {
    	//check param
    	if(name == null || "".equals(name)){
    		//入口参数为空,抛出错误
    		throw new RuntimeException("the Request Param name is empty!") ;
    	}
    	Map<String,String> obj = new HashMap<String,String>();
    	obj.put("name", name);
    	obj.put("memo", "the messge come from Spring-Cloud-Provider");
        return obj;
    }
    
    /**
     * 发生错误的回调方法,参数需要与原方法hello保持一致
     */
    public Object helloFallback(@RequestParam String name) {
    	//入口参数为空
    	Map<String,String> obj = new HashMap<String,String>();
    	obj.put("name", "the name is empty!");
    	obj.put("memo", "the error messge come from Spring-Cloud-Provider");
        return obj;
    }
}

SpringBootApplication类需要引入熔断注解 EnableCircuitBreaker,否则出现如下错误:
nameisempty
CloudProviderApplication.java 引入熔断注解

@EnableEurekaClient
@SpringBootApplication
@EnableCircuitBreaker//启动熔断处理
public class CloudProviderApplication {
	public static void main(String[] args) {
		SpringApplication.run(CloudProviderApplication.class, args);
	}
}

CircuitBreaker

2、服务消费者降级处理(Feign)

使用Feign规范编写fallback类,Feign已融合Hystrix
application.properties

feign.hystrix.enabled=true

HelloFeignFallback.java 回调类继承与HelloFeignRemote实现回调方法

@Component
public class HelloFeignFallback implements HelloFeignRemote{
	@Override
	public String hello(String name) {
    	//提供服务者出现异常状况,熔断返回
    	Map<String,String> obj = new HashMap<String,String>();
    	obj.put("name", "the provider is exception!");
    	obj.put("memo", "the fall messge come from local service");
		return obj.toString();
	}
}

HelloFeignRemote.java FeignClient注解引入HelloFeignFallback类

@FeignClient(name = "spring-cloud-provider",fallback = HelloFeignFallback.class)
public interface HelloFeignRemote {
	@RequestMapping(value = "/hello")
	public String hello(@RequestParam(value = "name") String name);
}

停止provider服务,测试
provider

猜你喜欢

转载自blog.csdn.net/weixin_44153121/article/details/86680677
今日推荐