前言

ServerCnxnFactory负责与客户端的连接。

初始化

org.apache.zookeeper.server.quorum.QuorumPeerMain#runFromConfig

启动

org.apache.zookeeper.server.quorum.QuorumPeer#start

ServerCnxnFactory类

继承关系

1
public abstract class ServerCnxnFactory {}

属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// sessionMap is used to speed up closeSession()
protected final ConcurrentMap<Long, ServerCnxn> sessionMap =
new ConcurrentHashMap<Long, ServerCnxn>();

/**
* The buffer will cause the connection to be close when we do a send.
*/
static final ByteBuffer closeConn = ByteBuffer.allocate(0);

protected SaslServerCallbackHandler saslServerCallbackHandler;
public Login login;
protected ZooKeeperServer zkServer;
private final Map<ServerCnxn, ConnectionBean> connectionBeans
= new ConcurrentHashMap<ServerCnxn, ConnectionBean>();

protected final HashSet<ServerCnxn> cnxns = new HashSet<ServerCnxn>();

抽象方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public abstract int getLocalPort();

public abstract Iterable<ServerCnxn> getConnections();

public abstract void closeSession(long sessionId);

public abstract void configure(InetSocketAddress addr,
int maxClientCnxns) throws IOException;

/** Maximum number of connections allowed from particular host (ip) */
public abstract int getMaxClientCnxnsPerHost();

/** Maximum number of connections allowed from particular host (ip) */
public abstract void setMaxClientCnxnsPerHost(int max);

public abstract void startup(ZooKeeperServer zkServer)
throws IOException, InterruptedException;

public abstract void join() throws InterruptedException;

public abstract void shutdown();

public abstract void start();

public abstract void closeAll();

public abstract InetSocketAddress getLocalAddress();

createFactory()构造方法

可以通过环境变量设置使用哪个实现类

环境变量:

ZOOKEEPER_SERVER_CNXN_FACTORY = “zookeeper.serverCnxnFactory”;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
static public ServerCnxnFactory createFactory() throws IOException {
String serverCnxnFactoryName =
System.getProperty(ZOOKEEPER_SERVER_CNXN_FACTORY);
if (serverCnxnFactoryName == null) { // 没有设置环境变量就使用NIO
serverCnxnFactoryName = NIOServerCnxnFactory.class.getName();
}
try {
// 反射生成对象
ServerCnxnFactory serverCnxnFactory = (ServerCnxnFactory) Class.forName(serverCnxnFactoryName)
.getDeclaredConstructor().newInstance();
LOG.info("Using {} as server connection factory", serverCnxnFactoryName);
return serverCnxnFactory;
} catch (Exception e) {
IOException ioe = new IOException("Couldn't instantiate "
+ serverCnxnFactoryName);
ioe.initCause(e);
throw ioe;
}
}

实现类

目前3.4.10版本实现类有

org.apache.zookeeper.server.NIOServerCnxnFactory
org.apache.zookeeper.server.NettyServerCnxnFactory