使用cppcms开发JSON_RPC服务:高级用法

来源:互联网 发布:js修改url 不跳转 编辑:程序博客网 时间:2024/05/14 17:37


通过最近几天的研究,我发现cppcms的API有更高级更丰富的功能,比如URL的映射,JSON value与常用数据类型的转换。其配置文件也有很丰富的选项,比如多线程和多进程模式,网络参数等。

代码示例如下:

#include <cppcms/application.h>#include <cppcms/applications_pool.h>#include <cppcms/service.h>#include <cppcms/http_response.h>#include <cppcms/rpc_json.h>#include <cppcms/json.h>#include <cppcms/mount_point.h>#include <map>#include <string> #include <exception>#include <iostream> using namespace std;using cppcms::rpc::json_rpc_server;using cppcms::rpc::json_method; class calc_service : public json_rpc_server {public:    calc_service(cppcms::service &srv) : json_rpc_server(srv) {        bind("sum",            json_method(&calc_service::sum,this),method_role);        bind("div",            json_method(&calc_service::div,this),method_role);    }    void sum(int x,int y) {        cppcms::json::value v;        v["x"]=x;        v["y"]=y;        v["result"]=x+y;        return_result(v);    }    void div(int x,int y) {        if(y == 0) {            return_error("Division by zero.");        } else {            return_result(x/y);        }    }}; class hello_service : public json_rpc_server {public:    hello_service(cppcms::service &srv) : json_rpc_server(srv) {        bind("hello",            json_method(&hello_service::hello,this),method_role);        bind("hello_all",            json_method(&hello_service::hello_all,this),method_role);        bind("hello_x",            json_method(&hello_service::hello_x,this),method_role);    }    void hello(string name) {        string say="Hello, " + name + ".";        return_result(say);    }    void hello_all(vector<string> names) {        string say="Hello, ";        for(unsigned i=0;i<names.size();i++) {            say += names[i] + " ";        }        return_result(say);    }    void hello_x(cppcms::json::value val) {        return_result(val);    }}; int main(int argc,char **argv) {    try {        cppcms::service srv(argc,argv);         srv.applications_pool().mount(            cppcms::applications_factory<calc_service>(),            cppcms::mount_point("/calc")        );         srv.applications_pool().mount(            cppcms::applications_factory<hello_service>(),            cppcms::mount_point("/hello")        );        srv.run();    } catch (exception const &e) {        cerr << e.what() << endl;    }    return 0;}


配置文件示例:

{    "service" : {        "api" : "http",        "ip" : "0.0.0.0",        "port" : 8080,        "worker_threads" : 50,        "worker_processes" : 4,        "backlog" : 1024,        "application_pool_size" : 128,             },    "http" : {        "script_names" : [ "/calc","/hello" ]    }}

http://xmgu2008.blog.163.com/blog/static/139122380201411291553265/

 


0 0
原创粉丝点击