•断路器功能非常强大,不仅仅只是这些属性和使用方式,还有非常牛掰的功能,深入学习断路器非常的必要。
•比如还可以单独设置某个服务的http调用断路器超时时间等:使用commandKey与commandProperties属性相互结合使用,可以单独的控制特殊需求的实现。
•再比如断路器执行的隔离策略,对应着并发量剧增的场景下使用限流的方式,比传统的限流策略、限流组件有天然的优势。
•还有强大的缓存功能,可以结合着spring cache配合使用 缓存http请求的结果。
•断路器为我们提供了批量请求合并的功能,可以将多少频率的http请求批量合并在一起,发送一个http请求到对应的服务端,节省了http访问的次数,在超高频访问的场景中非常的有效。
一、 在接口上为特定服务方法设置超时时间(局部超时设置会覆盖全局设置):
package com.cc.springcloud.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
@Service
public class HelloService {
@Autowired
private RestTemplate restTemplate;
/**
* 服务超时调用异常(服务的调用方)
* @return
*/
@HystrixCommand(fallbackMethod = "callHelloFailback")
public String callHello() {
String ret = restTemplate.getForObject("http://provider-service/hello", String.class);
System.out.println("hello service ret:"+ret);
return ret;
}
public String callHelloFailback() {
return "hello服务调用失败,进行降级处理";
}
/**
* 服务内部异常(被调用方)
* @return
*/
@HystrixCommand(fallbackMethod = "callHiFailback")
public String callHi() {
String ret = restTemplate.getForObject("http://provider-service/hi", String.class);
System.out.println("hi service ret:"+ret);
return ret;
}
public String callHiFailback() {
return "hi服务调用失败,进行降级处理";
}
/**
* 在服务的内部指定一个超时时间配置
* 一般来讲,需要设置一个全局的默认断路器超时时间,在application.properties中;
* 如业务需要会在具体的服务设置单独的设置超时时间
*
*/
@HystrixCommand(fallbackMethod = "timeoutFailback", //定义降级方法
commandKey = "callHello4timeout", //指定hystrix的方法的key,可以与方法名一致,也可自己定义
commandProperties = { //配置hystrix属性
//属性以Key-Value形式进行设置,可添加多个
//是否对此方法使用断路器超时,设置为true,即启用;其运行过程中会覆盖掉此application.properties全局设置
@HystrixProperty(name="execution.timeout.enabled",value="true"),
//设置超时时间,即单独指定此方法3秒钟超时时间,超时后会执行降级方法timeoutFailback
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")
}
)
public String callHello4timeout() {
String ret = restTemplate.getForObject("http://provider-service/hello", String.class);
System.out.println("hello service ret:"+ret);
return ret;
}
public String timeoutFailback() {
return "在callHello4timeout服务接口上定制超时时间,调用失败,进行降级处理";
}
}
-------------------------------------------------------------------------------
package com.cc.springcloud.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cc.springcloud.service.HelloService;
@RestController
public class ConsumerController {
@Autowired
private HelloService helloService;
@RequestMapping(value="/hystrix-hello")
public String hello() throws Exception {
return helloService.callHello();
}
@RequestMapping(value="/hystrix-hi")
public String hi() throws Exception {
return helloService.callHi();
}
@RequestMapping(value="/hystrix-callhello")
public String callhello() throws Exception {
return helloService.callHello4timeout();
}
}
访问后3秒钟返回了超时结果:
二、Hystrix结合spring cache做批量请求合并与发送:
代码模拟:
1.生产者:spring-cloud-03-provider-1和spring-cloud-03-provider-2相同;
package com.cc.springcloud.api;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.cc.springcloud.entity.User;
@RestController
public class ProviderController {
@RequestMapping(value="/hello")
public String hello() throws InterruptedException{
System.out.println("-----provider-1:say hello!-----");
Thread.sleep(5000); //模拟超时
return "-----provider-1:say hello!-----";
}
@RequestMapping(value="/hi")
public String hi() throws Exception{
int a = 1/0; //使程序抛出异常
System.out.println("-----provider-1:say hi!-----");
return "-----provider-1:say hi!-----";
}
/**
* 单独查询User接口
* 使用rest风格path方式 传递参数
* 请求方式为:http://localhost:7001/users/1
* 参数需要声明 @PathVariable
*/
@RequestMapping(value="/users/{id}")
public User getUser(@PathVariable String id) throws Exception {
//此处伪代码未查询数据库
System.out.println("provider-1 单独查询-------------》"+id);
return new User("1","张三");
}
/**合并请求需要单独接口和批量接口结合实现
* 批量查询Users接口
*/
@RequestMapping(value="/users")
public List<User> getUsers(@RequestParam("ids") String ids) throws Exception {
//此处伪代码未查询数据库
System.out.println("provider-1 批量查询-------------》"+ids);
List<User> users = new ArrayList<>();
users.add(new User("2","李四"));
users.add(new User("3","王五"));
users.add(new User("4","陈六"));
users.add(new User("5","冯七"));
return users;
}
}
【注意:单独查与批量查的URL(名称)一定要保持一致,(value="/users/{id}")和(value="/users")】
2.消费者:spring-cloud-03-hystrix-consumer-1
package com.cc.springcloud.service;
import java.util.List;
import java.util.concurrent.Future;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.cc.springcloud.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
@Service
public class HelloService {
@Autowired
private RestTemplate restTemplate;
/**
* 服务超时调用异常(服务的调用方)
* @return
*/
@HystrixCommand(fallbackMethod = "callHelloFailback")
public String callHello() {
String ret = restTemplate.getForObject("http://provider-service/hello", String.class);
System.out.println("hello service ret:"+ret);
return ret;
}
public String callHelloFailback() {
return "hello服务调用失败,进行降级处理";
}
/**
* 服务内部异常(被调用方)
* @return
*/
@HystrixCommand(fallbackMethod = "callHiFailback")
public String callHi() {
String ret = restTemplate.getForObject("http://provider-service/hi", String.class);
System.out.println("hi service ret:"+ret);
return ret;
}
public String callHiFailback() {
return "hi服务调用失败,进行降级处理";
}
/**
* 在服务的内部指定一个超时时间配置
* 一般来讲,需要设置一个全局的默认断路器超时时间,在application.properties中;
* 如业务需要会在具体的服务设置单独的设置超时时间
*
*/
@HystrixCommand(fallbackMethod = "timeoutFailback", //定义降级方法
commandKey = "callHello4timeout", //指定hystrix的方法的key,可以与方法名一致,也可自己定义
commandProperties = { //配置hystrix属性
//属性以Key-Value形式进行设置,可添加多个
//是否对此方法使用断路器超时,设置为true,即启用;其运行过程中会覆盖掉此application.properties全局设置
@HystrixProperty(name="execution.timeout.enabled",value="true"),
//设置超时时间,即单独指定此方法3秒钟超时时间,超时后会执行降级方法timeoutFailback
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")
}
)
public String callHello4timeout() {
String ret = restTemplate.getForObject("http://provider-service/hello", String.class);
System.out.println("hello service ret:"+ret);
return ret;
}
public String timeoutFailback() {
return "在callHello4timeout服务接口上定制超时时间,调用失败,进行降级处理";
}
/**
* 使用hystrix的批量合并请求功能;
* 需要使用@HystrixCollapser注解
* 此方法每200毫秒发送50个请求,200毫秒内将所有请求缓存,然后在200后,调用findAll方法执行;
* 最大合并数50个如果在200毫秒内合并,直接发送;
*/
@HystrixCollapser(batchMethod = "findAll",
collapserProperties = {
//配置单个请求延迟时间为200毫秒,意味着这个请求200毫秒后会被发送
@HystrixProperty(name="timerDelayInMilliseconds",value="200"),
//配置允许最大的合并请求数量为
@HystrixProperty(name="maxRequestsInBatch",value="50"),
//是否启用请求的本地缓存(对于一些静态数据可以启用,变化的动态数据不要启用,时间间隔内自我清理性能低)
@HystrixProperty(name="requestCache.enabled",value="false")
}
)
public Future<User> find(String id){
return null;
}
@HystrixCommand
public List<User> findAll(List<String> ids){
//查看是否为同一个线程
System.out.println("合并请求线程操作:------------------》" + Thread.currentThread().getName());
//users?ids={1},参数拼接:StringUtils.join(ids,",")
List<User> users = restTemplate.getForObject("http://provider-service/users?ids={1}", List.class,StringUtils.join(ids,","));
return users;
}
}
3.测试请求:
package com.cc.springcloud.api;
import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cc.springcloud.entity.User;
import com.cc.springcloud.service.HelloService;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
@RestController
public class ConsumerController {
@Autowired
private HelloService helloService;
@RequestMapping(value="/hystrix-hello")
public String hello() throws Exception {
return helloService.callHello();
}
@RequestMapping(value="/hystrix-hi")
public String hi() throws Exception {
return helloService.callHi();
}
@RequestMapping(value="/hystrix-callhello")
public String callhello() throws Exception {
return helloService.callHello4timeout();
}
@RequestMapping(value="/hystrix-batch")
public String batch() throws Exception {
//最优的方式是初始化一个HystrixRequestContext上下文对象
HystrixRequestContext ctx = HystrixRequestContext.initializeContext();
//模拟数据为四个,请求也要对应,否则会报异常
//请求是异步所以使用Future包装
Future<User> f1 = helloService.find("1");
Future<User> f2 = helloService.find("2");
Future<User> f3 = helloService.find("3");
Future<User> f4 = helloService.find("4");
System.out.println(f1.get());
System.out.println(f2.get());
System.out.println(f3.get());
System.out.println(f4.get());
//模拟超出200毫秒
Thread.sleep(500);
Future<User> f5 = helloService.find("5");
System.out.println(f5.get());
ctx.close();
return "batch success";
}
}
4.输出结果:
consumer控制台:两个线程请求结果
provider-1控制台:执行了第二次的请求
provider-2控制台:执行了第一次请求
两次都是批量请求,在此批量与单独请求性能基本一致;(如果想单独的一个请求使用单独请求需要重新实现; )
请求地址返回:
【实际工作中并发量请求接口大的时候,尽量使用Hystrix这种合并请求方式】