thrift通过TServerEventHandler获取客户端ip

用了这么久的thrift,一直不知道如何在接收端打印发送端的ip。一个笨的方法是在struct中添加字段并填充发送端的ip(或host),约定必须填充有效的ip,但这样不但增加了调用者的代码量,而且接收端还需要判断一个string字段是否为有效ip。

前段时间在网上查了一些资料,但无果。今天重新整理了这些资料,终于搞定了。

大致思路:http://web.archiveorange.com/archive/v/FzEy581cbgUiBLQh1GPv上讲的很清楚。我这里根据我的想法重复一下:

主要实现一个基类为TServerEventHandler的class,我叫它为ClientIPHandler。

1,定义一个map<uint64, string>,存放<pthread_self(), ip>。

2,在ClientIPHandler中createContext()里实现map的插入,deleteContext()实现删除。

3,定义一个成员函数,获取map的值。这个函数供你的XServiceHandler(thrift自动生成的)使用。

4,在调用serve()前,定义shared_ptr<ClientIPHandler>变量a,调用setServerEventHandler设置eventHandler_(server/TServer.h:217).

map的读写需要加锁。

部分代码

static map<uint64, std::string> thrift_client_ip;
static base::lock::Mutex mutex;

。。。

class ClientIPHandler : virtual public TServerEventHandler {
 public:
  ClientIPHandler() {
  }
  virtual ~ClientIPHandler() {
  }
  std::string GetThriftClientIp() {
    lock::MutexLock g(&mutex);
    return thrift_client_ip[pthread_self()];
  }

  virtual void preServe() {
  }
  virtual void* createContext(boost::shared_ptr<TProtocol> input,
                              boost::shared_ptr<TProtocol> output) {
    // insert when connection open
    TBufferedTransport *tbuf = dynamic_cast<TBufferedTransport *>(input->getTransport().get());
    TSocket *sock = dynamic_cast<TSocket *>(tbuf->getUnderlyingTransport().get());
    lock::MutexLock g(&mutex);
    thrift_client_ip[pthread_self()] = sock->getPeerAddress();
    return NULL;
  }
  virtual void deleteContext(void* serverContext,
                             boost::shared_ptr<TProtocol>input,
                             boost::shared_ptr<TProtocol>output) {
    // erase when connection close
    lock::MutexLock g(&mutex);
    thrift_client_ip.erase(pthread_self());
  }
  virtual void processContext(void* serverContext,
                              boost::shared_ptr<TTransport> transport) {
  }

 private:
};


 TServerEventHandler和TBufferedTransport需要相应的命名空间。 
 

据个人理解,createContext是在连接创建时调用,deleteContext是在连接断开后调用。

由于我的这些代码都写在一个.h中,所以GetThriftClientIp不适合全局函数。


至此,我们可以在XServiceHandler中调用GetThriftClientIp()来获得客户端的ip了,终于不再烦恼数据是从哪里发来的了。

猜你喜欢

转载自blog.csdn.net/hbuxiaoshe/article/details/38942869
今日推荐