本项目服务器的配置通过配置文件的形式来实现。配置文件格式为Json
配置文件包括以下信息:
- 热点判断时间
- 文件下载URL前缀路径(服务器根目录)
用于用户请求区分,eg:下载文件请求自动添加/download,查看请求自动添加wwwroot/ - 压缩包后缀名称格式 eg::eg:文件原名称+压缩后缀
- 上传文件存放位置
- 压缩文件存放位置
- 服务器备份信息存放文件:服务器启动信息持久化存储,使用MySQL,文件等
- 服务器监听ip和监听端口
使用配置文件加载一些程序运行关键信息可以让程序更加灵活
eg:
{
"hot_time":30,
"sever_ip":"116.204.70.147",
"sever_port":8081,
"download_prefix":"/download",
"packfile_suffix":".lz",
"packfile_dir":"./packdir",
"back_dir":"./backdir",
"backup_file":"./cloud.data"
}
单例配置类设计:(紧跟前面的项目设计)
#pragma once
#include "../util/json.hpp"
#include "../util/fileutil.hpp"
#include <mutex>
#define CONFIG_FILE "./config/cloud_backups.conf"
namespace CloudBackups
{
class Config
{
private:
Config(const Config &config) = delete;
Config()
{
// 读取配置文件
CloudBackups::FileUtil file(CONFIG_FILE);
std::string body;
if (file.getContent(body) == false)
{
LOG(FATAL, "read config error!");
exit(-1);
}
Json::Value root;
if (CloudBackups::JsonUtil::unserialize(body, root) == false)
{
LOG(FATAL, "unserialize config error!");
exit(-1);
}
// 解析配置
hot_time = root["hot_time"].asInt();
sever_port = root["server_port"].asInt();
server_ip = root["server_ip"].asString();
download_prefix = root["download_prefix"].asString();
packfile_suffix = root["packfile_suffix"].asString();
packfile_dir = root["packfile_dir"].asString();
back_dir = root["back_dir"].asString();
backup_file = root["backup_file"].asString();
}
static Config *instance;
static std::mutex lock;
int hot_time;
int sever_port;
std::string server_ip;
std::string download_prefix;
std::string packfile_suffix;
std::string packfile_dir;
std::string back_dir;
std::string backup_file;
public:
static Config *GetInstance()
{
if (!instance)
{
lock.lock();
if (!instance)
{
instance = new Config();
}
lock.unlock();
}
return instance;
}
int GetHotTime() { return hot_time; }
int GetServerPort() { return sever_port; }
std::string GetServerIp() { return server_ip; }
std::string GetDownloadPrefix() { return download_prefix; }
std::string GetPackfileSuffix() { return packfile_suffix; }
std::string GetPackfileDir() { return packfile_dir; }
std::string GetBackDir() { return back_dir; }
std::string GetBackupFile() { return backup_file; }
};
Config *Config::instance = nullptr;
std::mutex Config::lock;
}