diff --git a/ruoyi-common/ruoyi-common-tenant/src/main/java/org/dromara/common/tenant/helper/TenantHelper.java b/ruoyi-common/ruoyi-common-tenant/src/main/java/org/dromara/common/tenant/helper/TenantHelper.java index 8d435a367..2ef1a220e 100644 --- a/ruoyi-common/ruoyi-common-tenant/src/main/java/org/dromara/common/tenant/helper/TenantHelper.java +++ b/ruoyi-common/ruoyi-common-tenant/src/main/java/org/dromara/common/tenant/helper/TenantHelper.java @@ -1,7 +1,7 @@ package org.dromara.common.tenant.helper; import cn.dev33.satoken.context.SaHolder; -import cn.dev33.satoken.spring.SpringMVCUtil; +import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.convert.Convert; import com.alibaba.ttl.TransmittableThreadLocal; import com.baomidou.mybatisplus.core.plugins.IgnoreStrategy; @@ -82,10 +82,13 @@ public class TenantHelper { /** * 设置动态租户(一直有效 需要手动清理) *

- * 如果为非web环境 那么只在当前线程内生效 + * 如果为未登录状态下 那么只在当前线程内生效 */ public static void setDynamic(String tenantId) { - if (!SpringMVCUtil.isWeb()) { + if (!isEnable()) { + return; + } + if (!isLogin()) { TEMP_DYNAMIC_TENANT.set(tenantId); return; } @@ -97,10 +100,13 @@ public class TenantHelper { /** * 获取动态租户(一直有效 需要手动清理) *

- * 如果为非web环境 那么只在当前线程内生效 + * 如果为未登录状态下 那么只在当前线程内生效 */ public static String getDynamic() { - if (!SpringMVCUtil.isWeb()) { + if (!isEnable()) { + return null; + } + if (!isLogin()) { return TEMP_DYNAMIC_TENANT.get(); } String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId(); @@ -117,7 +123,10 @@ public class TenantHelper { * 清除动态租户 */ public static void clearDynamic() { - if (!SpringMVCUtil.isWeb()) { + if (!isEnable()) { + return; + } + if (!isLogin()) { TEMP_DYNAMIC_TENANT.remove(); return; } @@ -126,6 +135,34 @@ public class TenantHelper { SaHolder.getStorage().delete(cacheKey); } + /** + * 在动态租户中执行 + * + * @param handle 处理执行方法 + */ + public static void dynamic(String tenantId, Runnable handle) { + setDynamic(tenantId); + try { + handle.run(); + } finally { + clearDynamic(); + } + } + + /** + * 在动态租户中执行 + * + * @param handle 处理执行方法 + */ + public static T dynamic(String tenantId, Supplier handle) { + setDynamic(tenantId); + try { + return handle.get(); + } finally { + clearDynamic(); + } + } + /** * 获取当前租户id(动态租户优先) */ @@ -137,4 +174,13 @@ public class TenantHelper { return tenantId; } + private static boolean isLogin() { + try { + StpUtil.checkLogin(); + return true; + } catch (Exception e) { + return false; + } + } + }