1.在一個請求執行以前,都必須先初始化一個request contextjava
HystrixRequestContext context = HystrixRequestContext.initializeContext();
而後在請求結束以後,須要關閉request contextweb
context.shutdown();
通常來講,在java web來的應用中,都是經過filter過濾器來實現的緩存
filter:tomcat
/** * hystrix請求上下文過濾器 * @author 張三丰 * */ public class HystrixRequestContextFilter implements Filter { public void init(FilterConfig config) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HystrixRequestContext context = HystrixRequestContext.initializeContext(); try { chain.doFilter(request, response); } catch (Exception e) { e.printStackTrace(); } finally { context.shutdown(); } } public void destroy() { } }
command:網絡
/** * 獲取商品名稱的command * @author 張三丰 * */ public class GetProductNameCommand extends HystrixCommand<String> { private Long productId; public GetProductNameCommand(Long productId) { super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("BrandInfoService")) .andCommandKey(HystrixCommandKey.Factory.asKey("GetproductNameCommand")) .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("GetproductInfoPool")) .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()//配置線程池 .withCoreSize(15) .withQueueSizeRejectionThreshold(10)) .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()//配置信號量(這個參數設置了HystrixCommand.getFallback()最大容許的tomcat併發請求數量,默認值是10,也是經過semaphore信號量的機制去限流若是超出了這個最大值,那麼直接被reject)
.withFallbackIsolationSemaphoreMaxConcurrentRequests(15)) ); this.productId = productId; } @Override protected String run() throws Exception { // 調用一個商品服務的接口(對於同一個請求,會被緩存,好比productId=100的商品請求兩次,那麼第二次會直接查緩存,不會進到這裏) // 若是調用失敗了,報錯了,那麼就會去調用fallback降級機制 throw new Exception(); }
//拋出異常,走降級接口 @Override protected String getFallback() {
//從緩存拿數據,儘可能別走網絡,若是非得走網絡,須要再次調用command System.out.println("從本地緩存獲取商品數據,productId=" + productId); return "商品名稱"; } //開啓請求緩存 @Override protected String getCacheKey() { return "product_info_" + productId; } }
controller中:併發
@RequestMapping("/getProductInfos") @ResponseBody public String getProductInfos(Long productId) { GetProductInfoCommand getProductInfoCommand = new GetProductInfoCommand(productId); ProductInfo productInfo = getProductInfoCommand.execute(); System.out.println(productInfo); System.out.println(getProductInfoCommand.isResponseFromCache()); return "success"; }