2. tenant 组件:feign 调用时,通过 header 透传 Tenant 信息

This commit is contained in:
YunaiV
2022-06-11 23:13:58 +08:00
parent ca6e7a4528
commit f08fe24174
17 changed files with 126 additions and 19 deletions

View File

@@ -0,0 +1,17 @@
package cn.iocoder.yudao.framework.tenant.config;
import cn.iocoder.yudao.framework.tenant.core.rpc.TenantRequestInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnProperty(prefix = "yudao.tenant", value = "enable", matchIfMissing = true) // 允许使用 yudao.tenant.enable=false 禁用多租户
public class YudaoTenantRpcAutoConfiguration {
@Bean
public TenantRequestInterceptor tenantRequestInterceptor() {
return new TenantRequestInterceptor();
}
}

View File

@@ -0,0 +1,25 @@
package cn.iocoder.yudao.framework.tenant.core.rpc;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.HEADER_TENANT_ID;
/**
* Tenant 的 RequestInterceptor 实现类Feign 请求时,将 {@link TenantContextHolder} 设置到 header 中,继续透传给被调用的服务
*
* @author 芋道源码
*/
public class TenantRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
Long tenantId = TenantContextHolder.getTenantId();
if (tenantId != null) {
requestTemplate.header(HEADER_TENANT_ID, String.valueOf(tenantId));
}
}
}

View File

@@ -1,6 +1,8 @@
package cn.iocoder.yudao.framework.tenant.core.security;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.RpcConstants;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
@@ -53,6 +55,12 @@ public class TenantSecurityWebFilter extends ApiRequestFilter {
this.tenantFrameworkService = tenantFrameworkService;
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return super.shouldNotFilter(request) &&
!StrUtil.startWithAny(request.getRequestURI(), RpcConstants.RPC_API_PREFIX); // 因为 RPC API 也会透传租户编号
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {

View File

@@ -18,8 +18,6 @@ import java.io.IOException;
*/
public class TenantContextWebFilter extends OncePerRequestFilter {
private static final String HEADER_TENANT_ID = "tenant-id";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {