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

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

【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;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4667985.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-06
下一篇2022-11-06

发表评论

登录后才能评论

评论列表(0条)

    保存