对于最新的稳定版本,请使用 Spring Session 3.5.2spring-doc.cadn.net.cn

Redis 配置

现在您已经配置了应用程序,您可能想要开始自定义内容:spring-doc.cadn.net.cn

使用 JSON 序列化会话

默认情况下,Spring Session 使用 Java 序列化来序列化会话属性。 有时这可能会有问题,尤其是当您有多个应用程序使用相同的 Redis 实例但具有同一类的不同版本时。 您可以提供一个RedisSerializerbean 来自定义会话序列化到 Redis 的方式。 Spring Data Redis 提供了GenericJackson2JsonRedisSerializer使用 Jackson 的ObjectMapper.spring-doc.cadn.net.cn

配置 RedisSerializer
@Configuration
public class SessionConfig implements BeanClassLoaderAware {

	private ClassLoader loader;

	@Bean
	public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
		return new GenericJackson2JsonRedisSerializer(objectMapper());
	}

	/**
	 * Customized {@link ObjectMapper} to add mix-in for class that doesn't have default
	 * constructors
	 * @return the {@link ObjectMapper} to use
	 */
	private ObjectMapper objectMapper() {
		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModules(SecurityJackson2Modules.getModules(this.loader));
		return mapper;
	}

	/*
	 * @see
	 * org.springframework.beans.factory.BeanClassLoaderAware#setBeanClassLoader(java.lang
	 * .ClassLoader)
	 */
	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		this.loader = classLoader;
	}

}

上面的代码片段使用 Spring Security,因此我们正在创建一个自定义ObjectMapper使用 Spring Security 的 Jackson 模块。 如果您不需要 Spring Security Jackson 模块,则可以注入应用程序的ObjectMapperbean 并按如下方式使用它:spring-doc.cadn.net.cn

@Bean
public RedisSerializer<Object> springSessionDefaultRedisSerializer(ObjectMapper objectMapper) {
    return new GenericJackson2JsonRedisSerializer(objectMapper);
}

指定不同的命名空间

使用同一个 Redis 实例的多个应用程序并不少见。 因此,Spring Session 使用namespace(默认为spring:session) 以在需要时将会话数据分开。spring-doc.cadn.net.cn

使用 Spring Boot 属性

您可以通过设置spring.session.redis.namespace财产。spring-doc.cadn.net.cn

应用程序属性
spring.session.redis.namespace=spring:session:myapplication
application.yml
spring:
  session:
    redis:
      namespace: "spring:session:myapplication"

使用注释的属性

您可以指定namespace通过将redisNamespace属性中的@EnableRedisHttpSession,@EnableRedisIndexedHttpSession@EnableRedisWebSession附注:spring-doc.cadn.net.cn

@EnableRedisHttpSession
@Configuration
@EnableRedisHttpSession(redisNamespace = "spring:session:myapplication")
public class SessionConfig {
    // ...
}
@EnableRedisIndexedHttpSession
@Configuration
@EnableRedisIndexedHttpSession(redisNamespace = "spring:session:myapplication")
public class SessionConfig {
    // ...
}
@EnableRedisWebSession
@Configuration
@EnableRedisWebSession(redisNamespace = "spring:session:myapplication")
public class SessionConfig {
    // ...
}

在两者之间进行选择RedisSessionRepositoryRedisIndexedSessionRepository

使用 Spring Session Redis 时,您可能必须在RedisSessionRepositoryRedisIndexedSessionRepository. 两者都是SessionRepository接口,将会话数据存储在 Redis 中。 但是,它们在处理会话索引和查询的方式上有所不同。spring-doc.cadn.net.cn

  • RedisSessionRepository:RedisSessionRepository是一个基本实现,它将会话数据存储在 Redis 中,无需任何额外的索引。 它使用简单的键值结构来存储会话属性。 每个会话都分配有一个唯一的会话 ID,会话数据存储在与该 ID 关联的 Redis 密钥下。 当需要检索会话时,存储库会使用会话 ID 查询 Redis 以获取关联的会话数据。 由于没有索引,因此根据会话 ID 以外的属性或条件查询会话可能效率低下。spring-doc.cadn.net.cn

  • RedisIndexedSessionRepository:RedisIndexedSessionRepository是一个扩展实现,为存储在 Redis 中的会话提供索引功能。 它在 Redis 中引入了额外的数据结构,以根据属性或条件有效地查询会话。 除了RedisSessionRepository,它维护额外的索引以实现快速查找。 例如,它可以根据用户 ID 或上次访问时间等会话属性创建索引。 这些索引允许根据特定标准高效查询会话,从而增强性能并启用高级会话管理功能。 除此之外,RedisIndexedSessionRepository还支持会话过期和删除。spring-doc.cadn.net.cn

