我在我的Java thrift服务器上实现了TServerEventHandler
,并在那里为每个连接分配了id之类的东西。我想知道是否有办法访问从处理程序传递给processContext
的上下文,以验证例如id是否正确。
有一些简单的方法吗?
答案 0 :(得分:0)
我将字段放在threadLocal中,与ThriftServiceEventHandler一起使用。 clientIpThreadLocal.get()。它有效,但不美观。
public class ThriftServiceEventHandler implements TServerEventHandler {
public static ThreadLocal<String> clientIpThreadLocal = new ThreadLocal<>();
/**
* Called before the server begins.
*/
@Override
public void preServe() {
}
/**
* Called when a new client has connected and is about to being processing.
*/
@Override
public ServerContext createContext(TProtocol input, TProtocol output) {
TTransport inputTransport = input.getTransport();
if (inputTransport instanceof TSocket) {
TSocket tsocket = (TSocket)inputTransport;
Socket socket = tsocket.getSocket();
InetAddress inetAddress = socket.getInetAddress();
String hostAddress = inetAddress != null ? inetAddress.getHostAddress(): null;
clientIpThreadLocal.set(hostAddress);
}
return null;
}
/**
* Called when a client has finished request-handling to delete server context.
*/
@Override
public void deleteContext(ServerContext serverContext, TProtocol input, TProtocol output) {
clientIpThreadLocal.remove();
}
/**
* Called when a client is about to call the processor.
*/
@Override
public void processContext(ServerContext serverContext, TTransport inputTransport, TTransport outputTransport) {
}
}