Thrift第六课 异常日志处理和客户端信息IP地址获取
  TEZNKK3IfmPf 2023年11月14日 41 0

1)异常日志打印

默认Thrift日志输出到屏幕,但可以让它输出到自己的日志文件中。这个功能通过全局对象apache::thrift::GlobalOutput来实现,在Thrift.h中声明了GlobalOutput,它的定义在Thrift.cpp文件中。

类TOutput提供了方法setOutputFunction()用来设置日志输出函数:


class TOutput
{

  
public:

     
 inline void setOutputFunction(void (*function)(const char *));};

例子
void WriteThriftLog(const char* pszLog)
{
 MyLog(pszLog);
}
apache::thrift::GlobalOutput.setOutputFunction(WriteThriftLog);

 

2)客户端信息IP地址获取

struct TConnectionInfo {
  // The input and output protocols
  boost::shared_ptr<protocol::TProtocol> input;
  boost::shared_ptr<protocol::TProtocol> output;
  // The underlying transport used for the connection
  // This is the transport that was returned by TServerTransport::accept(),
  // and it may be different than the transport pointed to by the input and
  // output protocols.
  boost::shared_ptr<transport::TTransport> transport;
};
该结构体中input保存了客户端的IP地址和端口

TBufferedTransport *tbuf = dynamic_cast<TBufferedTransport *>(input->getTransport().get());
TSocket *sock = dynamic_cast<TSocket *>(tbuf->getUnderlyingTransport().get());
int nPort = sock->getPeerPort();
std::string strIP = sock->getPeerAddress();

class ProcessorFactoryImp : public TProcessorFactory
{
 virtual boost::shared_ptr<TProcessor> getProcessor(const TConnectionInfo &conninfo)
 {
  return boost::make_shared<UploadMessageServiceProcessor>(boost::make_shared<UploadMessageServiceHandler>(conninfo.transport, conninfo.input));
 }
};
在这里将conninfo.input传递给UploadMessageServiceHandler作为参数,就可以直接获取到客户端的IP地址和端口
class UploadMessageServiceHandler : virtual public UploadMessageServiceIf {
public:

 UploadMessageServiceHandler(const boost::shared_ptr<TTransport> &trans, const boost::shared_ptr<protocol::TProtocol> &input)
  : m_socketClient(boost::make_shared<TBinaryProtocol>(trans))
  {
  }
}
UploadMessageServiceHandler就是客户端的处理逻辑代码

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

TEZNKK3IfmPf