Skip to content

Migrate Redis session repositories from DisposableBean to SmartLifecycle #3460

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: 3.3.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2014-2023 the original author or authors.
* Copyright 2014-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -38,6 +38,7 @@
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.SmartLifecycle;
import org.springframework.core.NestedExceptionUtils;
import org.springframework.data.redis.connection.ReactiveSubscription;
import org.springframework.data.redis.core.ReactiveRedisOperations;
Expand Down Expand Up @@ -230,12 +231,13 @@
* {@code "spring:session:sessions:648377f7-c76f-4f45-b847-c0268bb48381:idx"} Redis set.
*
* @author Marcus da Coregio
* @author Ham Seung Hun
* @since 3.3
*/
public class ReactiveRedisIndexedSessionRepository
implements ReactiveSessionRepository<ReactiveRedisIndexedSessionRepository.RedisSession>,
ReactiveFindByIndexNameSessionRepository<ReactiveRedisIndexedSessionRepository.RedisSession>, DisposableBean,
InitializingBean {
InitializingBean, SmartLifecycle {

private static final Log logger = LogFactory.getLog(ReactiveRedisIndexedSessionRepository.class);

Expand All @@ -249,6 +251,28 @@ public class ReactiveRedisIndexedSessionRepository
*/
public static final int DEFAULT_DATABASE = 0;

/**
* The default SmartLifecycle phase.
*
* <p>
* Set to {@code Integer.MAX_VALUE / 2} to position this repository between the Redis
* {@link org.springframework.data.redis.connection.RedisConnectionFactory} (typically
* small, e.g. {@code 0}) and web server / messaging listener containers (very large
* values, e.g. {@code Integer.MAX_VALUE - 1024}, {@code Integer.MAX_VALUE - 100},
* {@code Integer.MAX_VALUE}), preventing shutdown races.
* </p>
*
* <p>
* <b>NOTE</b>: if the ConnectionFactory’s phase is >= this value, raise it via
* {@link #setPhase(int)} to keep “SessionRepository phase > ConnectionFactory phase”.
* </p>
*
* @see org.springframework.context.SmartLifecycle
* @see org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory
* @see org.springframework.data.redis.connection.jedis.JedisConnectionFactory
*/
public static final int DEFAULT_SMART_LIFECYCLE_PHASE = Integer.MAX_VALUE / 2;

private final ReactiveRedisOperations<String, Object> sessionRedisOperations;

private final ReactiveRedisTemplate<String, String> keyEventsOperations;
Expand Down Expand Up @@ -281,6 +305,8 @@ public class ReactiveRedisIndexedSessionRepository

private int database = DEFAULT_DATABASE;

private int phase = DEFAULT_SMART_LIFECYCLE_PHASE;

private ReactiveRedisSessionIndexer indexer;

private SortedSetReactiveRedisSessionExpirationStore expirationStore;
Expand All @@ -289,6 +315,8 @@ public class ReactiveRedisIndexedSessionRepository

private Clock clock = Clock.systemUTC();

private volatile boolean running = false;

/**
* Creates a new instance with the provided {@link ReactiveRedisOperations}.
* @param sessionRedisOperations the {@link ReactiveRedisOperations} to use for
Expand All @@ -308,9 +336,20 @@ public ReactiveRedisIndexedSessionRepository(ReactiveRedisOperations<String, Obj
}

@Override
public void afterPropertiesSet() throws Exception {
public void start() {
if (this.running) {
return;
}

subscribeToRedisEvents();
setupCleanupTask();

this.running = true;
}

@Override
public void afterPropertiesSet() throws Exception {
start();
}

private void setupCleanupTask() {
Expand All @@ -325,19 +364,46 @@ private void setupCleanupTask() {
}

private Flux<Void> cleanUpExpiredSessions() {
return this.expirationStore.retrieveExpiredSessions(this.clock.instant()).flatMap(this::touch);
return this.expirationStore.retrieveExpiredSessions(this.clock.instant())
.filter((ignored) -> isRunning())
.flatMap(this::touch);
}

private Mono<Void> touch(String sessionId) {
return this.sessionRedisOperations.hasKey(getExpiredKey(sessionId)).then();
}

@Override
public void destroy() {
public void stop() {
if (!this.running) {
return;
}

for (Disposable subscription : this.subscriptions) {
subscription.dispose();
}
this.subscriptions.clear();

this.running = false;
}

@Override
public void destroy() {
stop();
}

@Override
public boolean isRunning() {
return this.running;
}

@Override
public int getPhase() {
return this.phase;
}

public void setPhase(int phase) {
this.phase = phase;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2014-2023 the original author or authors.
* Copyright 2014-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -32,6 +32,7 @@
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.SmartLifecycle;
import org.springframework.core.NestedExceptionUtils;
import org.springframework.dao.NonTransientDataAccessException;
import org.springframework.data.redis.connection.Message;
Expand Down Expand Up @@ -256,11 +257,12 @@
*
* @author Rob Winch
* @author Vedran Pavic
* @author Ham Seung Hun
* @since 2.2.0
*/
public class RedisIndexedSessionRepository
implements FindByIndexNameSessionRepository<RedisIndexedSessionRepository.RedisSession>, MessageListener,
InitializingBean, DisposableBean {
InitializingBean, DisposableBean, SmartLifecycle {

private static final Log logger = LogFactory.getLog(RedisIndexedSessionRepository.class);

Expand All @@ -281,8 +283,32 @@ public class RedisIndexedSessionRepository
*/
public static final String DEFAULT_NAMESPACE = "spring:session";

/**
* The default SmartLifecycle phase.
*
* <p>
* Set to {@code Integer.MAX_VALUE / 2} to position this repository between the Redis
* {@link org.springframework.data.redis.connection.RedisConnectionFactory} (typically
* small, e.g. {@code 0}) and web server / messaging listener containers (very large
* values, e.g. {@code Integer.MAX_VALUE - 1024}, {@code Integer.MAX_VALUE - 100},
* {@code Integer.MAX_VALUE}), preventing shutdown races.
* </p>
*
* <p>
* <b>NOTE</b>: if the ConnectionFactory’s phase is >= this value, raise it via
* {@link #setPhase(int)} to keep “SessionRepository phase > ConnectionFactory phase”.
* </p>
*
* @see org.springframework.context.SmartLifecycle
* @see org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory
* @see org.springframework.data.redis.connection.jedis.JedisConnectionFactory
*/
public static final int DEFAULT_SMART_LIFECYCLE_PHASE = Integer.MAX_VALUE / 2;

private int database = DEFAULT_DATABASE;

private int phase = DEFAULT_SMART_LIFECYCLE_PHASE;

/**
* The namespace for every key used by Spring Session in Redis.
*/
Expand Down Expand Up @@ -329,6 +355,8 @@ public class RedisIndexedSessionRepository

private BiFunction<String, Map<String, Object>, MapSession> redisSessionMapper = new RedisSessionMapper();

private volatile boolean running = false;

/**
* Creates a new instance. For an example, refer to the class level javadoc.
* @param sessionRedisOperations the {@link RedisOperations} to use for managing the
Expand All @@ -343,12 +371,23 @@ public RedisIndexedSessionRepository(RedisOperations<String, Object> sessionRedi
}

@Override
public void afterPropertiesSet() {
public void start() {
if (this.running) {
return;
}

if (!Scheduled.CRON_DISABLED.equals(this.cleanupCron)) {
this.taskScheduler = createTaskScheduler();
this.taskScheduler.initialize();
this.taskScheduler.schedule(this::cleanUpExpiredSessions, new CronTrigger(this.cleanupCron));
}

this.running = true;
}

@Override
public void afterPropertiesSet() {
start();
}

private static ThreadPoolTaskScheduler createTaskScheduler() {
Expand All @@ -358,10 +397,35 @@ private static ThreadPoolTaskScheduler createTaskScheduler() {
}

@Override
public void destroy() {
public void stop() {
if (!this.running) {
return;
}

if (this.taskScheduler != null) {
this.taskScheduler.destroy();
}

this.running = false;
}

@Override
public void destroy() {
stop();
}

@Override
public boolean isRunning() {
return this.running;
}

@Override
public int getPhase() {
return this.phase;
}

public void setPhase(int phase) {
this.phase = phase;
}

/**
Expand Down Expand Up @@ -486,6 +550,10 @@ public void save(RedisSession session) {
}

public void cleanUpExpiredSessions() {
if (!isRunning()) {
return;
}

this.expirationPolicy.cleanExpiredSessions();
}

Expand Down
Loading
Loading