5.Hystrix实现Request Cache减压

2020-06-06  本文已影响0人  溅十三
image.png

实现步骤如下

1.在下面创建RequestCacheService类

要点:
@CacheResult 把Friend 对象缓存起来
@CacheKey 唯一标识,把name当做获取Friend的唯一的key
@HystrixCommand 针对一个特定的服务要进行降级

RequestCacheService:

package com.imooc.springcloud.hystrix;

import com.imooc.springcloud.Friend;
import com.imooc.springcloud.MyService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by 半仙.
 */
@Slf4j
@Service
public class RequestCacheService {

    @Autowired
    private MyService service;

    @CacheResult
    @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;
    }

}

2.调用RequestCacheService类中的requestCache方法

save的时候一直点击保存,RequestCacheService上下文可以让方法只被调用一次

package com.imooc.springcloud;

import com.imooc.springcloud.hystrix.RequestCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {

    @Autowired
    private MyService myService;
    @Autowired
    private RequestCacheService requestCacheService;

    @GetMapping("/fallback")
    public String fallback(){
        return myService.error();
    }

    @GetMapping("/timeout")
    public String timeout(Integer timeout){
        return myService.retry(timeout);
    }

    @GetMapping("/cache")
    public Friend cache(String  name){
        Friend friend = requestCacheService.requestCache(name);

        return friend;
    }

}

3.配置文件

image.png

4.测试缓存

image.png
image.png

121?
1个上线文
2个注解@CacheResult @CacheKey
1个@HystrixCommand

上一篇 下一篇

猜你喜欢

热点阅读