abelkhan中的rpc框架

rpc简介:http://www.ibm.com/developerworks/cn/aix/library/au-rpc_programming/index.html

常见的rpc框架有protobufthrift

不过abelkhan没有采用这些开源的rpc框架,而是选择自己开发了一套新的rpc框架juggle(主要是为了享受重复发明轮子的乐趣)。

juggle采用一套dsl语言描述通信协议,然后使用codegen生成对应c++或c#的代码。dsl语言的语法如下:

module test{
        void test_func(string argv1, int argv2);
}

其中module在juggle中表示一组协议,在codegen的过程中,会以module为单位生成c++(c#)文件。
在juggle中函数返回值只能是void,因为juggle中的函数是远程调用(也就是说,当调用juggle的一个函数时,会发送一条消息到连接的目标进程),不支持立刻返回返回值。
juggle支持string、int、bool、float、array和table 6种数据类型。
juggle中的类型,在c++和c#中的对应类型如下:

bool               ->        in cpp bool  (in c# Boolean)

int                  ->        in cpp int64_t (in c# Int64)

float               ->         in cpp double (in c# Double)

string             ->         in cpp std::string (in c# String)

array             ->         in cpp std::vector<boost::any> (in c# ArrayList)

table             ->         in cpp std::unordered_map<std::string, boost::any> (in c# Hashtable)

编写juggle的dsl脚本之后,进入juggle目录之后,执行gencpp即可生成c++代码(gencsharp生成c#代码)。
调用gencpp需要传入的2个参数,第一个为dsl脚本所在目录,第二个为生成代码所在的文件夹。

生成代码如下:

/*this caller file is codegen by juggle for c++*/
#include <sstream>
#include <tuple>
#include <string>
#include <Icaller.h>
#include <Ichannel.h>
#include <boost/any.hpp>
#include <boost/make_shared.hpp>

namespace caller
{
class test : public juggle::Icaller {
public:
    test(boost::shared_ptr<juggle::Ichannel> _ch) : Icaller(_ch) {
        module_name = "test";
    }

    ~test(){
    }

    void test_func(std::string argv0,int64_t argv1){
        auto v = boost::make_shared<std::vector<boost::any> >();
        v->push_back("test");
        v->push_back("test_func");
        v->push_back(boost::make_shared<std::vector<boost::any> >());
        (boost::any_cast<boost::shared_ptr<std::vector<boost::any> > >((*v)[2]))->push_back(argv0);
        (boost::any_cast<boost::shared_ptr<std::vector<boost::any> > >((*v)[2]))->push_back(argv1);
        ch->push(v);
    }

};

}
/*this module file is codegen by juggle for c++*/
#include <Imodule.h>
#include <boost/shared_ptr.hpp>
#include <boost/signals2.hpp>
#include <string>
namespace module
{
class test : public juggle::Imodule {
public:
    test(){
        module_name = "test";
        protcolcall_set.insert(std::make_pair("test_func", boost::bind(&test::test_func, this, _1)));
    }

    ~test(){
    }

    boost::signals2::signal<void(std::string, int64_t) > sigtest_funchandle;
    void test_func(boost::shared_ptr<std::vector<boost::any> > _event){
        sigtest_funchandle(
            boost::any_cast<std::string>((*_event)[0]), 
            boost::any_cast<int64_t>((*_event)[1]));
    }

};

}


caller文件夹中的是供发起远程调用端调用的代码,module是响应远程调用所需代码。

将生成的代码以include的方式引用头文件即可使用。

abelkhan服务器框架论坛:http://abelkhan.com/forum.php?mod=forumdisplay&fid=2&page=1

原文地址:https://www.cnblogs.com/qianqians/p/5693185.html