abelkhan中的rpc框架

abelkhan中的rpc框架

编码文章call10242025-04-11 14:07:5120A+A-

常见的rpc框架有protobuf、thrift。

不过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 (in c# ArrayList)

table ->         in cpp std::unordered_map (in c# Hashtable)

编写juggle的dsl脚本之后,进入juggle目录之后,执行gencpp即可生成c++代码(gencsharp生成c#代码)。

调用gencpp需要传入的2个参数,第一个为dsl脚本所在目录,第二个为生成代码所在的文件夹。

生成代码如下:

/*this caller file is codegen by juggle for c++*/
#include 
#include 
#include 
#include 
#include 
#include <boost/any.hpp>
#include <boost/make_shared.hpp>

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

    ~test{
    }

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

};

}
/*this module file is codegen by juggle for c++*/
#include 
#include <boost/shared_ptr.hpp>
#include <boost/signals2.hpp>
#include 
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 sigtest_funchandle;
    void test_func(boost::shared_ptr<std::vector > _event){
        sigtest_funchandle(
 boost::any_cast((*_event)[0]), 
 boost::any_cast((*_event)[1]));
    }

};

}

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

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

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4