栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【spring cloud】hystrix请求缓存功能,提高服务响应速度

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【spring cloud】hystrix请求缓存功能,提高服务响应速度

hystrix的降级和超时都已经写过了,接下来记录下hystrix的请求缓存功能。对于同一个ip的对同一个方法的请求,hystrix有请求缓存功能可以让服务更快的返回结果。

示例如下,首先调用controller中的方法,该方法调用缓存方法。从上下文中获得结果,记得用lombok的@Cleanup关闭上下文。

@RestController
public class Controller {

    @Autowired
    private MyService myService;

    @Autowired
    private RequestCacheService requestCacheService;
    
    @GetMapping("/cache")
    public Friend cache(String name){
        // @Cleanup默认会调用context的close方法,也可以通过指定值来指定
        @Cleanup HystrixRequestContext context = HystrixRequestContext.initializeContext();
        Friend friend = requestCacheService.requestCache(name);
        name += "!";
        friend = requestCacheService.requestCache(name);
        return friend;
    }
}

@CacheResult可以打开请求缓存功能,当第二次访问时,对参数name值相同的请求,直接返回上下文中的结果,提高服务响应速度。

@Slf4j
@Service
public class RequestCacheService {

    @Autowired
    private MyService service;

    @CacheResult
    // commandKey的值对应application.yml里的服务名字"cacheKey",简化方法签名
    @HystrixCommand(commandKey = "cacheKey")
    public Friend requestCache(@CacheKey String name){
        log.info("request cache " + name);
        Friend friend = new Friend();
        friend.setName(name);
        friend = service.sayHiPost(friend);
        log.info("after requesting cache " + name);
        return friend;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/336868.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号