云备份day3
使用文件配置加载一些程序的运行关键信息可以让程序的运行更加灵活,且当需要修改部分内容时,不需要在代码上修改,只需要修改配置文件,然后重启服务器即可。
配置信息
- 热点判断时间
- 文件下载URL前缀路径
- 压缩包后缀名称
- 上传文件存放路径
- 压缩文件存放路径
- 服务端备份信息存放文件
- 服务器访问 IP 地址
- 服务器访问端口
采用json
格式将配置信息存放在Cloud.conf中,当启动服务器时,由服务器从.conf文件中读取关键数据。
Cloud.conf
{
“hot_time” : 30,
“server_port” : 9090,
“server_ip” : “1.1.1.1”,
“url_prefix” : “/download/”,
“arc_suffix” : “.lz”,
“pack_dir” : “./packdir/”,
“back_dir” : “./backdir/”,
“manager_file” : “./back.dat”
}
读取配置信息:
在服务器启动时,需要其自动化去加载数据,采取单例模式,在服务器启动时一起进行初始化。(懒汉模式)
#define CONFIG_FILE "./cloud.conf"
class Config{
private:
time_t _hot_time;
int _server_port;
std::string _server_ip;
std::string _url_prefix;
std::string _arc_suffix;
std::string _pack_dir;
std::string _back_dir;
std::string _manager_file;//备份信息的配置管理
private:
static std::mutex _mutex;
static Config *_instance;
Config();
public:
bool ReadConfig(const std::string &filename);
int GetHotTime();
int GetServerPort();
std::string GetServerIp();
std::string GetURLPrefix();
std::string GetArcSuffix();
std::string GetPackDir();
std::string GetBackDir();
std::string GetManagerFile();
public:
static Config *GetInstance();
};
代码:
#define CONFIG_FILE "./cloud.conf"
class Config{
private:
Config(){
ReadConfigFile();
}
static Config *_instance;
static std::mutex _mutex;
private:
int _hot_time;
int _server_port;
std::string _server_ip;
std::string _download_prefix;
std::string _packfile_suffix;
std::string _pack_dir;
std::string _back_dir;
std::string _backup_file;
bool ReadConfigFile() {
FileUtil fu(CONFIG_FILE);
std::string body;
if(fu.GetContent(&body) == false){
std::cout << "load config file failed!\n";
return false;
}
Json::Value root;
if (JsonUtil::UnSerialize(body, &root) == false){
std::cout << "parse config file failed!\n";
return false;
}
_hot_time = root["hot_time"].asInt();
_server_port = root["server_port"].asInt();
_server_ip = root["server_ip"].asString();
_download_prefix = root["download_prefix"].asString();
_packfile_suffix = root["packfile_suffix"].asString();
_pack_dir = root["pack_dir"].asString();
_back_dir = root["back_dir"].asString();
_backup_file = root["backup_file"].asString();
return true;
}
public:
static Config *GetInstance() {
if (_instance == NULL){
_mutex.lock();
if (_instance == NULL) {
_instance = new Config();
}
_mutex.unlock();
}
return _instance;
}
int GetHotTime() {
return _hot_time;
}
int GetServerPort() {
return _server_port;
}
std::string GetServerIp() {
return _server_ip;
}
std::string GetDownloadPrefix() {
return _download_prefix;
}
std::string GetPackFileSuffix() {
return _packfile_suffix;
}
std::string GetPackDir() {
return _pack_dir;
}
std::string GetBackDir() {
return _back_dir;
}
std::string GetBackupFile() {
return _backup_file;
}
};
Config *Config::_instance = NULL;
std::mutex Config::_mutex;