feat(extension/tenant): 新增 TenantIgnoreAspect 切面,完善定时任务等需要忽略租户的场景

This commit is contained in:
2025-07-16 22:44:52 +08:00
parent a0b64b81d5
commit 07e1637363
8 changed files with 125 additions and 11 deletions

View File

@@ -21,6 +21,10 @@ import java.lang.annotation.*;
/** /**
* 租户忽略注解 * 租户忽略注解
* *
* <p>
* 例如:定时任务等需要忽略租户的场景
* </p>
*
* @author Charles7c * @author Charles7c
* @since 2.7.0 * @since 2.7.0
*/ */

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.continew.starter.extension.tenant.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import top.continew.starter.extension.tenant.annotation.TenantIgnore;
import top.continew.starter.extension.tenant.context.TenantContextHolder;
/**
* 租户忽略注解切面
*
* @author Charles7c
* @since 2.13.1
*/
@Aspect
public class TenantIgnoreAspect {
/**
* 忽略租户
*
* @param joinPoint 切点
* @return 返回结果
* @throws Throwable 异常
*/
@Around("@annotation(tenantIgnore)")
public Object around(ProceedingJoinPoint joinPoint, TenantIgnore tenantIgnore) throws Throwable {
boolean oldIgnore = TenantContextHolder.isIgnore();
try {
TenantContextHolder.setIgnore(true);
return joinPoint.proceed();
} finally {
TenantContextHolder.setIgnore(oldIgnore);
}
}
}

View File

