RestTemplate+Hystrix
作者:互联网
项目中调用第三方采购的项目,采用的是restTemplate,但这样无法做线程隔离。
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.*; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import java.util.Map; /** * @author duanxz * 2019年6月1日 下午3:41:34 */ @Component public class RestTemplateHystrixCombination { private Logger logger = LoggerFactory.getLogger(RestTemplateHystrixCombination.class); @Resource @Qualifier("getRestTemplate2") RestTemplate restTemplate; /** * * @param url * @param name * @return */ @HystrixCommand(groupKey="CrmGroup", commandKey = "getTest", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),//指定多久超时,单位毫秒。超时进fallback @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//判断熔断的最少请求数,默认是10;只有在一个统计窗口内处理的请求数量达到这个阈值,才会进行熔断与否的判断 @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),//判断熔断的阈值,默认值50,表示在一个统计窗口内有50%的请求处理失败,会触发熔断 }, threadPoolProperties = { @HystrixProperty(name = "coreSize", value = "1"), @HystrixProperty(name = "maximumSize", value = "1"), @HystrixProperty(name = "maxQueueSize", value = "0"), @HystrixProperty(name = "keepAliveTimeMinutes", value = "2"), @HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"), @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "12"), @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "1440")}) public Object getTest(String url, String name) { Object origResult = restTemplate.getForEntity(url, String.class); return origResult; } }
groupKey和commandKey都是自定义的,取一下能代表业务含义的就好。
timeoutInMilliseconds、coreSize和maximumSize是我要的
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/restTemplate") public class RestTemplateHystrixCombinationController { @Autowired RestTemplateHystrixCombination restService; @GetMapping("/test") public Object testabc(){ return restService.getTest("http://172.29.163.90:8088/uniteApi/riskService/riskService/sync", "duanxz"); } }
标签:name,Hystrix,RestTemplate,value,HystrixProperty,springframework,org,import 来源: https://www.cnblogs.com/duanxz/p/15708773.html