繁体   English   中英

Java Spring 引导如何设置 Redis Z594C103F5903E04E0C31DAZ8 上多个查询字符串参数的缓存键

[英]Java Spring Boot how to set Redis cache key for multiple query string parameters on controller

使用以下 Controller 方法:

    @GetMapping("/books")
    public ResponseEntity<List<Book>> getBooksByTitleOrAuthor(
        @RequestParam(required = false) String title,
        @RequestParam(required = false) String author) {

        if ((title== null || title.isEmpty()) && (author == null || author.isEmpty()))
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

        if (author != null) {
            Logger.info("GET /books?author=" + author);
            return bookService.getByAuthor(author)
        }

        Logger.info("GET /books?title=" + title);
        return bookService.getByTitle(title));
    }

我可以调用端点:

/books?title=SomeBookTitle

或者

/books?author=SomeAuthor

如何使用@Cacheable在此处设置带有titleauthor的 Redis 密钥?

您可以尝试使用缓存的 SpEL 元数据,例如正在调用的方法的名称,如下所示:

@Cacheable(value = "books", key = "{ #root.methodName, #title, #author }")
@Cacheable (
    cacheManager = "books", 
    value= "books", 
    key = "'book'"
)


cacheManager:处理缓存请求的bean的名称

@Bean(name = "books")
public CacheManager booksCacheManager(){
    // template bean is actual redis handler
    return RedisConfigUtils.genericCacheManager(TimeUnit.MILLISECONDS.toSeconds(expiry), templateBean);
}


@Bean(name = "templateBean")
    RedisTemplate couponRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        Jackson2JsonRedisSerializer type = new Jackson2JsonRedisSerializer<ArrayList>(ArrayList.class){
            @Override
            protected JavaType getJavaType(Class<?> clazz){
                if (List.class.isAssignableFrom(clazz)) {
                    setObjectMapper(mapper);
                    return mapper.getTypeFactory().constructCollectionType(ArrayList.class, Test.class);
                } else {
                    return super.getJavaType(clazz);
                }
            }
        };
        return RedisConfigUtils.genericRedisTemplate(redisConnectionFactory, type);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM