Sa-Token 多账号体系下Redis持久化问题

在使用Sa-Token框架实现多账号体系时,当后端服务重启后,系统报错"未能获取对应StpLogic,type=XXX"。这种情况通常发生在配置了Redis持久化存储的场景下,特别是在多账号体系中使用自定义的StpLogic时。

这个问题的本质在于Sa-Token的多账号体系实现机制与Redis持久化存储之间的协同工作方式。当开发者定义了一个新的StpLogic实例(如ADMIN = new StpLogic("ADMIN"))时,这个定义仅存在于JVM内存中。服务重启后,虽然Redis中存储的Token数据仍然存在,但JVM中的StpLogic实例定义已经丢失。

原本实现代码:

java 复制代码
package com.example.auth.service;

import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;

/**
 * StpLogic 门面类,管理项目中所有的 StpLogic 账号体系
 */
public class StpKit {

    public static final String USER_TYPE = "client";
    public static final String xxx_TYPE = "xxx";


    /**
     * 默认原生会话对象
     */
    public static final StpLogic DEFAULT = StpUtil.stpLogic;


    /**
     * User 会话对象,管理 client 类型所有账号的登录、权限认证
     */
    public static final StpLogic USER = new StpLogic(USER_TYPE);

    /**
     * xxx 会话对象
     */
    public static final StpLogic xxx = new StpLogic(xxx_TYPE);


}

解决方案

在StpLogic门面类上加入@Component注解即可。

java 复制代码
package com.example.auth.service;

import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.stereotype.Component;

/**
 * StpLogic 门面类,管理项目中所有的 StpLogic 账号体系
 */
@Component
public class StpKit {

    public static final String USER_TYPE = "client";
    public static final String xxx_TYPE = "xxx";


    /**
     * 默认原生会话对象
     */
    public static final StpLogic DEFAULT = StpUtil.stpLogic;


    /**
     * User 会话对象,管理 client 类型所有账号的登录、权限认证
     */
    public static final StpLogic USER = new StpLogic(USER_TYPE);

    /**
     * xxx 会话对象
     */
    public static final StpLogic xxx = new StpLogic(xxx_TYPE);


}
相关推荐
IT毕设实战小研21 分钟前
基于Spring Boot校园二手交易平台系统设计与实现 二手交易系统 交易平台小程序
java·数据库·vue.js·spring boot·后端·小程序·课程设计
泉城老铁32 分钟前
Spring Boot 中根据 Word 模板导出包含表格、图表等复杂格式的文档
java·后端
极客BIM工作室38 分钟前
谈谈《More Effective C++》的条款30:代理类
java·开发语言·c++
孤狼程序员38 分钟前
【Spring Cloud 微服务】1.Hystrix断路器
java·spring boot·spring·微服务
RainbowSea1 小时前
伙伴匹配系统(移动端 H5 网站(APP 风格)基于Spring Boot 后端 + Vue3 - 04
java·spring boot·后端
用户84913717547161 小时前
JustAuth实战系列(第11期):测试驱动开发 - 质量保证与重构实践
java·设计模式·单元测试
RainbowSea1 小时前
伙伴匹配系统(移动端 H5 网站(APP 风格)基于Spring Boot 后端 + Vue3 - 03
java·spring boot·后端
心月狐的流火号1 小时前
Java SPI 机制与 Spring Boot 自动装配原理
java·spring boot
AAA修煤气灶刘哥2 小时前
面试必问:聊一聊Spring中bean的循环依赖问题 ?——从原理到避坑
java·后端·程序员
星火飞码iFlyCode2 小时前
真实案例 | 如何用iFlyCode开发Webpack插件?
java·python·编辑器