我有 4 个容器,配置如下 ( docker-compose.yml):
version: '3'
networks:
my-ntwk:
ipam:
config:
- subnet: 172.20.0.0/24
services:
f-app:
image: f-app
tty: true
container_name: f-app
hostname: f-app.info.my
ports:
- "22:22"
networks:
my-ntwk:
ipv4_address: 172.20.0.5
extra_hosts:
- "f-db.info.my:172.20.0.6"
- "p-app.info.my:172.20.0.7"
- "p-db.info.my:172.20.0.8"
depends_on:
- f-db
- p-app
- p-db
f-db:
image: f-db
tty: true
container_name: f-db
hostname: f-db.info.my
networks:
my-ntwk:
ipv4_address: 172.20.0.6
p-app:
image: p-app
tty: true
container_name: p-app
hostname: p-app.info.my
networks:
my-ntwk:
ipv4_address: 172.20.0.7
p-db:
image: p-db
tty: true
container_name: prod-db
hostname: …Run Code Online (Sandbox Code Playgroud) 我需要连接到 4 台机器并从套接字读取数据。我选择使用 nio2 的异步模型。
这是一个伪代码:
class Connector {
private final AsynchronousChannelGroup group;
private final String host;
private final int port
//...
public void connect() {
try (AsynchronousSocketChannel client = AsynchronousSocketChannel.open(group)) {
client.connect(new InetSocketAddress(host(), port())).get(5, TimeUnit.SECONDS);
if (!group.isShutdown()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
client.read(buffer, 5, TimeUnit.SECONDS, new Attachement(buffer), new ReadHandler(client)); //#1
}
} catch (Exception e) {
//
}
}
private class ReadHandler implements CompletionHandler<Integer, Attachement> {
final AsynchronousSocketChannel channel;
@Override
public void completed(Integer result, Attachement attachment) {
attachment.buffer.clear();
channel.read(attachment.buffer, …Run Code Online (Sandbox Code Playgroud)