spring 是否可以将缓存名称设置为动态?如果可以,如何设置?

rqdpfwrv  于 2022-11-21  发布在  Spring
关注(0)|答案(1)|浏览(268)

`

@RestController
public class TestController {
    
    @Cacheable(cacheNames = "testCache", key = "#name")
    @GetMapping("/test/{name}")
    public String test(@PathVariable String name) {
        System.out.println("########Test Called ###### " + name);
        return HttpStatus.OK.toString();
       }

}

这里cacheNames是Stirng数组,如果name不存在于cacheNames中,那么它应该先添加,然后再执行其余的操作。
我使用的是spring Boot 缓存,必须根据请求参数添加cacheNames。

qoefvg9y

qoefvg9y1#

如果您想要更大的灵活性,可以这样做:

import org.springframework.cache.CacheManager;
import org.springframework.cache.Cache;
// other imports

@RestController
public class TestController {

    private final Cache myCache;

    public TestController(@Autowired CacheManager cacheManager) {
       this.myCache = cacheManager.getCache("myCache");
    }
    
    @GetMapping("/test/{name}")
    public String test(@PathVariable String name) {
        return myCache.get(name, () -> {
          // your expensive operation that needs to be cached.
          System.out.println("########Test Called ###### " + name);
          return HttpStatus.OK.toString();
        });
    }

}

在这种情况下,缓存名称将不是动态的,但该高速缓存键将是动态的。

相关问题