我想使用Netflix-Ribbon作为没有Spring Cloud的TCP客户端负载平衡器,并且编写测试代码。
public class App implements Runnable
{
public static String msg = "hello world";
public BaseLoadBalancer lb;
public RxClient<ByteBuf, ByteBuf > client;
public Server echo;
App(){
lb = new BaseLoadBalancer();
echo = new Server("localhost", 8000);
lb.setServersList(Lists.newArrayList(echo));
DefaultClientConfigImpl impl = DefaultClientConfigImpl.getClientConfigWithDefaultValues();
client = RibbonTransport.newTcpClient(lb, impl);
}
public static void main( String[] args ) throws Exception
{
for( int i = 40; i > 0; i--)
{
Thread t = new Thread(new App());
t.start();
t.join();
}
System.out.println("Main thread is finished");
}
public String sendAndRecvByRibbon(final String data)
{
String response = "";
try {
response = client.connect().flatMap(new Func1<ObservableConnection<ByteBuf, ByteBuf>,
Observable<ByteBuf>>() {
public Observable<ByteBuf> call(ObservableConnection<ByteBuf, ByteBuf> connection) {
connection.writeStringAndFlush(data);
return connection.getInput();
}
}).timeout(1, TimeUnit.SECONDS).retry(1).take(1)
.map(new Func1<ByteBuf, String>() {
public String call(ByteBuf ByteBuf) {
return ByteBuf.toString(Charset.defaultCharset());
}
})
.toBlocking()
.first();
}
catch (Exception e) {
System.out.println(((LoadBalancingRxClientWithPoolOptions) client).getMaxConcurrentRequests());
System.out.println(lb.getLoadBalancerStats());
}
return response;
}
public void run() {
for (int i = 0; i < 200; i++) {
sendAndRecvByRibbon(msg);
}
}
}
我发现即使
sendAndRecvByRibbon
设置为true,每次调用poolEnabled
都会创建一个新的套接字。所以,这让我感到困惑,我想念什么吗?并且没有配置池大小的选项,但是有一个
PoolMaxThreads
和MaxConnectionsPerHost
。我的问题是如何在我的简单代码中使用连接池,而
sendAndRecvByRibbon
有什么问题,它打开一个套接字然后仅使用一次,我该如何重用连接?感谢您的时间。该服务器只是用pyhton3编写的简单回显服务器,我将
conn.close()
注释掉,因为我想使用长连接。import socket
import threading
import time
import socketserver
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
conn = self.request
while True:
client_data = conn.recv(1024)
if not client_data:
time.sleep(5)
conn.sendall(client_data)
# conn.close()
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
if __name__ == "__main__":
HOST, PORT = "localhost", 8000
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
ip, port = server.server_address
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
server.serve_forever()
和mevan的pom,我只是在IED的自动生成的POM中添加了两个依赖项。
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>com.netflix.ribbon</groupId>
<artifactId>ribbon</artifactId>
<version>2.2.2</version>
</dependency>
打印src_port的代码
@Sharable
public class InHandle extends ChannelInboundHandlerAdapter {
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(ctx.channel().localAddress());
super.channelRead(ctx, msg);
}
}
public class Pipeline implements PipelineConfigurator<ByteBuf, ByteBuf> {
public InHandle handler;
Pipeline() {
handler = new InHandle();
}
public void configureNewPipeline(ChannelPipeline pipeline) {
pipeline.addFirst(handler);
}
}
并将
client = RibbonTransport.newTcpClient(lb, impl);
更改为Pipeline pipe = new Pipeline();client = RibbonTransport.newTcpClient(lb, pipe, impl, new DefaultLoadBalancerRetryHandler(impl));
最佳答案
因此,您的App()
构造函数将对lb / client / etc进行初始化。
然后,通过在第一个for循环中调用new App()
,用40个不同的RxClient实例(每个实例默认都有自己的池)启动40个不同的线程。为了清楚起见,在这里生成多个RxClient实例的方式不允许它们共享任何公共池。尝试改用一个RxClient实例。
如果您像下面那样更改主要方法,该方法会停止创建额外的套接字吗?
public static void main( String[] args ) throws Exception
{
App app = new App() // Create things just once
for( int i = 40; i > 0; i--)
{
Thread t = new Thread(()->app.run()); // pass the run()
t.start();
t.join();
}
System.out.println("Main thread is finished");
}
如果上述方法不能完全解决问题(至少会减少40倍的已创建套接字数),请您说明一下如何确定:
我发现每次调用sendAndRecvByRibbon都会创建一个新的套接字
并在此行中更新构造函数后,您的测量结果是什么:
DefaultClientConfigImpl impl = DefaultClientConfigImpl.getClientConfigWithDefaultValues();
impl.set(CommonClientConfigKey.PoolMaxThreads,1); //Add this one and test
更新
是的,查看
sendAndRecvByRibbon
似乎不希望通过调用close
将PooledConnection标记为no longer acquired,一旦您不希望再读取它。只要您期望唯一的一次读取事件,只需更改此行
connection.getInput()
到
return connection.getInput().zipWith(Observable.just(connection), new Func2<ByteBuf, ObservableConnection<ByteBuf, ByteBuf>, ByteBuf>() {
@Override
public ByteBuf call(ByteBuf byteBuf, ObservableConnection<ByteBuf, ByteBuf> conn) {
conn.close();
return byteBuf;
}
});
请注意,如果您要设计基于TCP的更复杂的协议,则可以分析输入的bytebuf以查找特定的“通信结束”符号,该符号指示可以将连接返回到池中。