全部代码
package com.gitee.munan56.cloud.hystrixconsumer; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import com.netflix.ribbon.proxy.annotation.Hystrix; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.List; /** * @author munan * @version 1.0 * @date 2020/1/13 10:41 */ @Service public class AService { @Autowired private RestTemplate restTemplate; public String doAService(){ return "A Service is run"; } // @Hystrix(fallbackHandler = ) @HystrixCommand(fallbackMethod = "error") public String doBServiceOne(){ System.out.println("begin do provider service"); return restTemplate.getForEntity("http://service-provider:8081/api/v1/provider/do",String.class).getBody(); } /** * CacheResult 请求缓存(针对request的缓存),官方建议在serverlet filter 中初始化HystrixRequestContext * 在同一用户请求的上下文中缓存在统一请求的上下文环境中有效。 * @param id * @return */ @CacheResult(cacheKeyMethod = "getKey") @HystrixCommand(fallbackMethod = "error") public String doBServiceTwo(String id){ System.out.println("begin do provider service"); return restTemplate.getForEntity("http://service-provider:8081/api/v1/provider/do",String.class).getBody(); } /** * 建议: 服务提供方有较高的延迟。可以考虑使用请求合并 * HystrixCollapser 合并请求的时候会创建一个请求处理器。如果每次合并的请求量不大,只有很少的请求还要合并,会造成合并时间窗 * 并发量增大,时间窗的创建和消耗增大。所以只有在时间窗内有很大的并发量,推荐请求合并。 * * batchMethod 请求合并后的替换方法com.gitee.munan56.cloud.hystrixconsumer.AService#findALl(java.util.List) 注意客户端要有这个方法 *HystrixProperty 一个属性合并时间窗100s 这个时间结束后会发起请求,也就是指这个时间是合并处理的时间 * @param id * @return */ @HystrixCollapser(batchMethod = "findALl",collapserProperties = @HystrixProperty(name = "timerDelayInMilliseconds",value = "100")) public String doBFindOne(String id){ System.out.println("begin do provider service"); return restTemplate.getForEntity("http://service-provider:8081/api/v1/provider/do",String.class).getBody(); } @HystrixCommand() public String findALl(List<String> ids){ System.out.println("begin do provider service"); return restTemplate.getForEntity("http://service-provider:8081/api/v1/provider/do",String.class).getBody(); } /** * 服务降级 * 指定调用服务出错的回调方法 * @return */ public String error(Throwable e){ return "do provider error this is default result" + "the error is " + e.getMessage(); } /** * 服务降级 * 指定调用服务出错的回调方法 * @return */ public String error(String id ,Throwable e){ return "do provider error this is default result" + "the error is " + e.getMessage(); } public String getKey(String id){ return id; } }