Search code examples
javaspring-bootspring-securityehcache

Using a cache key based on user login


I have a SpringBoot + Security + EhCache project. There is a wrapper class (LoggedUserInfo) around SecurityContextHolder and a service to deal with User information:

public LoggedUserInfo {
    public static String getLogin() {
        return SecurityContextHolder.getContext().getAuthentication().getName();
    }
}

public UserService {
    //(...)

    public User getLoggedUser() {
        var login = LoggedUserInfo.getLogin();

        return getByLogin(login);
    }

    @Cacheable(value = "userByLogin", key = "#login")
    public User getByLogin(String login) {
        return userRepository.findByLogin(login);
    }
}

My cache is configured as:

<cache alias="userByLogin">
        <key-type>java.lang.String</key-type>
        <value-type>com.myproject.User</value-type>
        <expiry>
            <ttl unit="hours">24</ttl>
        </expiry>
        <resources>
            <heap unit="MB">1</heap>
        </resources>
</cache>

The cache for UserService::getByLogin is working fine. I would like to do the same to UserService::getLoggedUser but based on the current user login.

After reading cache and spel docs I figured out It would be possible with something like this:

@Cacheable(value = "userByLogin", key = "T(com.myproject.LoggedUserInfo).getLogin()")
public User getLoggedUser() {\\...}

or:

@Cacheable(value = "userByLogin", key = "T(com.myproject.LoggedUserInfo).login")
public User getLoggedUser() {\\...}

But if I try to do that there is a warning every time getLoggedUser is called and the cache is never used:

WARN  o.e.i.i.store.heap.OnHeapStore - Max Object Graph Size reached for the object : [B@28c27a2f

What am I missing?


Solution

  • You could try bumping up the max object graph size (default: 1000).

    You can tune it like so:

    <cache alias="userByLogin">
            <key-type>java.lang.String</key-type>
            <value-type>com.myproject.User</value-type>
            <expiry>
                <ttl unit="hours">24</ttl>
            </expiry>
            <resources>
                <heap unit="MB">1</heap>
            </resources>
            <heap-store-settings>
                <max-object-graph-size>10000</max-object-graph-size>
            </heap-store-settings>
    </cache>