添加redis和rpc功能

This commit is contained in:
2021-08-29 18:31:21 +08:00
parent c5c2efb823
commit 430d002311
17 changed files with 643 additions and 231 deletions

32
utils/redis/driver.ts Normal file
View File

@@ -0,0 +1,32 @@
import Redis from 'ioredis'
const clients = new Map<string,RedisClientDriver>()
export class RedisClientDriver extends Redis {
constructor (
/**
* redis 客户端名字
*/
private readonly _name:string,
host:string,
port:number,
password:string,
db:number
) {
super(port,host,{
password,
db
})
clients.set(this.name,this)
}
static getClient (name:string):RedisClientDriver|null {
return clients.get(name) || null
}
get name ():string {
return this._name
}
}

53
utils/redis/init.ts Normal file
View File

@@ -0,0 +1,53 @@
import { RedisClientDriver } from './driver'
import { event } from '../../event'
interface EasyRedisConfig {
host:string,
port:number,
db:number,
password:string
}
const config_cache = new Map<string,EasyRedisConfig>()
export function getConfig (prefix:string):EasyRedisConfig {
if(!config_cache.has(prefix)) {
const host = process.env[prefix + 'REDIS_HOST'] || ''
const port = process.env[prefix + 'REDIS_PORT'] || '6379'
const db = process.env[prefix + 'REDIS_DB'] || '0'
const password = process.env[prefix + 'REDIS_PWD'] || ''
const cache = {
host,
port:parseInt(port,10),
db:parseInt(db,10),
password
}
config_cache.set(prefix,cache)
return cache
}
return config_cache.get(prefix) as unknown as EasyRedisConfig
}
function init () {
const clients_connect = [{ name:'normal',prefix:'' }]
clients_connect.forEach(item=>{
let success_count = 0
const config = getConfig(item.prefix)
const client = new RedisClientDriver(item.name,config.host,config.port,config.password,config.db)
client.addListener('connect',()=>{
success_count++
if(success_count === clients_connect.length) {
event.emit('redis-all-connected')
}
})
})
}
init()