Search code examples
javacachingwildflycdijava-ee-7

WildFly 11/Java EE 7/JSR 107: caching - what's the best way to cache information and let it expire automatically?


What's the recommended way to store pieces of data and let it expire automatically from within a Java EE/WebApp container? I could use the session persistence mechanism, but my http sessions are usually A LOT longer than I want those pieces of information to be retained.

Is there something provided by Java EE 7 or by CDI? Some preliminary variant of the JCache spec JSR 107? Any other good solution?


Solution

  • I'm not sure it is the "best" way but I've been using the Google Guava cache in Wildfly (8 through 10 but hopefully still applicable). For me I'm caching Oauth tokens because of a very slow auth server. My code looks something like:

    private static LoadingCache<String, MyPrincipal> tokenCacheMap;
    
    @PostConstruct
    private void postConstruct() {
        tokenCacheMap = CacheBuilder.newBuilder()
                .expireAfterAccess(15, TimeUnit.MINUTES)
                .build(
                        new CacheLoader<String, MyUserPrincipal>() {
                            @Override
                            public MyUserPrincipal load(String token) {
                                MyUserPrincipal myUserPrincipal = getUserFromToken(token);
    
                                if( myUserPrincipal != null ) {
                                    myUserPrincipal.setToken(token);
                                    return myUserPrincipal;
                                }
    
                                throw new SecurityException("token is not valid");
                            }
                        }
                );
    }
    
    //
    // later in the code...
    //
    MyUserPrincipal myUserPrincipal = tokenCacheMap.get(token);
    

    Basically what this does is set up a cache where the tokens live for 15 minutes. If needed, the load() method is called to, in this case, get an auth token and user. The cache is lazily filled as needed - the first call will have the overhead of getting the token but after that it's all in memory.

    There are other options to, for example, evict old information based on the number of items in the cache. The documentation is very good and should get you going.

    The downside is that this is not a JEE standard but it has worked for me in the past.