站在巨人的肩膀上
C++高性能分布式服务器框架
从零开始重写sylar C++高性能分布式服务器框架
概述
- 从配置文件中加载用户配置,灵活实现用户自己按需配置。
- 其实最简单的配置文件方式还是 .ini 那种,极其简单。YAML 的好处是支持复杂的数据类型。
- 这里使用 YAML 作为配置文件,配置名称大小写不敏感,并且支持级别格式的数据类型。
- 这里支持 STL 容器(vector, list, set, map 等等),支持自定义类型(但需要实现序列化和反序列化方法,也就是两个仿函数)。
- YAML 语法快速简单入门:https://www.runoob.com/w3cnote/yaml-intro.html
ConfigVarBase
- 配置变量的基类。
- 虚基类。包含配置名称和配置描述两个属性。提供 toString() 和 fromString() 两个纯虚函数将参数值转换成 YAML String 和从 YAML String 转成参数的值。
LexicalCast
ConfigVar
- template, class ToStr = LexicalCast >。其中,T 是配置项参数,FromStr 是将 YAML String 转成参数的值的仿函数,ToStr 是将参数值转换成 YAML String 的仿函数。
- 对于每种类型的配置,在对应的 ConfigVar 模板类实例化时都要提供其 FromStr 和 ToStr 两个仿函数,用于实现该类型和 YAML 字符串的相互转换。
- 配置参数模板子类。继承自 ConfigVarBase。
- 保存对应类型 T 的参数值。
- 根据不同的非内置基本类型 T,FromStr 和 ToStr 具有不同的模板偏特化实现。
- 内含一个 std::map,存放配置变更的回调函数。
- 提供 setValue() 和 getValue() 函数,其中在 setValue() 函数中,会调用 std::map 中存放的所有回调函数进行通知配置变更。
- 关于回调函数,提供 addListener()、delListener()、getListener()、clearListener() 四个函数给外界使用。
Config
- ConfigVar 的管理类。
- 管理所有的配置项,通过静态函数 GetDatas() 获取缓存的 std::unordered_map。
- 提供 Lookup(const std::string& name, const T& default_value, const std::string& description = “”) 函数给外界获取/创建对应参数名的配置参数。
- 提供 Lookup(const std::string& name) 函数给外界查找配置参数。
- 提供 LoadFromYaml(const YAML::Node& root) 函数给外界使用YAML::Node初始化配置模块。
- 提供 LoadFromConfDir(const std::string& path, bool force = false) 给外界加载path文件夹里面的配置文件。
- 值得注意的是 Config 所有函数和变量均为静态的。
大概用法
sylar::ConfigVar::ptr g_int_value_config = sylar::Config::Lookup("system.port", (int)8080, "system port");
|
|
\|/
SYLAR_LOG_INFO(SYLAR_LOG_ROOT()) << "before: " << g_int_value_config->getValue();
|
|
\|/
YAML::Node root = YAML::LoadFile("/home/sylar/workspace/sylar/bin/conf/test.yml");
sylar::Config::LoadFromYaml(root);
|
|
\|/
SYLAR_LOG_INFO(SYLAR_LOG_ROOT()) << "after: " << g_int_value_config->getValue();
部分相关代码
/**
* @filename config.h
* @brief 配置模块
* @author L-ge
* @version 0.1
* @modify 2022-06-25
*/
#ifndef __SYLAR_CONFIG_H__
#define __SYLAR_CONFIG_H__
#include
#include
#include
#include
#include
#include
#include
广告时间:基于sylar框架实现的小demo(希望给个star)
基于redis的参数查询服务