使用时RedisIndexedSessionRepository使用 Redis Cluster,您必须知道它只订阅来自集群中一个随机 Redis 节点的事件,如果事件发生在不同的节点中,这可能会导致某些会话索引无法被清理。

配置RedisSessionRepository

使用 Spring Boot 属性

如果您使用的是 Spring Boot,则RedisSessionRepository是默认实现。 但是,如果您想明确说明这一点,可以在应用程序中设置以下属性:spring-doc.cadn.net.cn

应用程序属性
spring.session.redis.repository-type=default
application.yml
spring:
  session:
    redis:
      repository-type: default

使用注释

您可以配置RedisSessionRepository通过使用@EnableRedisHttpSession注解:spring-doc.cadn.net.cn

@Configuration
@EnableRedisHttpSession
public class SessionConfig {
    // ...
}

配置RedisIndexedSessionRepository

使用 Spring Boot 属性

您可以配置RedisIndexedSessionRepository通过在应用程序中设置以下属性:spring-doc.cadn.net.cn

应用程序属性
spring.session.redis.repository-type=indexed
application.yml
spring:
  session:
    redis:
      repository-type: indexed

使用注释

您可以配置RedisIndexedSessionRepository通过使用@EnableRedisIndexedHttpSession注解:spring-doc.cadn.net.cn

@Configuration
@EnableRedisIndexedHttpSession
public class SessionConfig {
    // ...
}

侦听会话事件

通常,对会话事件做出反应很有价值,例如,您可能希望根据会话生命周期执行某种处理。 为了能够做到这一点,您必须使用索引存储库。 如果您不知道索引存储库和默认存储库之间的区别,可以转到此部分spring-doc.cadn.net.cn

配置索引存储库后,您现在可以开始监听SessionCreatedEvent,SessionDeletedEvent,SessionDestroyedEventSessionExpiredEvent事件。 有几种方法可以在 Spring 中监听应用程序事件,我们将使用@EventListener注解。spring-doc.cadn.net.cn

@Component
public class SessionEventListener {

    @EventListener
    public void processSessionCreatedEvent(SessionCreatedEvent event) {
        // do the necessary work
    }

    @EventListener
    public void processSessionDeletedEvent(SessionDeletedEvent event) {
        // do the necessary work
    }

    @EventListener
    public void processSessionDestroyedEvent(SessionDestroyedEvent event) {
        // do the necessary work
    }

    @EventListener
    public void processSessionExpiredEvent(SessionExpiredEvent event) {
        // do the necessary work
    }

}

查找特定用户的所有会话

通过检索特定用户的所有会话,您可以跨设备或浏览器跟踪用户的活动会话。 例如,您可以将此信息用于会话管理目的,例如允许用户使特定会话失效或注销,或者根据用户的会话活动执行作。spring-doc.cadn.net.cn

为此,首先您必须使用索引存储库,然后您可以注入FindByIndexNameSessionRepository接口,如下所示:spring-doc.cadn.net.cn

@Autowired
public FindByIndexNameSessionRepository<? extends Session> sessions;

public Collection<? extends Session> getSessions(Principal principal) {
    Collection<? extends Session> usersSessions = this.sessions.findByPrincipalName(principal.getName()).values();
    return usersSessions;
}

public void removeSession(Principal principal, String sessionIdToDelete) {
    Set<String> usersSessionIds = this.sessions.findByPrincipalName(principal.getName()).keySet();
    if (usersSessionIds.contains(sessionIdToDelete)) {
        this.sessions.deleteById(sessionIdToDelete);
    }
}

在上面的示例中,您可以使用getSessions方法来查找特定用户的所有会话,以及removeSession删除用户特定会话的方法。spring-doc.cadn.net.cn