Skip to content

gotson/spring-session-caffeine

Repository files navigation

Spring Session Caffeine GitHub Workflow Status (branch)

Provides a SessionRepository implementation backed by a Caffeine cache.

Features

  • respond to entries being added, evicted, and removed from the registry causes these events to trigger publishing of SessionCreatedEvent, SessionExpiredEvent, and SessionDeletedEvent events (respectively) through the ApplicationEventPublisher
  • automatically purge expired sessions
  • configure underlying cache by setting a specific Scheduler or Executor
  • implements FindByIndexNameSessionRepository, which can be used with SpringSessionBackedSessionRegistry if you need to support Spring Security concurrent session control

When to use it?

Spring Session Caffeine is a good candidate when you need more capabilities than the default MapSessionRepository, like events firing or automatic purging of expired sessions, or when you need a FindByIndexNameSessionRepository.

If you need those extra capabilities, you may consider Spring Session Caffeine instead of other Spring Session Modules in the following cases:

  • Single instance. Spring Session Caffeine will be more lightweight than Spring Session Redis or Spring Session Hazelcast, as those solutions depend on external systems, while Caffeine is a pure Java implementation. Caffeine is not a distributed cache, so it will only work with a single instance.
  • No JDBC database. While Spring Session JDBC can be a good candidate for a single instance service, you may not be using a database already.
  • SQLite. When using Spring Session JDBC with SQLite, the high number of writes can impact the performances of your application when sharing the SQLite database between sessions and the rest of your application. In that case Spring Session Caffeine can be a good alternative.

Installation

Maven Central javadoc

Gradle

implementation "com.github.gotson:spring-session-caffeine:{version}"

Gradle (Kotlin DSL)

implementation("com.github.gotson:spring-session-caffeine:{version}")

Maven

<dependency>
    <groupId>com.github.gotson</groupId>
    <artifactId>spring-session-caffeine</artifactId>
    <version>{version}</version>
</dependency>

Usage

Simple

@EnableCaffeineHttpSession(maxInactiveIntervalInSeconds = 3600)
public class Config {
}

Advanced

@EnableCaffeineHttpSession
public class Config {
    @Bean
    SessionRepositoryCustomizer<CaffeineIndexedSessionRepository> customize() {
        return (sessionRepository -> {
            sessionRepository.setDefaultMaxInactiveInterval(Duration.ofDays(7).getSeconds());
            sessionRepository.setExecutor(Executors.newFixedThreadPool(1));
            sessionRepository.setScheduler(Scheduler.forScheduledExecutorService(Executors.newScheduledThreadPool(1)));
        }
        );
    }
}