从0开始搭建编程框架——主框架和源码
Posted breaksoftware
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从0开始搭建编程框架——主框架和源码相关的知识,希望对你有一定的参考价值。
一个良好的结构是“对修改关闭,对扩展开放”的。(转载请指明出于breaksoftware的csdn博客)
这个过程就像搭建积木。框架本身需要有足够的向内扩展能力以使自身有进化能力,其次要有足够的外向扩展能力以使其可以方便定制业务。一般来说,我们让使用者继承框架暴露的接口,或者填充一些配置项以达到“扩展”的目的。
对内部分,我们称为模块(module)。它主要提供initialize方法供各个模块加载配置
template<class T>
class Module
public:
Module() ;
virtual ~Module() ;
public:
virtual bool initialize() final
config_callback fn = boost::bind(&T::on_init, dynamic_cast<T*>(this), _1);
ConfigRegistry::get_mutable_instance().register_config_dir(dynamic_cast<T*>(this)->name(), fn);
return true;
;
private:
virtual void on_init(const char*) = 0;
virtual const char* name() = 0;
;
module是个模板类,这是因为第8行我们需要知道子类的类型,以将其on_init方法绑定到一个函数对象fn上。fn最终会和模块的名称通过单例类ConfigRegistry的register_config_dir绑定在一起(9行)。
ConfigRegistry是框架内模块中唯一不继承于Module的单例类。
typedef boost::function<void(
const char*)> config_callback;
class ConfigRegistry :
public boost::serialization::singleton<ConfigRegistry>
public:
ConfigRegistry(void);
~ConfigRegistry(void);
public:
bool initialize(const char* conf_path);
bool register_config_dir(
const char* name,
config_callback& f_config_proc) const;
private:
void init_from_file(const char* conf_path);
private:
peleus::modules::configure::config_registry_conf _config;
struct std::map<std::string, std::string> _config_name_path;
;
它在程序一开始时就启动执行,以把框架的整体配置读取进来(9行),然后各个模块初始化时,让它们加载自己对应的配置(38行)
using ::peleus::modules::configure::module_conf;
ConfigRegistry::ConfigRegistry(void)
ConfigRegistry::~ConfigRegistry(void)
bool ConfigRegistry::initialize(const char* conf_path)
bool suc = peleus::utils::file2conf(conf_path, _config);
LOG(DEBUG) << "ConfigRegistry::initialize from " << conf_path;
if (!suc)
LOG(FATAL) << "ConfigRegistry::initialize Fatal";
return suc;
int size = _config.modules_conf_size();
for (int i = 0; i < size; i++)
const module_conf& conf = _config.modules_conf(i);
_config_name_path[conf.name()] = conf.path();
LOG(DEBUG) << "ConfigRegistry::initialize "
<< conf.name().c_str() << " " << conf.path().c_str();
LOG(DEBUG) << "ConfigRegistry::initialize Success";
return suc;
bool ConfigRegistry::register_config_dir(
const char* name,
config_callback& f_config_proc) const
auto it = _config_name_path.find(std::string(name));
if (it == _config_name_path.end())
LOG(WARNING) << "ConfigRegistry::register_config_dir search " << name << " failed";
return false;
LOG(DEBUG) << "ConfigRegistry::register_config_dir search " << name << " path: " << it->second.c_str();
f_config_proc(it->second.c_str());
return true;
第10行执行配置读取和转换。之前做服务开发时,最烦的就是配置解析和请求协议解析。在此要特别感谢google的protobuf,真是个好东西,让我把配置解析的代码也给省了
#include <string>
#include <fstream>
#include <streambuf>
#include <butil/logging.h>
#include <boost/filesystem.hpp>
#include <google/protobuf/text_format.h>
namespace peleus
namespace utils
template <class T>
bool file2conf(const char* path, T& t)
if (!boost::filesystem::exists(path))
LOG(ERROR) << path << " is not exist";
return false;
std::ifstream infile(path);
std::string content = std::string(std::istreambuf_iterator<char>(infile),
std::istreambuf_iterator<char>());
return google::protobuf::TextFormat::ParseFromString(content, &t);
对外的扩展,我们称为插件(plugin)。插件是由若干组件(Component)组成的,其暴露的on_init方法供各个组件子类实现,以加载配置
class Component
public:
explicit Component(const char* name) : _name(std::string(name))
;
virtual ~Component() ;
public:
const char* name() const
return _name.c_str();
;
public:
virtual void on_init(const char* conf_path) = 0;
virtual void reset() = 0;
private:
Component();
private:
std::string _name;
;
组件具有承载业务逻辑的作用。在《从0开始搭建编程框架——思考》一文中,我们设定每个异步过程都是以一个服务形式提供的。于是有些组件将提供服务功能,即它是个入口,这样就需要继承Entrance类
class Entrance : public Component
public:
explicit Entrance(const char* name) : Component(name)
;
virtual ~Entrance() ;
public:
virtual void on_init(const char*) = 0;
virtual void reset() = 0;
;
typedef boost::shared_ptr<Entrance> smart_ptr;
typedef smart_ptr (*creator_t)(const char*);
组件需要向框架注册,框架提供下面的方法以支持
//h
bool register_creator(const char*, creator_t);
creator_t lookup_creator(const char*);
template<class type> smart_ptr creator(const char* name)
return boost::make_shared<type>(name);
;
template<class type> bool register_class(const char* name)
return register_creator(name, creator<type>);
;
//cpp
bool register_creator(const char* name, creator_t creator)
return peleus::modules::CreatorRepertory::
get_mutable_instance().register_creator(name, creator);
creator_t lookup_creator(const char* name)
return peleus::modules::CreatorRepertory::
get_mutable_instance().lookup_creator(name);
creator和register_class方法会在插件代码中编译,register_creator和lookup_creator会在框架中编译,其中它们连接的函数register_creator将在链接时被确定。
CreatorRepertory类继承于Module,它主要用于注册和查询组件类构造指针,这些指针都是在插件注册时向框架注册绑定的
bool CreatorRepertory::register_creator(
const char* name, creator_t creator)
if (_creators.end() != _creators.find(name))
LOG(TRACE) << name << " have registed";
return true;
_creators[name] = creator;
return true;
creator_t CreatorRepertory::lookup_creator(const char* name)
auto it = _creators.find(name);
if (_creators.end() == it)
LOG(FATAL) << "can't lookup " << name << " creator";
return NULL;
return it->second;
我们再看下插件管理加载PluginLoader。其核心就是load_plugin_and_run方法。插件可以以静态链接库或者动态链接库供框架使用。
typedef bool (*module_init_func_t)(const char*);
void PluginLoader::load_plugin_and_run(
const char* so_path, int static_flag, const char* fun_name, const char* conf_path)
module_init_func_t init_func = NULL;
if (!static_flag)
FALSE_THROW(boost::filesystem::exists(so_path),
"%s can't find %s file", name(), so_path);
void* handle = dlopen(so_path, RTLD_NOW | RTLD_GLOBAL);
if (!handle)
const char* err_reason = dlerror();
FALSE_THROW(!err_reason,
"%s load %s error.reason : %s", name(), so_path, err_reason);
FALSE_THROW(0, "%s load %s error", name(), so_path);
init_func = (module_init_func_t)dlsym(handle, fun_name);
else
init_func = (module_init_func_t)dlsym((void*)RTLD_LOCAL, fun_name);
FALSE_THROW(init_func, "%s get function %s error", name(), fun_name);
FALSE_THROW(init_func(conf_path), "%s call plugin %s func %s error", name(), so_path, fun_name)
对外Server只提供一个端口,处理业务的组件对象在init_from_file方法中获取,然后再start方法中运行
void Server::init_from_file(const char* conf_path)
try
entrance_conf config;
bool suc = peleus::utils::file2conf(conf_path, config);
if (!suc)
FALSE_THROW(0, "init_from_file Fatal: %s", conf_path);
smart_ptr ptr = _entrance_repertory.get_entrance(config.name().c_str());
Service* service = dynamic_cast<google::protobuf::Service*>(ptr.get());
if (!service)
FALSE_THROW(0, "%s get service error", config.name().c_str());
if (_server.AddService(service, brpc::SERVER_DOESNT_OWN_SERVICE) != 0)
FALSE_THROW(0, "%s Add %s server error", name(), config.name().c_str());
catch (PeleusException& e)
throw;
catch (const std::exception& exp)
throw;
void Server::start()
brpc::ServerOptions options;
options.idle_timeout_sec = _config.idle_timeout_sec();
options.max_concurrency = _config.max_concurrency();
options.num_threads = _config.num_threads();
options.internal_port = _config.internal_port();
try
if (_server.Start(_config.port(), &options) != 0)
FALSE_THROW(0, "%s start server error", name());
_server.RunUntilAskedToQuit();
catch (PeleusException& e)
throw;
catch (const std::exception& exp)
throw;
提供内部服务的InterServer是类似的
void InterServer::add_inter_service()
TraversalCallback traversal_file = [this](const char* path) this->init_from_file(path);;
TraversalFloder traversal;
traversal.set_callback(NULL, traversal_file, __FILE__);
traversal.init(_config.inter_servers_conf_path().c_str());
void InterServer::init_from_file(const char* conf_path)
entrance_conf config;
bool suc = peleus::utils::file2conf(conf_path, config);
if (!suc)
LOG(FATAL) << "init_from_file Fatal: " << conf_path;
return;
add_service(config.name());
void InterServer::add_service(const std::string& entrance_name)
smart_ptr ptr = _entrance_repertory.get_entrance(entrance_name.c_str());
Service* service = dynamic_cast<google::protobuf::Service*>(ptr.get());
if (!service)
LOG(WARNING) << name() << " get service error";
if (_server.AddService(service, brpc::SERVER_DOESNT_OWN_SERVICE) != 0)
FALSE_THROW(0, "%s Add %s server error", name(), entrance_name.c_str());
void InterServer::start()
brpc::ServerOptions options;
options.idle_timeout_sec = _config.idle_timeout_sec();
options.max_concurrency = _config.max_concurrency();
try
if (_server.Start(_config.port(), &options) != 0)
FALSE_THROW(0, "%s start server error", name());
init_channel();
//_server.RunUntilAskedToQuit();
catch (PeleusException& e)
throw;
catch (const std::exception& exp)
throw;
void InterServer::init_channel()
brpc::ChannelOptions options;
const query_inter_server_conf& conf = _config.query_conf();
options.connection_type = conf.connection_type();
options.connect_timeout_ms = conf.connect_timeout_ms();
options.timeout_ms = conf.timeout_ms();
options.max_retry = conf.max_retry();
std::string server_lower = conf.server();
transform(server_lower.begin(), server_lower.end(), server_lower.begin(), ::toupper);
std::stringstream ss;
ss << _config.port();
std::string port = ss.str();
std::string server_port = conf.server();
server_port += ":";
server_port += port;
if (_channel.Init(server_port.c_str(), &options) != 0)
FALSE_THROW(0, "%s fail to initialize channel %s", name(), server_port.c_str());
Server和InterServer所使用的组件是具有“入口”性质的,即应该继承于Entrance。与之相关的类EntranceFactory通过create将各个对象构造出来
smart_ptr EntranceFactory::create(const std::string& entrance_name)
smart_ptr sp;
try
auto it = _entrances_conf.find(entrance_name);
FALSE_THROW(!(it == _entrances_conf.end()), "%s create get %s conf error", name(), entrance_name.c_str());
creator_t create_fun = CreatorRepertory::get_mutable_instance().lookup_creator(entrance_name.c_str());
FALSE_THROW(create_fun, "%s create lookup %s creator error", name(), entrance_name.c_str());
sp = create_fun(entrance_name.c_str());
FALSE_THROW(sp.get(), "%s create create %s error", name(), entrance_name.c_str());
sp->on_init(it->second.c_str());
catch (PeleusException& e)
throw;
catch (const std::exception& exp)
throw;
return sp;
如此我们便将整个框架搭建出来了。最后看下类图
以上是关于从0开始搭建编程框架——主框架和源码的主要内容,如果未能解决你的问题,请参考以下文章