当数据需本地化存储时,如何动态路由到境内 OSS?
解读
在国内合规场景下,敏感业务数据必须留存在境内,而阿里云 OSS 的华东 1、华北 2、华南 1 等地域 bucket 是最常用的“境内存储”载体。
面试官真正想考察的是:
- 你能否在 Struts 拦截器层 无侵入地识别“需本地化”请求;
- 你能否 运行时动态切换 endpoint(境外 bucket → 境内 bucket),而不是靠重启改配置;
- 你能否保证 同一套代码 既能服务国内云,也能服务海外云,满足跨国企业“一套代码、多地合规”的痛点。
知识点
- Struts 拦截器栈(Interceptor Stack):在 Action 执行前插入逻辑,零侵入改造。
- OGNL 上下文 + ActionContext:把“当前用户地域”放在值栈里,供拦截器读取。
- 阿里云 OSS Endpoint 映射表:境外
oss-ap-southeast-1.aliyuncs.com对应境内oss-cn-shanghai.aliyuncs.com,通过 RegionId → Endpoint 的内存 Map 做路由。 - STS 临时凭证:境内 STS 与境外 STS endpoint 不同,需要 动态构造 AssumeRoleRequest。
- Spring-Struts 集成:把
OSSRouterService注册成 Spring Bean,Struts 拦截器通过ServletContext拿到 Spring 容器,实现 依赖注入。 - 灰度开关:使用 阿里巴巴 Diamond/Nacos 配置中心 推送
route.oss.enable=true/false,实时生效,无需重启。 - 单元测试:利用 StrutsSpringTestCase 模拟上传请求,验证路由是否走到境内 Mock Endpoint。
答案
- 定义 DataLocalizationInterceptor,注册到默认拦截器栈:
- 在
intercept(ActionInvocation invocation)里,先取当前登录用户的countryCode=CN(从 Session 或 JWT)。 - 若
countryCode=CN且灰度开关开启,把ActionContext.getContext().put("ossEndpoint", "oss-cn-shanghai.aliyuncs.com");否则放境外 endpoint。
- 在
- 在 Service 层注入
OSSRouterService:- 该类持有
Map<String,String> regionMapping,key 为“用户地域”,value 为“境内 bucket+endpoint”。 - 提供
public String routeEndpoint(String originalEndpoint),返回境内对应 endpoint。
- 该类持有
- 上传前,Action 调用
OSSRouterService.routeEndpoint(original)拿到真实 endpoint,再构造OSSClient:String endpoint = (String) ActionContext.getContext().get("ossEndpoint"); OSSClient client = new OSSClient(endpoint, credentialsProvider); - 通过 Nacos 配置中心 推送
route.oss.bucket.cn=your-shanghai-bucket,实现 bucket 名动态切换。 - 返回前端时,把最终上传 host 拼成
https://your-shanghai-bucket.oss-cn-shanghai.aliyuncs.com,保证 DNS 解析落在国内,满足 数据本地化 监管要求。
拓展思考
- 双栈容灾:若境内 STS 服务异常,可降级到 境外 STS 但强制把文件 跨区域复制回境内 bucket,通过 OSS 的 Cross-Region Replication 实现,RPO<15min。
- 性能优化:境内 VPC 网络下,使用 OSS 内网 endpoint(
oss-cn-shanghai-internal.aliyuncs.com)可节省 0.12 元/GB 流出流量费;通过 ECS 角色授权 避免 AccessKey 硬编码。 - 合规审计:在拦截器里埋点,把“用户 ID+文件 MD5+境内 bucket”异步发到 阿里云操作审计(ActionTrail),满足 等保 2.0 审计要求。