From 48ea805999c6cb8e900aeaec6edaf68788bd51e0 Mon Sep 17 00:00:00 2001 From: syuilo Date: Tue, 23 Mar 2021 11:53:25 +0900 Subject: [PATCH] =?UTF-8?q?perf(server):=20Redis=E6=8E=A5=E7=B6=9A?= =?UTF-8?q?=E3=82=92=E3=82=B9=E3=83=88=E3=83=AA=E3=83=BC=E3=83=9F=E3=83=B3?= =?UTF-8?q?=E3=82=B0=E6=8E=A5=E7=B6=9A=E3=81=94=E3=81=A8=E3=81=AB=E4=BD=9C?= =?UTF-8?q?=E3=82=89=E3=81=9A=E3=80=81=E3=83=97=E3=83=AD=E3=82=BB=E3=82=B9?= =?UTF-8?q?=E5=85=A8=E4=BD=93=E3=81=A7=E5=85=B1=E6=9C=89=E3=81=99=E3=82=8B?= =?UTF-8?q?=E3=82=88=E3=81=86=E3=81=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/redis.ts | 6 +++++- src/server/api/streaming.ts | 33 ++++++++------------------------- 2 files changed, 13 insertions(+), 26 deletions(-) diff --git a/src/db/redis.ts b/src/db/redis.ts index 41d030149..7570aa59b 100644 --- a/src/db/redis.ts +++ b/src/db/redis.ts @@ -1,7 +1,7 @@ import * as redis from 'redis'; import config from '../config'; -export default redis.createClient( +const client = redis.createClient( config.redis.port, config.redis.host, { @@ -10,3 +10,7 @@ export default redis.createClient( db: config.redis.db || 0 } ); + +client.subscribe(config.host); + +export default client; diff --git a/src/server/api/streaming.ts b/src/server/api/streaming.ts index 10f2a70ba..4ec0c5137 100644 --- a/src/server/api/streaming.ts +++ b/src/server/api/streaming.ts @@ -1,12 +1,11 @@ import * as http from 'http'; import * as websocket from 'websocket'; -import * as redis from 'redis'; import MainStreamConnection from './stream'; import { ParsedUrlQuery } from 'querystring'; import authenticate from './authenticate'; import { EventEmitter } from 'events'; -import config from '../../config'; +import redisClient from '../../db/redis'; module.exports = (server: http.Server) => { // Init websocket server @@ -24,37 +23,21 @@ module.exports = (server: http.Server) => { const connection = request.accept(); - let ev: EventEmitter; + const ev = new EventEmitter(); - // Connect to Redis - const subscriber = redis.createClient( - config.redis.port, - config.redis.host, - { - password: config.redis.pass - } - ); + async function onRedisMessage(_: string, data: string) { + const parsed = JSON.parse(data); + ev.emit(parsed.channel, parsed.message); + } - subscriber.subscribe(config.host); - - ev = new EventEmitter(); - - subscriber.on('message', async (_, data) => { - const obj = JSON.parse(data); - - ev.emit(obj.channel, obj.message); - }); - - connection.once('close', () => { - subscriber.unsubscribe(); - subscriber.quit(); - }); + redisClient.on('message', onRedisMessage); const main = new MainStreamConnection(connection, ev, user, app); connection.once('close', () => { ev.removeAllListeners(); main.dispose(); + redisClient.off('message', onRedisMessage); }); connection.on('message', async (data) => {