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

本文介绍了如何在Hystrix中利用请求缓存功能,提升对同一IP和方法请求的响应速度,通过实例展示了`@CacheResult`和`@HystrixCommand`在Spring Boot中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值