IM/MS/MS.cpp
dongl 7b54e1449e 创建了vector保存固定数量的mysql链接,使用时取vector的, 暂时解了回收链接的问题。 而不是无限的新建
封了一层回收mysql链接的函数

解决了表面上的内存泄漏

30个链接 在4MB 左右
而新建 返回到池 在2.5 左右

注:后续好好看一下 mysqlpp 的连接池内容
Grab a free connection from the pool.
This method creates a new connection if an unused one doesn't exist, and destroys any that have remained unused for too long. If there is more than one free connection, we return the most recently used one; this allows older connections to die off over time when the caller's need for connections decreases. Do not delete the returned pointer. This object manages the lifetime of connection objects it creates.
Return values

a pointer to the connection
2023-05-13 14:27:10 +08:00

102 lines
2.5 KiB
C++

//
// Created by dongl on 23-4-8.
//
#include "MS.h"
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "event2/listener.h"
ev_pool* MS::pool = nullptr;
management* MS::mage = nullptr;
MS::MS() {
pool = new ev_pool(4);
pool->add_event_base(listener);
pool->add_event_bases(4);
pool->run();
mage = new class management();
}
MS::~MS() {
delete pool;
delete mage;
}
void MS::listener() {
event_base *base = event_base_new();
sockaddr_in sin = {0};
memset(&sin, 0, sizeof(sin));
sin = {
AF_INET,
htons(9999)
};
evconnlistener *listener =
evconnlistener_new_bind(base,
MS::link,
base,
LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_EXEC |
LEV_OPT_DEFERRED_ACCEPT,
10,
(sockaddr *) &sin,
sizeof(sin)
);
event_base_dispatch(base);
evconnlistener_free(listener);
event_base_free(base);
}
void MS::link(struct evconnlistener *e, int fd, struct sockaddr *addr, int socklen, void *arg) {
if (!pool) {
perror("en: Prohibit manual static invocation MS::safe_grab()\n");
return;
}
printf("listen_cb\n");
pool->add_buffer_event(fd, read_cb, write_cb, event_cb,
BEV_OPT_CLOSE_ON_FREE, (sockaddr_in*)addr);
fflush(stdout);
}
void MS::read_cb(struct bufferevent *bev, void *ctx) {
BBCA* bbca = (BBCA*) ctx;
auto addr = bbca->addr;
auto base = bbca->base;
printf("[read]: ip:%s, bev:%p, fd:%d, base:%p\n",
inet_ntoa(addr->sin_addr), bev, bufferevent_getfd(bev), base);
if (!mage) {
mage = new class management();
}
mage->read_packet(bev, (sockaddr_in*)ctx);
fflush(stdout);
}
void MS::write_cb(struct bufferevent *bev, void *ctx) {
BBCA* bbca = (BBCA*) ctx;
auto addr = bbca->addr;
auto base = bbca->base;
printf("[write]: %p\n", base);
fflush(stdout);
}
void MS::event_cb(struct bufferevent *bev, short what, void *ctx) {
BBCA* bbca = (BBCA*) ctx;
auto addr = bbca->addr;
auto base = bbca->base;
printf("[event]: %p\n", base);
if (what == BEV_EVENT_EOF || BEV_EVENT_ERROR || BEV_EVENT_TIMEOUT) {
printf("客户端退出\n");
handler::remove_user(bev);
}
fflush(stdout);
}