我想在没有Spring Cloud的情况下使用Netflix-Ribbon作为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));
答案 0 :(得分:2)
因此,您的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
来将Python: How to turn a dictionary of Dataframes into one big dataframe with column names being the key of the previous dict?标记为PooledConnection,一旦您不希望再读到它。
只要您期望唯一的一次读取事件,只需更改此行
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的更复杂的协议,则可以分析输入的字节缓冲区以查找您的特定“通信结束”符号,该符号指示可以将连接返回到池中。