问题描述
我正在尝试使用hazelcast实现缓存.
I am trying to implement caching using hazelcast.
这是我的代码.我的问题是,当执行findAllGames()时,我会将所有游戏都缓存在"gamesCache"中,而当执行findGameByTypes()时,我希望它查询"gamesCache",而不是访问数据库并返回结果.
Here's my code. My question is that, when findAllGames() is executed i am caching all the games in "gamesCache" and when findGameByTypes() is executed, I want it to query "gamesCache" instead of hitting the database and return the result.
@Cacheable(cacheNames = "gamesCache", key = "#root.methodName")
public List<Game> findAllGames() {
List<Game> games = gamesDao.getAllGames(); // dao call
//some database call
}
public List<Game> findGameByTypes(GameType gameType) {
List<Game> games = gamesDao.getGamesByType(gameType); // dao call
//some logic
}
public class Game implements Serializable {
private long gameId;
private String gameName;
private GameType gameType;
}
public class GameType implements Serializable {
private long gameId;
private String gameGenre;
private Boolean status;
}
findAllGames()总是比findGamesByTypes()优先.
findAllGames() is always hit first than findGamesByTypes().
现在,将使用"findAllGames"作为键并使用游戏列表作为值来生成缓存的地图.现在,有什么方法可以使用GameType属性作为条件来查询地图.
Now the cached map is generated with "findAllGames" as key and List of games as value. Now Is there any way to query the map using the GameType attributes as criteria.
有什么办法可以实现呢?我也愿意接受其他建议.
Is there any way to implement this? I am open to other suggestions as well.
推荐答案
如@wildnez所建议,您可以使用PRedicate和/或SQLQuery.另外,由于您使用的是Spring,因此您还可以受益于Spring-Data-Hazelcast项目,该项目会自动从方法名称为您生成查询: https://github.com/hazelcast/spring-data-hazelcast
As suggested by @wildnez, you can use PRedicate and/or SQLQuery. Also, since you're using Spring, you can also benefit from Spring-Data-Hazelcast project which automatically generates queries for you from method name: https://github.com/hazelcast/spring-data-hazelcast
但是您需要更改缓存方式.使用键 findAllGames
将所有游戏存储在一个集合中,而不是在缓存中仅存储一个条目,而应将所有条目分别存储在缓存中 gameId
作为键& Game
作为值.这样,您可以使用任何一种方法查询值.
But you need to change your way of caching. Instead of having only one entry in the cache, with key findAllGames
and storing all games in a collection, you should store all entries individually in the cache, gameId
as key & Game
as value. This way you can query values using either of the methods.
这篇关于是否可以查询Hazelcast缓存?如果是,该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!