一个RPC方法中需要知道客户端的IP要怎么实现?
网上看了一堆关于thrift获取获取client ip的文章,基本都要自己写一个TServerEventHandler或TProcessor来实现。如下,所有的文章讲到的都是这两种方法。
虽然没有再深入研究,但我想如果用thrift这应该是正确的办法。
但是看着好烦呐,不就获取个ip么,就没有更简单点的办法?
说明一下:我的项目中并没有直接调用 thrift API,我用是facebook/swift来做RPC框架的,服务端用Nifty(a Netty NIO-based thrift server)实现的。
研究了Niffy代码发现,获取客户端IP相当简单,示例如下:
import java.net.SocketAddress;
...
import com.facebook.nifty.core.ConnectionContext;
import com.facebook.nifty.core.RequestContext;
import com.facebook.nifty.core.RequestContexts;
...
// RPC接口方法
@Override
public PersonBean savePerson(PersonBean bean)throws ServiceRuntimeException {
//...业务代码
// 获取当前的请求上下文
RequestContext ctx = RequestContexts.getCurrentContext();
// 获取连接上下文
ConnectionContext connect = ctx.getConnectionContext();
// 获取IP地址
SocketAddress address = connect.getRemoteAddress();
System.out.println(address);
//...业务代码
}
...
另附上基于nifty的thrift server初始化代码片段
public static final int DEFAULT_PORT = 26411;
private final ExecutorService executor;
private final ThriftServer server;
private final int serverPort;
private final ThriftServiceProcessor processor;
public Server(List<?> services,int serverPort,ExecutorService executor) {
checkArgument(null != services && !services.isEmpty());
this.serverPort = serverPort>0? serverPort : DEFAULT_PORT;
this.executor = checkNotNull(executor);
processor = new ThriftServiceProcessor(
new ThriftCodecManager(),ImmutableList.<ThriftEventHandler>of(),services
);
ThriftServerDef serverDef = ThriftServerDef.newBuilder()
.listen(serverPort)
.withProcessor(processor)
.using(this.executor)
.build();
NettyServerConfig serverConfig = NettyServerConfig.newBuilder()
.setBossThreadExecutor(this.executor)
.setWorkerThreadExecutor(this.executor)
.build();
server = new ThriftServer(serverConfig,serverDef);
}