具有分页的Spring @Cacheable方法 [英] Spring @Cacheable method with pagination

查看:582
本文介绍了具有分页的Spring @Cacheable方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用带有多个参数和分页功能的@Cacheable时遇到了麻烦。

I'm having trouble with @Cacheable using with multi parameters and pagination.

@Cacheable(value = "books", key = "#p0")
public List<Book> findBooks(Long loggedUserId, String q, Integer firstResult, Integer maxResults) {

    ...

    return result;

}

问题是我第一次调用该方法时,成功缓存了内容,结果就像我期望的那样。但是当我第二次打电话时,返回的结果等于第一次。如果禁用缓存或删除键,结果将有所不同。

The problem is when I call the method by the first time, the content is cached with success and the result is like I expect. But when I call by the second time, the result returned is equals to the first time. If I disable the cache or remove the key the results are different.

必须使用键,因为有时会删除指定用户的缓存。

The use of the key is obligatory because sometimes the cache of a specified user is removed.

谢谢。

推荐答案

我认为您的问题是缺乏对可缓存的注释,您正在使用它。所以让我看看我是否可以帮忙

I think your issue is a lack of understanding of the Cacheable annotation, and you you are using it. So let me see if I can help

您的注释为@Cacheable(value = books,key =#p0)

Your annotation is @Cacheable(value = "books", key = "#p0")

这意味着调用此方法时,它将获取第一个参数并在高速缓存中查找它,如果有结果,将返回该参数而不是执行该方法。

This means that when this method is called it will take the first parameter and look it up in the cache and if there is a result, it will be returned instead of executing the method. IT IS ONLY CHECKING THE FIRST PARAMETER.

您的缓存键必须是可以唯一标识结果集的东西。在这种情况下,用户ID在多个结果中是通用的,并且不能唯一地标识页面。

Your cache key needs to be something that uniquely identifies the result set. In this case user id is common across multiple results, and does not uniquely identify a page.

您比我更了解用例,但类似的情况可能是更好:

You know your use case better than I, but something like this would probably be better:

@Cacheable(value = "books", key = {"#p1","#p2","#p3"})
public List<Book> findBooks(Long loggedUserId, String q, Integer firstResult, Integer maxResults) {

...

return result;

}

以上将基于搜索查询和索引进行缓存页面的页面(结果的开始和结束)。由于我不知道您的用例,所以我不知道为什么会有用户ID,但是从我的信息来看,这三个应该可以唯一地标识结果页。

The above will cache based on the search query and the index of the page (start and end of results). Since I don't know your use case I don't know why user id is in there, but from the information I have those three should uniquely identify a result page.

这篇关于具有分页的Spring @Cacheable方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