配置
本指南详细介绍 Tushare SDK 的所有配置选项,包括重试策略、缓存配置、并发控制和日志记录等高级特性。
基本配置
创建 TushareClient 实例时传入配置选项:
1import { TushareClient } from '@hestudy/tushare-sdk';
2
3const client = new TushareClient({
4 token: 'YOUR_TUSHARE_TOKEN',
5 timeout: 30000, // 请求超时时间 (毫秒)
6 endpoint: 'https://api.tushare.pro' // API 端点
7});
配置接口
1interface TushareConfig {
2 token: string; // API Token (必需)
3 endpoint?: string; // API 端点 (默认: 'https://api.tushare.pro')
4 timeout?: number; // 请求超时时间 (默认: 30000ms)
5 retry?: Partial<RetryConfig>; // 重试配置
6 cache?: Partial<CacheConfig>; // 缓存配置
7 concurrency?: Partial<ConcurrencyConfig>; // 并发控制配置
8 logger?: Logger; // 日志记录器
9}
| 配置项 |
类型 |
必需 |
默认值 |
说明 |
token |
string |
✅ |
- |
Tushare API Token |
endpoint |
string |
❌ |
'https://api.tushare.pro' |
API 端点 |
timeout |
number |
❌ |
30000 |
请求超时时间 (毫秒) |
retry |
Partial<RetryConfig> |
❌ |
- |
重试配置 |
cache |
Partial<CacheConfig> |
❌ |
- |
缓存配置 |
concurrency |
Partial<ConcurrencyConfig> |
❌ |
- |
并发控制配置 |
logger |
Logger |
❌ |
ConsoleLogger(INFO) |
日志记录器 |
重试配置
SDK 使用指数退避算法自动重试失败的请求。
配置选项
1import { TushareClient } from '@hestudy/tushare-sdk';
2
3const client = new TushareClient({
4 token: 'YOUR_TOKEN',
5 retry: {
6 maxRetries: 3, // 最大重试次数
7 initialDelay: 1000, // 初始延迟 (毫秒)
8 maxDelay: 30000, // 最大延迟 (毫秒)
9 backoffFactor: 2 // 退避因子
10 }
11});
RetryConfig 接口
1interface RetryConfig {
2 maxRetries: number; // 最大重试次数 (默认: 3)
3 initialDelay: number; // 初始延迟 (默认: 1000ms)
4 maxDelay: number; // 最大延迟 (默认: 30000ms)
5 backoffFactor: number; // 指数退避因子 (默认: 2)
6}
| 配置项 |
类型 |
默认值 |
取值范围 |
说明 |
maxRetries |
number |
3 |
0-10 |
最大重试次数 |
initialDelay |
number |
1000 |
≥0 |
初始延迟 (毫秒) |
maxDelay |
number |
30000 |
≥1000 |
最大延迟 (毫秒) |
backoffFactor |
number |
2 |
≥1 |
指数退避因子 |
延迟计算公式
delay = min(initialDelay * backoffFactor^n, maxDelay)
例如,使用默认配置时:
- 第1次重试: 1秒
- 第2次重试: 2秒
- 第3次重试: 4秒
可重试的错误类型
SDK 会自动重试以下类型的错误:
RATE_LIMIT - 限流错误 (请求频率超限)
NETWORK_ERROR - 网络错误 (网络连接失败)
TIMEOUT_ERROR - 超时错误 (请求超时)
SERVER_ERROR - 服务器错误 (500, 502, 503, 504)
缓存配置
启用缓存可以减少重复请求,提高性能。
使用内存缓存
1import { TushareClient } from '@hestudy/tushare-sdk';
2
3const client = new TushareClient({
4 token: 'YOUR_TOKEN',
5 cache: {
6 enabled: true,
7 ttl: 3600000 // 缓存 1 小时 (毫秒)
8 }
9});
CacheConfig 接口
1interface CacheConfig {
2 enabled: boolean; // 是否启用缓存 (默认: false)
3 provider?: CacheProvider; // 缓存提供者 (默认: MemoryCacheProvider)
4 ttl: number; // 缓存过期时间 (默认: 3600000ms = 1小时)
5}
| 配置项 |
类型 |
默认值 |
说明 |
enabled |
boolean |
false |
是否启用缓存 |
provider |
CacheProvider |
MemoryCacheProvider |
缓存提供者 |
ttl |
number |
3600000 (1小时) |
缓存过期时间 (毫秒) |
自定义缓存提供者
实现 CacheProvider 接口以使用自定义缓存(如 Redis):
1import { CacheProvider, TushareClient } from '@hestudy/tushare-sdk';
2import Redis from 'ioredis';
3
4class RedisCacheProvider implements CacheProvider {
5 private redis: Redis;
6
7 constructor(redis: Redis) {
8 this.redis = redis;
9 }
10
11 async get<T>(key: string): Promise<T | null> {
12 const value = await this.redis.get(key);
13 return value ? JSON.parse(value) : null;
14 }
15
16 async set<T>(key: string, value: T, ttl = 3600000): Promise<void> {
17 await this.redis.set(key, JSON.stringify(value), 'PX', ttl);
18 }
19
20 async delete(key: string): Promise<void> {
21 await this.redis.del(key);
22 }
23
24 async clear(): Promise<void> {
25 await this.redis.flushdb();
26 }
27}
28
29// 使用自定义缓存
30const redis = new Redis();
31const client = new TushareClient({
32 token: 'YOUR_TOKEN',
33 cache: {
34 enabled: true,
35 provider: new RedisCacheProvider(redis),
36 ttl: 7200000 // 2 小时
37 }
38});
CacheProvider 接口
1interface CacheProvider {
2 get<T>(key: string): Promise<T | null>;
3 set<T>(key: string, value: T, ttl?: number): Promise<void>;
4 delete(key: string): Promise<void>;
5 clear(): Promise<void>;
6}
并发控制配置
根据 Tushare 积分等级配置并发限制,避免触发限流。
配置选项
1import { TushareClient } from '@hestudy/tushare-sdk';
2
3const client = new TushareClient({
4 token: 'YOUR_TOKEN',
5 concurrency: {
6 maxConcurrent: 5, // 最大并发请求数
7 minInterval: 200 // 最小请求间隔 (毫秒)
8 }
9});
ConcurrencyConfig 接口
1interface ConcurrencyConfig {
2 maxConcurrent: number; // 最大并发请求数 (默认: 5)
3 minInterval: number; // 最小请求间隔 (默认: 200ms)
4}
| 配置项 |
类型 |
默认值 |
取值范围 |
说明 |
maxConcurrent |
number |
5 |
1-50 |
最大并发请求数 |
minInterval |
number |
200 |
≥0 |
最小请求间隔 (毫秒) |
积分等级推荐配置
根据积分等级选择合适的配置:
| 积分等级 |
频率限制 |
推荐配置 |
| 200 积分 |
1 次/秒 |
{ maxConcurrent: 1, minInterval: 1000 } |
| 2000 积分 |
5 次/秒 |
{ maxConcurrent: 5, minInterval: 200 } |
| 5000 积分 |
20 次/秒 |
{ maxConcurrent: 20, minInterval: 50 } |
示例: 200积分配置
1const client = new TushareClient({
2 token: 'YOUR_TOKEN',
3 concurrency: {
4 maxConcurrent: 1,
5 minInterval: 1000 // 1 次/秒
6 }
7});
示例: 5000积分配置
1const client = new TushareClient({
2 token: 'YOUR_TOKEN',
3 concurrency: {
4 maxConcurrent: 20,
5 minInterval: 50 // 20 次/秒
6 }
7});
日志配置
自定义日志输出。
使用内置日志
1import { TushareClient, ConsoleLogger, LogLevel } from '@hestudy/tushare-sdk';
2
3const client = new TushareClient({
4 token: 'YOUR_TOKEN',
5 logger: new ConsoleLogger(LogLevel.DEBUG) // 输出调试日志
6});
LogLevel 枚举
1enum LogLevel {
2 DEBUG = 0, // 调试日志
3 INFO = 1, // 信息日志
4 WARN = 2, // 警告日志
5 ERROR = 3 // 错误日志
6}
自定义日志记录器
实现 Logger 接口以使用自定义日志记录器:
1import { Logger, TushareClient } from '@hestudy/tushare-sdk';
2
3class CustomLogger implements Logger {
4 debug(message: string, ...args: unknown[]): void {
5 // 自定义调试日志处理
6 console.debug(`[DEBUG] ${message}`, ...args);
7 }
8
9 info(message: string, ...args: unknown[]): void {
10 // 自定义信息日志处理
11 console.info(`[INFO] ${message}`, ...args);
12 }
13
14 warn(message: string, ...args: unknown[]): void {
15 // 自定义警告日志处理
16 console.warn(`[WARN] ${message}`, ...args);
17 }
18
19 error(message: string, ...args: unknown[]): void {
20 // 自定义错误日志处理
21 console.error(`[ERROR] ${message}`, ...args);
22 }
23}
24
25const client = new TushareClient({
26 token: 'YOUR_TOKEN',
27 logger: new CustomLogger()
28});
Logger 接口
1interface Logger {
2 debug(message: string, ...args: unknown[]): void;
3 info(message: string, ...args: unknown[]): void;
4 warn(message: string, ...args: unknown[]): void;
5 error(message: string, ...args: unknown[]): void;
6}
完整配置示例
1import { TushareClient, ConsoleLogger, LogLevel } from '@hestudy/tushare-sdk';
2
3const client = new TushareClient({
4 // 基本配置
5 token: 'YOUR_TOKEN',
6 endpoint: 'https://api.tushare.pro',
7 timeout: 30000,
8
9 // 重试配置
10 retry: {
11 maxRetries: 3,
12 initialDelay: 1000,
13 maxDelay: 30000,
14 backoffFactor: 2
15 },
16
17 // 缓存配置
18 cache: {
19 enabled: true,
20 ttl: 3600000 // 1 小时
21 },
22
23 // 并发控制 (2000积分等级)
24 concurrency: {
25 maxConcurrent: 5,
26 minInterval: 200
27 },
28
29 // 日志配置
30 logger: new ConsoleLogger(LogLevel.INFO)
31});
环境变量配置
推荐使用环境变量管理 Token:
.env 文件
1TUSHARE_TOKEN=your_api_token_here
在代码中使用
1import { TushareClient } from '@hestudy/tushare-sdk';
2
3const client = new TushareClient({
4 token: process.env.TUSHARE_TOKEN!
5});
获取 API Token
如果你还没有 API Token,请按照以下步骤获取:
- 访问 Tushare Pro 官网
- 注册并登录账号
- 在个人中心获取 API Token
- 查看积分等级,根据积分配置并发限制
常见问题
Q: Token 无效怎么办?
A: 请检查:
- Token 是否正确复制(没有多余的空格)
- Token 是否已过期
- 账号是否已激活
Q: 如何选择合适的并发配置?
A: 根据 Tushare 积分等级选择:
- 200 积分:
{ maxConcurrent: 1, minInterval: 1000 }
- 2000 积分:
{ maxConcurrent: 5, minInterval: 200 }
- 5000 积分:
{ maxConcurrent: 20, minInterval: 50 }
Q: 是否应该启用缓存?
A: 推荐启用缓存,特别是在以下场景:
- 频繁查询相同的数据(如股票基础信息)
- 需要减少 API 调用次数以避免限流
- 数据更新频率较低(如日线数据)
Q: 如何在不同环境使用不同的配置?
A: 使用环境变量文件:
1// .env.development
2TUSHARE_TOKEN=dev_token
3TUSHARE_LOG_LEVEL=DEBUG
4
5// .env.production
6TUSHARE_TOKEN=prod_token
7TUSHARE_LOG_LEVEL=INFO
安全最佳实践
- 永远不要将 Token 硬编码在代码中
1// ❌ 不要这样做
2const client = new TushareClient({ token: 'abc123xyz' });
3
4// ✅ 使用环境变量
5const client = new TushareClient({ token: process.env.TUSHARE_TOKEN! });
- 将 .env 文件添加到 .gitignore
1# .gitignore
2.env
3.env.local
4.env.*.local
- 提供 .env.example 模板
1# .env.example
2TUSHARE_TOKEN=your_token_here
- 在生产环境使用环境变量管理工具
如 AWS Secrets Manager, Azure Key Vault, 或 Vercel Environment Variables。
下一步