feat: load balance

websocket
adriano 2024-05-20 10:00:45 -03:00
parent eb1d0f2303
commit 62f137d884
8 changed files with 63 additions and 28 deletions

View File

@ -17,6 +17,7 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@sentry/node": "^5.29.2", "@sentry/node": "^5.29.2",
"@socket.io/redis-adapter": "^7.2.0",
"@types/fluent-ffmpeg": "^2.1.21", "@types/fluent-ffmpeg": "^2.1.21",
"@types/pino": "^6.3.4", "@types/pino": "^6.3.4",
"axios": "^1.2.3", "axios": "^1.2.3",
@ -41,12 +42,13 @@
"pino": "^6.9.0", "pino": "^6.9.0",
"pino-pretty": "^9.1.1", "pino-pretty": "^9.1.1",
"qrcode-terminal": "^0.12.0", "qrcode-terminal": "^0.12.0",
"redis": "^4.6.13",
"reflect-metadata": "^0.1.13", "reflect-metadata": "^0.1.13",
"sequelize": "^5.22.3", "sequelize": "^5.22.3",
"sequelize-cli": "^5.5.1", "sequelize-cli": "^5.5.1",
"sequelize-typescript": "^1.1.0", "sequelize-typescript": "^1.1.0",
"sharp": "^0.32.5", "sharp": "^0.32.5",
"socket.io": "^3.0.5", "socket.io": "^4.7.5",
"socket.io-client": "^4.5.4", "socket.io-client": "^4.5.4",
"uuid": "^8.3.2", "uuid": "^8.3.2",
"whatsapp-web.js": "github:pedroslopez/whatsapp-web.js", "whatsapp-web.js": "github:pedroslopez/whatsapp-web.js",

View File

