RedisConnectionFactory
Tổng quan
RedisConnectionFactory là một lớp factory tĩnh tạo kết nối Redis ở chế độ đơn hoặc cluster. Nó trừu tượng hóa sự khác biệt giữa RedisHelper (đơn) và RedisClusterHelper (cluster) sau giao diện chung DefaultRedisHelper từ IGNIS, cho phép mã downstream hoạt động với cả hai chế độ một cách minh bạch.
| Thuộc tính | Giá trị |
|---|---|
| Nguồn | packages/core/src/helpers/redis/redis-connection.factory.ts |
| Kế thừa | BaseHelper (từ @venizia/ignis) |
| Trả về | DefaultRedisHelper (giao diện chung cho RedisHelper và RedisClusterHelper) |
API
RedisConnectionFactory.create()
Tạo kết nối Redis dựa trên chế độ được cung cấp.
static create(opts: TRedisConnectionOptions): DefaultRedisHelper| Tham số | Kiểu | Bắt buộc | Mô tả |
|---|---|---|---|
opts | TRedisConnectionOptions | Có | Tùy chọn kết nối (đơn hoặc cluster) |
Trả về: DefaultRedisHelper -- instance RedisHelper hoặc RedisClusterHelper.
Ném lỗi: Nếu chế độ không hợp lệ được cung cấp.
RedisConnectionFactory.parseClusterNodes()
Phân tích chuỗi phân cách bằng dấu phẩy gồm các cặp host:port thành mảng đối tượng node. Dùng để đọc danh sách cluster node từ biến môi trường.
static parseClusterNodes(opts: { raw: string }): Array<{ host: string; port: number }>| Tham số | Kiểu | Bắt buộc | Mô tả |
|---|---|---|---|
opts.raw | string | Có | Chuỗi phân cách bằng dấu phẩy, ví dụ "node1:6379,node2:6380,node3:6381" |
Trả về: Mảng đối tượng { host, port }. Port mặc định là 6379 nếu phân tích thất bại.
Giao diện Kiểu
IRedisConnectionSingleOptions
Tùy chọn để tạo kết nối Redis đơn.
interface IRedisConnectionSingleOptions {
mode?: typeof RedisModes.SINGLE; // 'single' (default when omitted)
name: string;
host?: string; // Default: 'localhost'
port?: number; // Default: 6379
password?: string;
database?: number; // Default: 0
maxRetry?: number; // Default: 5
autoConnect?: boolean; // Default: false
}| Trường | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
mode | 'single' | 'single' | Định danh chế độ kết nối |
name | string | -- | Tên kết nối dùng cho ghi log và nhận diện |
host | string | 'localhost' | Hostname server Redis |
port | number | 6379 | Port server Redis |
password | string | -- | Mật khẩu xác thực Redis |
database | number | 0 | Chỉ số cơ sở dữ liệu Redis |
maxRetry | number | 5 | Số lần thử kết nối lại tối đa |
autoConnect | boolean | false | Kết nối ngay khi tạo |
IRedisConnectionClusterOptions
Tùy chọn để tạo kết nối Redis cluster.
interface IRedisConnectionClusterOptions {
mode: typeof RedisModes.CLUSTER; // 'cluster' (required)
name: string;
nodes: Array<{ host: string; port: number }>;
password?: string;
}| Trường | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
mode | 'cluster' | -- | Phải là 'cluster' |
name | string | -- | Tên kết nối dùng cho ghi log và nhận diện |
nodes | Array<{ host, port }> | -- | Danh sách các seed node của cluster |
password | string | -- | Mật khẩu xác thực Redis (áp dụng cho tất cả node) |
TRedisConnectionOptions
Kiểu union của cả hai giao diện tùy chọn:
type TRedisConnectionOptions = IRedisConnectionSingleOptions | IRedisConnectionClusterOptions;Hành vi theo Chế độ
Chế độ Đơn
Tạo instance RedisHelper với các tùy chọn được cung cấp. Đây là mặc định khi mode bị bỏ qua.
const redis = RedisConnectionFactory.create({
name: 'my-cache-redis',
host: 'localhost',
port: 6379,
database: 0,
maxRetry: 5,
});Nội bộ tạo ra:
new RedisHelper({
name: 'my-cache-redis',
host: 'localhost',
port: 6379,
password: undefined,
database: 0,
maxRetry: 5,
autoConnect: false,
});Chế độ Cluster
Tạo instance RedisClusterHelper với sharded subscribers được bật, kết nối lazy và hỗ trợ offline queue.
const redis = RedisConnectionFactory.create({
mode: 'cluster',
name: 'my-cache-cluster',
nodes: [
{ host: 'node1', port: 6379 },
{ host: 'node2', port: 6379 },
{ host: 'node3', port: 6379 },
],
password: 'secret',
});Nội bộ tạo ra:
new RedisClusterHelper({
name: 'my-cache-cluster',
nodes: [
{ host: 'node1', port: 6379 },
{ host: 'node2', port: 6379 },
{ host: 'node3', port: 6379 },
],
clusterOptions: {
redisOptions: { password: 'secret' },
shardedSubscribers: true,
lazyConnect: true,
enableOfflineQueue: true,
},
});Tùy chọn Chế độ Cluster
| Tùy chọn Cluster | Giá trị | Mô tả |
|---|---|---|
shardedSubscribers | true | Sử dụng sharded pub/sub cho đăng ký cluster Redis 7+ |
lazyConnect | true | Không kết nối cho đến khi lệnh đầu tiên được thực thi |
enableOfflineQueue | true | Xếp hàng lệnh trong khi kết nối đang được thiết lập |
Sử dụng trong Các Gói Downstream
Bảy gói sử dụng RedisConnectionFactory để tạo kết nối WebSocket emitter:
Cách Sử dụng Điển hình trong Component
Mẫu được sử dụng bởi ApplicationWebSocketComponent của mỗi gói:
import { EnvironmentKeys, RedisConnectionFactory, RedisModes } from '@nx/core';
import { applicationEnvironment, WebSocketEmitter } from '@venizia/ignis';
export class ApplicationWebSocketComponent extends BaseComponent {
override async binding(): Promise<void> {
const mode =
applicationEnvironment.get<string>(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_MODE) ??
RedisModes.SINGLE;
const redis =
mode === RedisModes.CLUSTER
? this._createClusterRedis()
: this._createSingleRedis();
const emitter = new WebSocketEmitter({
identifier: 'sale-ws-emitter',
redisConnection: redis,
});
this.application.bind({ key: MyBindingKeys.WEBSOCKET_EMITTER }).toValue(emitter);
this.application.service(MySocketEventService);
}
private _createSingleRedis() {
return RedisConnectionFactory.create({
mode: 'single',
name: applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_IDENTIFIER)
?? 'my-ws-redis',
host: applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_HOST)
?? 'localhost',
port: int(applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_PORT))
?? 6379,
password: applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_PASSWORD),
database: int(applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_DB))
?? 0,
maxRetry: int(applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_MAX_RETRY))
?? 5,
});
}
private _createClusterRedis() {
const clusterNodesStr = applicationEnvironment.get<string>(
EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_CLUSTER_NODES,
);
if (!clusterNodesStr) {
throw getError({ message: 'Missing cluster nodes env var' });
}
return RedisConnectionFactory.create({
mode: 'cluster',
name: applicationEnvironment.get(
EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_CLUSTER_IDENTIFIER,
) ?? 'my-ws-redis-cluster',
nodes: RedisConnectionFactory.parseClusterNodes({ raw: clusterNodesStr }),
password: applicationEnvironment.get(EnvironmentKeys.APP_ENV_WEBSOCKET_REDIS_PASSWORD),
});
}
}Biến Môi trường
| Biến | Dùng cho | Ví dụ |
|---|---|---|
APP_ENV_WEBSOCKET_REDIS_MODE | Chọn chế độ đơn hoặc cluster | single |
APP_ENV_WEBSOCKET_REDIS_HOST | Hostname chế độ đơn | localhost |
APP_ENV_WEBSOCKET_REDIS_PORT | Port chế độ đơn | 6379 |
APP_ENV_WEBSOCKET_REDIS_PASSWORD | Xác thực (cả hai chế độ) | secret |
APP_ENV_WEBSOCKET_REDIS_DB | Chỉ số database chế độ đơn | 0 |
APP_ENV_WEBSOCKET_REDIS_MAX_RETRY | Số lần thử lại chế độ đơn | 5 |
APP_ENV_WEBSOCKET_REDIS_CLUSTER_NODES | Danh sách node chế độ cluster | node1:6379,node2:6379 |
Tài liệu Liên quan
- IGNIS Redis Helper -- Chi tiết triển khai
RedisHelpervàRedisClusterHelper - Thiết lập IGNIS WebSocket -- Thành phần WebSocket sử dụng Redis để mở rộng
- BaseSocketEventService -- Service sử dụng emitter được tạo với factory này
- Gói Signal -- Sử dụng
RedisConnectionFactorycho kết nối Redis WebSocket và pub/sub