Midway 集成阿里云 TableStore 实战指南:安装、多客户端配置与数据读写
Midway 集成阿里云 TableStore 实战指南:安装、多客户端配置与数据读写
本文介绍如何基于 Midway 框架(标准项目、Serverless 与一体化项目均可)接入阿里云 TableStore(表格存储),涵盖组件安装、客户端配置、依赖注入与工厂多实例管理,以及 getRow、putRow、条件过滤、事务与搜索索引等数据操作。读完本文,你将掌握在 Midway 应用中通过 TableStoreService 快速读写表格数据、通过 TableStoreServiceFactory 管理多实例,并了解底层代理实现与可复用的示例代码。
组件能力概览
Midway 通过 @midwayjs/tablestore 组件将阿里云 TableStore(原 OTS)官方 Node.js SDK 无缝接入依赖注入体系,可用场景如下:
| 描述 | |
|---|---|
| 可用于标准项目 | ✅ |
| 可用于 Serverless | ✅ |
| 可用于一体化 | ✅ |
| 包含独立主框架 | ❌ |
| 包含独立日志 | ❌ |
该组件不包含独立主框架与独立日志能力,仅作为数据访问组件运行在 Midway 主框架之上。从源码看,组件核心由 configuration.ts、manager.ts、proxy.ts 与 interface.ts 构成,后文将逐一展开。
安装依赖
在项目根目录执行:
$ npm i @midwayjs/tablestore@4 --save
或者在 package.json 中增加依赖后重新安装:
{
"dependencies": {
"@midwayjs/tablestore": "^4.0.0"
}
}
@midwayjs/tablestore 底层依赖阿里云官方 tablestore SDK,安装时会一并拉取。
引入组件
在 src/configuration.ts 中导入组件:
import { Configuration } from '@midwayjs/core';
import * as tablestore from '@midwayjs/tablestore';
import { join } from 'path';
@Configuration({
imports: [
tablestore, // 导入 tablestore 组件
],
importConfigs: [
join(__dirname, 'config'),
],
})
export class MainConfiguration {
}
组件内部通过 configuration.ts 以 @Configuration({ namespace: 'tableStore' }) 注册命名空间,并在 onReady 阶段异步获取 TableStoreServiceFactory,确保应用启动时客户端已被创建、后续注入即可直接使用。
配置
组件使用 tableStore 顶层配置项,支持单客户端与多客户端两种形式。
单客户端配置
// src/config/config.default.ts
export default {
tableStore: {
client: {
accessKeyId: '<your access key id>',
secretAccessKey: '<your access key secret>',
stsToken: '<your stsToken>', // 使用 STS 授权时需要填写
endpoint: '<your endpoint>',
instancename: '<your instance name>',
},
},
};
多客户端配置
// src/config/config.default.ts
export default {
tableStore: {
clients: {
db1: {
accessKeyId: '<your access key id>',
secretAccessKey: '<your access key secret>',
stsToken: '<your stsToken>',
endpoint: '<your endpoint>',
instancename: '<your instance name>',
},
db2: {
accessKeyId: '<your access key id>',
secretAccessKey: '<your access key secret>',
stsToken: '<your stsToken>',
endpoint: '<your endpoint>',
instancename: '<your instance name>',
},
},
},
};
配置参数说明
根据 interface.ts 中 TableStoreConfig 的定义,客户端支持以下参数:
| 参数 | 说明 | 默认值 |
|---|---|---|
accessKeyId |
阿里云访问密钥 ID,必填 | 无 |
secretAccessKey / accessKeySecret |
访问密钥 Secret,两者等价 | 无 |
stsToken / securityToken |
使用 STS 临时授权时填写,两者等价 | 无 |
endpoint |
TableStore 实例访问地址,必填 | 无 |
instancename |
实例名称,必填 | 无 |
logger |
自定义日志对象 | 无 |
httpOptions.timeout |
HTTP 请求超时时间(毫秒) | 无 |
httpOptions.maxSockets |
最大 socket 连接数 | 300 |
maxRetries |
请求失败最大重试次数 | 无 |
computeChecksums |
是否计算校验和 | true |
更多底层参数可查阅阿里云官方 TableStore Node.js SDK 文档;
@midwayjs/tablestore直接以这些配置构造官方TableStore.Client。
使用 TableStore 服务
注入 TableStoreService
在任意被依赖注入管理的类中注入即可使用:
import { Provide, Controller, Inject, Get } from '@midwayjs/core';
import { TableStoreService } from '@midwayjs/tablestore';
@Provide()
export class UserService {
@Inject()
tableStoreService: TableStoreService;
async invoke() {
await this.tableStoreService.putRow(params);
}
}
TableStoreService 是单例(ScopeEnum.Singleton),内部持有默认客户端(单客户端配置下的 default 实例),并把官方 TableStore.Client 的全部方法(putRow、getRow、getRange、batchGetRow 等)通过 delegateTargetPrototypeMethod 代理到自身(见 manager.ts)。若默认实例不存在,初始化时会抛出 TableStore default instance not found. 错误。
通过工厂获取多客户端实例
多客户端场景下,使用 TableStoreServiceFactory 按名称获取不同实例:
import { TableStoreServiceFactory } from '@midwayjs/tablestore';
import { join } from 'path';
@Provide()
export class UserService {
@Inject()
tableStoreServiceFactory: TableStoreServiceFactory;
async save() {
const db1 = await this.tableStoreServiceFactory.get('db1');
const db2 = await this.tableStoreServiceFactory.get('db2');
// ...
}
}
TableStoreServiceFactory 继承自 Midway 的 ServiceFactory,在 init 阶段根据 tableStore 配置并发创建全部客户端(见 manager.ts),命名空间名为 tableStore。单客户端配置时实例名为 default;多客户端配置时实例名为 clients 下的 key(如 db1、db2)。
完整示例:getRow 与条件过滤
以 getRow 为例,@midwayjs/tablestore 已代理接管官方 SDK 导出的类型(如 Long、CompositeCondition、SingleColumnCondition、LogicalOperator、ComparatorType 等),可直接使用:
import { join } from 'path';
import {
TableStoreService,
Long,
CompositeCondition,
SingleColumnCondition,
LogicalOperator,
ComparatorType,
} from '@midwayjs/tablestore';
@Provide()
export class UserService {
@Inject()
tableStoreService: TableStoreService;
async getInfo() {
const data = await this.tableStoreService.getRow({
tableName: 'sampleTable',
primaryKey: [{ gid: Long.fromNumber(20013) }, { uid: Long.fromNumber(20013) }],
maxVersions: 1, // 读取最新版本,默认为 1
columnsToGet: ['col1', 'col2'], // 只读取指定列
columnFilter: condition,
});
// TODO
}
}
参照仓库示例 getRow.ts,可以组合条件过滤器,实现"当 col1 = 表格存储 且 col5 = 123456789 时返回该行"的读取语义:
const condition = new CompositeCondition(LogicalOperator.AND);
condition.addSubCondition(
new SingleColumnCondition('col1', '表格存储', ComparatorType.EQUAL)
);
condition.addSubCondition(
new SingleColumnCondition('col5', Long.fromNumber(123456789), ComparatorType.EQUAL)
);
深入了解:条件构造器与工具函数
@midwayjs/tablestore 在 proxy.ts 中对官方 SDK 的条件类做了包装,保持原有 API 形态:
CompositeCondition(combinator):组合条件,combinator取LogicalOperator.NOT / AND / OR,通过addSubCondition添加子条件;Condition(rowExistenceExpectation, columnCondition?):行条件,RowExistenceExpectation取IGNORE / EXPECT_EXIST / EXPECT_NOT_EXIST;SingleColumnCondition(columnName, columnValue, comparator, passIfMissing = true, latestVersionOnly = true):单列条件,ComparatorType提供EQUAL / NOT_EQUAL / GREATER_THAN / GREATER_EQUAL / LESS_THAN / LESS_EQUAL六种比较符,passIfMissing控制目标列不存在时条件是否通过(默认通过);Long:与官方TableStore.Long一致,支持fromNumber/fromString构造 Int64 主键值。
此外,util.ts 提供了两个结果格式化工具:formatRow(row, filterColumn) 将 SDK 返回的主键与属性列扁平化为 { 列名: 值 } 对象(可按列名过滤,值统一转为字符串);formatRows(result, filterColumn) 批量格式化 getRange 等接口返回的行列表,并额外提取 next_start_primary_key 作为分页游标 next。
测试与运行验证
组件自带测试与可运行示例,可先于真实环境验证接入逻辑:
- 测试用例 index.test.ts 通过
createLightApp加载轻量应用,断言TableStoreService、TableStoreServiceFactory可正常获取且工厂命名为tableStore,并验证条件构造器与"默认实例缺失时抛错"的行为; - 示例代码位于 test/sample 目录,覆盖
putRow、getRow、getRange、updateRow、deleteRow、batchGetRow、batchWriteRow、createTable、createSearchIndex、search、transaction、autoIncrement等 27 个场景,可作为各类数据操作的参考模板; - 测试夹具 base-app 展示了最小配置形态(
tableStore.client下仅配置必填的accessKeyId即可完成客户端创建)。
结语
通过 @midwayjs/tablestore 组件,Midway 应用可以像使用其他数据组件一样,以声明式配置与依赖注入方式使用阿里云 TableStore:单客户端直接注入 TableStoreService,多客户端通过 TableStoreServiceFactory 按名获取;官方 SDK 的类型与条件构造器全部被代理接管,配合仓库中的 27 个示例脚本,可快速覆盖建表、读写、范围查询、批量操作、搜索索引与局部事务等完整场景。