@ -104,16 +104,16 @@ const monitor = async () => {
stdout = stdout[1].trim().split(/\s+/); stdout = stdout[1].trim().split(/\s+/);
// DISK SPACE MONITORING // DISK SPACE MONITORING
const io = getIO(); // const io = getIO();
io.emit("diskSpaceMonit", { // io.emit("diskSpaceMonit", {
action: "update", // action: "update",
diskSpace: { // diskSpace: {
size: stdout[1], // size: stdout[1],
used: stdout[2], // used: stdout[2],
available: stdout[3], // available: stdout[3],
use: stdout[4] // use: stdout[4]
} // }
}); // });
let data: any = {}; let data: any = {};

View File

@ -3,6 +3,9 @@ import { Server } from "http";
import AppError from "../errors/AppError"; import AppError from "../errors/AppError";
import { logger } from "../utils/logger"; import { logger } from "../utils/logger";
import { createAdapter } from "@socket.io/redis-adapter";
import { createClient } from 'redis';
import { v4 as uuidv4 } from "uuid"; import { v4 as uuidv4 } from "uuid";
import ListUserParamiterService from "../services/UserServices/ListUserParamiterService"; import ListUserParamiterService from "../services/UserServices/ListUserParamiterService";
import { import {
@ -27,6 +30,7 @@ import {
} from "../services/WbotServices/wbotMessageListener"; } from "../services/WbotServices/wbotMessageListener";
import { join } from "path"; import { join } from "path";
import Whatsapp from "../models/Whatsapp"; import Whatsapp from "../models/Whatsapp";
import { get } from "../helpers/RedisClient"
let count: number = 0; let count: number = 0;
let listOnline: any[] = []; let listOnline: any[] = [];
@ -42,14 +46,30 @@ let dateTime = splitDateTime(
new Date(format(new Date(), "yyyy-MM-dd HH:mm:ss", { locale: ptBR })) new Date(format(new Date(), "yyyy-MM-dd HH:mm:ss", { locale: ptBR }))
); );
const pubClient = createClient({ url: 'redis://172.31.187.29:6379' });
const subClient = pubClient.duplicate();
pubClient.connect().catch(console.error);
subClient.connect().catch(console.error);
export const initIO = (httpServer: Server): SocketIO => { export const initIO = (httpServer: Server): SocketIO => {
io = new SocketIO(httpServer, { io = new SocketIO(httpServer, {
cors: { cors: {
origin: process.env.FRONTEND_URL origin: "*",
allowedHeaders: ["my-custom-header"],
credentials: true
}, },
maxHttpBufferSize: 1e8 maxHttpBufferSize: 1e8,
pingInterval: 25000,
pingTimeout: 60000,
adapter: createAdapter(pubClient, subClient)
}); });
io.on("connection", socket => { io.on("connection", socket => {
logger.info("Client Connected"); logger.info("Client Connected");
@ -107,6 +127,7 @@ export const initIO = (httpServer: Server): SocketIO => {
socket.on("online", (userId: any) => { socket.on("online", (userId: any) => {
// console.log('userId: ', userId) // console.log('userId: ', userId)
return
obj.uuid = uuidv4(); obj.uuid = uuidv4();
if (userId.logoutUserId) { if (userId.logoutUserId) {
@ -233,13 +254,18 @@ export const initIO = (httpServer: Server): SocketIO => {
if (rooms && rooms.size == 2 && ![...rooms][1].startsWith("session_")) if (rooms && rooms.size == 2 && ![...rooms][1].startsWith("session_"))
return; return;
let whatsappIds: any = await Whatsapp.findAll({ let whatsappIds = await get({
attributes: ["id"], key: "whatsapp:*",
raw: true parse: true
}); });
// let whatsappIds: any = await Whatsapp.findAll({
// attributes: ["id"],
// raw: true
// });
if (whatsappIds && whatsappIds.length > 0) { if (whatsappIds && whatsappIds.length > 0) {
whatsappIds = whatsappIds.map((e: any) => `${e.id}`); // whatsappIds = whatsappIds.map((e: any) => `${e.id}`);
console.log( console.log(
"whatsappIds whatsappIds whatsappIds whatsappIds whatsappIds: ", "whatsappIds whatsappIds whatsappIds whatsappIds whatsappIds: ",

View File

@ -43,7 +43,7 @@
"yup": "^0.32.8" "yup": "^0.32.8"
}, },
"scripts": { "scripts": {
"start": "react-scripts start", "start": "PORT=3331 react-scripts start",
"build": "react-scripts build", "build": "react-scripts build",
"test": "react-scripts test", "test": "react-scripts test",
"eject": "react-scripts eject" "eject": "react-scripts eject"

View File

@ -6,4 +6,4 @@ app.use(express.static(path.join(__dirname, "build")));
app.get("/*", function (req, res) { app.get("/*", function (req, res) {
res.sendFile(path.join(__dirname, "build", "index.html")); res.sendFile(path.join(__dirname, "build", "index.html"));
}); });
app.listen(3333); app.listen(3331);

View File

@ -450,16 +450,16 @@ const MessagesList = ({ ticketId, isGroup }) => {
socket.on("connect", onConnectMessagesList) socket.on("connect", onConnectMessagesList)
onAppMessageMessagesList = (data) => { const onAppMessageMessagesList = (data) => {
if (data.action === "create" && data.ticket.id === ticketId) { if (data.action === "create") {
dispatch({ type: "ADD_MESSAGE", payload: data.message }) dispatch({ type: "ADD_MESSAGE", payload: data.message })
scrollToBottom() scrollToBottom()
} }
if (data.action === "update" && data.ticket.id === ticketId) { if (data.action === "update") {
dispatch({ type: "UPDATE_MESSAGE", payload: data.message }) dispatch({ type: "UPDATE_MESSAGE", payload: data.message })
} }
} }

View File

@ -1,7 +1,7 @@
import axios from "axios"; import axios from "axios";
const api = axios.create({ const api = axios.create({
baseURL: process.env.REACT_APP_BACKEND_URL, baseURL: process.env.REACT_APP_BACKEND_URL + "/api",
withCredentials: true, withCredentials: true,
}); });

View File

@ -3,4 +3,11 @@ import { io } from 'socket.io-client';
// "undefined" means the URL will be computed from the `window.location` object // "undefined" means the URL will be computed from the `window.location` object
const URL = process.env.REACT_APP_BACKEND_URL const URL = process.env.REACT_APP_BACKEND_URL
export const socket = io(URL); export const socket = io(URL, {
path: "/api-ws/socketio",
withCredentials: true,
extraHeaders: {
"my-custom-header": "abcd"
},
// transports: ['websocket', 'polling']
});