Search code examples
javaspringcachinghazelcasthazelcast-imap

Is it possible to query Hazelcast Cache? If yes, How to do it?


I am trying to implement caching using hazelcast.

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() is always hit first than findGamesByTypes().

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.


Solution

  • 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

    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.