Refactored database handling

This commit is contained in:
2021-05-18 18:44:17 +02:00
parent a89068047b
commit d25e039751
6 changed files with 58 additions and 50 deletions

View File

@ -1,18 +1,19 @@
mod database;
mod http;
mod udp;
mod usimp;
mod websocket;
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod, SslStream};
use std::net::{TcpListener, UdpSocket, SocketAddr};
use r2d2;
use r2d2::{ManageConnection, Pool};
use r2d2_postgres::{postgres::NoTls, PostgresConnectionManager};
use std::net::{SocketAddr, TcpListener, UdpSocket};
use std::ops::Deref;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use threadpool::ThreadPool;
use r2d2_postgres::{PostgresConnectionManager, postgres::NoTls};
use r2d2;
use r2d2::{ManageConnection, Pool};
use std::ops::Deref;
enum SocketType {
Http,
@ -25,26 +26,6 @@ struct SocketConfig {
socket_type: SocketType,
}
pub enum BackendPool {
Postgres(Pool<PostgresConnectionManager<NoTls>>),
}
pub enum BackendClient {
Postgres(r2d2::PooledConnection<PostgresConnectionManager<NoTls>>),
}
static mut DB_POOL: Option<Arc<Mutex<BackendPool>>> = None;
pub fn get_backend() -> BackendClient {
unsafe {
match DB_POOL.as_ref().unwrap().clone().lock().unwrap().deref() {
BackendPool::Postgres(pool) => {
BackendClient::Postgres(pool.get().unwrap())
}
}
}
}
fn main() {
let socket_configs: Vec<SocketConfig> = vec![
SocketConfig {
@ -58,17 +39,10 @@ fn main() {
SocketConfig {
address: "[::]:3126".parse().unwrap(),
socket_type: SocketType::Udp,
}
},
];
let db_manager = PostgresConnectionManager::new(
"host=localhost user=postgres dbname=test".parse().unwrap(),
NoTls,
);
let db_pool = r2d2::Pool::new(db_manager).unwrap();
unsafe {
DB_POOL = Some(Arc::new(Mutex::new(BackendPool::Postgres(db_pool))));
}
database::init();
let thread_pool = ThreadPool::new(256);
let thread_pool_mutex = Arc::new(Mutex::new(thread_pool));
@ -121,7 +95,10 @@ fn main() {
loop {
let (size, addr) = udp_socket.recv_from(&mut buf).unwrap();
let req = udp::Request::new(&udp_socket, addr, size, &buf);
thread_pool_mutex.lock().unwrap().execute(|| udp::handler(req));
thread_pool_mutex
.lock()
.unwrap()
.execute(|| udp::handler(req));
}
}),
});