@@ -16,6 +16,7 @@
package top.continew.starter.extension.tenant.autoconfigure; package top.continew.starter.extension.tenant.autoconfigure;
import cn.hutool.core.annotation.AnnotationUtil;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered; import org.springframework.core.Ordered;
@@ -44,8 +45,13 @@ public class TenantInterceptor implements HandlerInterceptor, Ordered {
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (handler instanceof HandlerMethod handlerMethod) { if (handler instanceof HandlerMethod handlerMethod) {
TenantIgnore tenantIgnore = handlerMethod.getMethodAnnotation(TenantIgnore.class); TenantIgnore methodAnnotation = handlerMethod.getMethodAnnotation(TenantIgnore.class);
if (tenantIgnore != null) { if (methodAnnotation != null) {
return true;
}
TenantIgnore classAnnotation = AnnotationUtil.getAnnotation(handlerMethod
.getBeanType(), TenantIgnore.class);
if (classAnnotation != null) {
return true; return true;
} }
} }

View File

@@ -32,7 +32,15 @@ import java.util.Optional;
*/ */
public class TenantContextHolder { public class TenantContextHolder {
private static final TransmittableThreadLocal<TenantContext> CONTEXT_HOLDER = new TransmittableThreadLocal<>(); /**
* 租户上下文
*/
private static final TransmittableThreadLocal<TenantContext> CONTEXT = new TransmittableThreadLocal<>();
/**
* 是否忽略租户
*/
private static final TransmittableThreadLocal<Boolean> IGNORE = new TransmittableThreadLocal<>();
private TenantContextHolder() { private TenantContextHolder() {
} }
@@ -43,7 +51,7 @@ public class TenantContextHolder {
* @param context 上下文 * @param context 上下文
*/ */
public static void setContext(TenantContext context) { public static void setContext(TenantContext context) {
CONTEXT_HOLDER.set(context); CONTEXT.set(context);
} }
/** /**
@@ -52,14 +60,33 @@ public class TenantContextHolder {
* @return 上下文 * @return 上下文
*/ */
public static TenantContext getContext() { public static TenantContext getContext() {
return CONTEXT_HOLDER.get(); return CONTEXT.get();
} }
/** /**
* 清除上下文 * 设置是否忽略租户
*
* @param ignore 是否忽略租户
*/
public static void setIgnore(boolean ignore) {
IGNORE.set(ignore);
}
/**
* 是否忽略租户
*
* @return 是否忽略租户
*/
public static boolean isIgnore() {
return Boolean.TRUE.equals(IGNORE.get());
}
/**
* 清除
*/ */
public static void clearContext() { public static void clearContext() {
CONTEXT_HOLDER.remove(); CONTEXT.remove();
IGNORE.remove();
} }
/** /**

View File

@@ -30,6 +30,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.core.ResolvableType; import org.springframework.core.ResolvableType;
import top.continew.starter.core.constant.PropertiesConstants; import top.continew.starter.core.constant.PropertiesConstants;
import top.continew.starter.extension.tenant.aop.TenantIgnoreAspect;
import top.continew.starter.extension.tenant.config.TenantProvider; import top.continew.starter.extension.tenant.config.TenantProvider;
import top.continew.starter.extension.tenant.handler.DefaultTenantHandler; import top.continew.starter.extension.tenant.handler.DefaultTenantHandler;
import top.continew.starter.extension.tenant.TenantDataSourceHandler; import top.continew.starter.extension.tenant.TenantDataSourceHandler;
@@ -59,6 +60,15 @@ public class TenantAutoConfiguration {
this.tenantProperties = tenantProperties; this.tenantProperties = tenantProperties;
} }
/**
* 租户忽略切面
*/
@Bean
@ConditionalOnMissingBean
public TenantIgnoreAspect tenantIgnoreAspect() {
return new TenantIgnoreAspect();
}
/** /**
* 租户行级隔离拦截器 * 租户行级隔离拦截器
*/ */

View File

@@ -67,7 +67,6 @@ public class TenantDataSourceAdvisor extends AbstractPointcutAdvisor implements
AspectJExpressionPointcut cut = new AspectJExpressionPointcut(); AspectJExpressionPointcut cut = new AspectJExpressionPointcut();
cut.setExpression(""" cut.setExpression("""
execution(* *..controller..*(..)) execution(* *..controller..*(..))
&& !@annotation(top.continew.starter.extension.tenant.annotation.TenantIgnore)
"""); """);
return new ComposablePointcut((Pointcut)cut); return new ComposablePointcut((Pointcut)cut);
} }

View File

@@ -39,6 +39,11 @@ public class TenantDataSourceInterceptor implements MethodInterceptor {
@Override @Override
public Object invoke(MethodInvocation invocation) throws Throwable { public Object invoke(MethodInvocation invocation) throws Throwable {
// 忽略租户
if (TenantContextHolder.isIgnore()) {
return true;
}
// 忽略行级隔离
if (TenantIsolationLevel.LINE.equals(TenantContextHolder.getIsolationLevel())) { if (TenantIsolationLevel.LINE.equals(TenantContextHolder.getIsolationLevel())) {
return invocation.proceed(); return invocation.proceed();
} }

View File

@@ -20,6 +20,9 @@ import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler; import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue; import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.continew.starter.extension.tenant.autoconfigure.TenantProperties; import top.continew.starter.extension.tenant.autoconfigure.TenantProperties;
import top.continew.starter.extension.tenant.context.TenantContextHolder; import top.continew.starter.extension.tenant.context.TenantContextHolder;
import top.continew.starter.extension.tenant.enums.TenantIsolationLevel; import top.continew.starter.extension.tenant.enums.TenantIsolationLevel;
@@ -32,6 +35,7 @@ import top.continew.starter.extension.tenant.enums.TenantIsolationLevel;
*/ */
public class DefaultTenantLineHandler implements TenantLineHandler { public class DefaultTenantLineHandler implements TenantLineHandler {
private static final Logger log = LoggerFactory.getLogger(DefaultTenantLineHandler.class);
private final TenantProperties tenantProperties; private final TenantProperties tenantProperties;
public DefaultTenantLineHandler(TenantProperties tenantProperties) { public DefaultTenantLineHandler(TenantProperties tenantProperties) {
@@ -44,7 +48,8 @@ public class DefaultTenantLineHandler implements TenantLineHandler {
if (tenantId != null) { if (tenantId != null) {
return new LongValue(tenantId); return new LongValue(tenantId);
} }
return null; log.warn("Tenant ID not found in current context.");
return new NullValue();
} }
@Override @Override
@@ -54,13 +59,20 @@ public class DefaultTenantLineHandler implements TenantLineHandler {
@Override @Override
public boolean ignoreTable(String tableName) { public boolean ignoreTable(String tableName) {
Long tenantId = TenantContextHolder.getTenantId(); // 忽略租户
if (tenantId != null && tenantId.equals(tenantProperties.getSuperTenantId())) { if (TenantContextHolder.isIgnore()) {
return true; return true;
} }
// 忽略超级租户
Long tenantId = TenantContextHolder.getTenantId();
if (tenantId == null || tenantId.equals(tenantProperties.getSuperTenantId())) {
return true;
}
// 忽略数据源级隔离
if (TenantIsolationLevel.DATASOURCE.equals(TenantContextHolder.getIsolationLevel())) { if (TenantIsolationLevel.DATASOURCE.equals(TenantContextHolder.getIsolationLevel())) {
return true; return true;
} }
// 忽略指定表
return CollUtil.contains(tenantProperties.getIgnoreTables(), tableName); return CollUtil.contains(tenantProperties.getIgnoreTables(), tableName);
} }
} }