采用C++模板技术,实现的分布式哈希存储服务器

来源:互联网 发布:传奇数据库攻速是哪个 编辑:程序博客网 时间:2024/05/29 00:31
一、设计目标:
1.采用c++模板技术,只需编写少量代码即可生成服务器
2.灵活,消息内容可以自定义,存储容量可配置
3.分布式,支持客户端和服务器之间多对多的关系
4.单机可以启动多个服务器实例
5.服务器配置简单易懂

二、使用举例

让我们先一个例子:

  1. #include "ServerContext.hpp"
  2. #include "BlockId.hpp"
  3. struct MyContext : public SocketBufferServerContext<MyContext,BlockId,unsigned int>
  4. {
  5.     typedef SocketBufferServerContext<MyContext,BlockId,unsigned int> Base;
  6.     typedef Base::Key Key;
  7.     typedef Base::Value Value;
  8.     MyContext():cmd(-1){}
  9.     static void DoUpdate(bool bInsert,Value & val,Response & response)
  10.     {
  11.         if(!bInsert)
  12.         {
  13.             val++;
  14.         }
  15.         response.appendInt(val);
  16.     }
  17.     void DoProcessCommand(int argc,int & index,char * argv[])
  18.     {
  19.         if(strcmp(argv[index],"-o") ==0 )
  20.         {
  21.             cmd = OUTPUT_COMMAND;
  22.         }
  23.     }
  24.     static void DoOutput(Key const & key,Value const & val)
  25.     {
  26.         std::cout<<key<<","<<val<<std::endl;
  27.     }
  28.     bool DoStart()
  29.     {
  30.         if(cmd == OUTPUT_COMMAND)
  31.         {
  32.             this->storage->Output();
  33.             return false;
  34.         }
  35.         return true;
  36.     }
  37. private:
  38.     int cmd;
  39. };
  40. int main(int argc,char * argv[])
  41. {
  42.     MyContext ctx;
  43.     if(!ctx.ProcessCommand(argc,argv) )
  44.     {
  45.         std::cout<<"ProcessCommand is failed/n";
  46.         return 1;
  47.     }
  48.     if(!ctx.Start() )
  49.     {
  50.         return 1;
  51.     }
  52.     return 0;
  53. }
只要几十行代码,我们就已经完成了一个服务器的编写!
服务器框架包含在ServerContext.hpp文件中,网络部分采用多线程的反应器模式(Reactor,包含在Reactor.hpp中)

原创粉丝点击