sofa-rpc源码解析-服务端netty启动过程

  1. 创建server
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    //ServerConfig.java

    public synchronized Server buildIfAbsent() {
    if (server != null) {
    return server;
    }
    // 提前检查协议+序列化方式
    // ConfigValueHelper.check(ProtocolType.valueOf(getProtocol()),
    // SerializationType.valueOf(getSerialization()));

    server = ServerFactory.getServer(this);
    return server;
    }

如果不存在则创建,关键在于ServerFactory的getServer方法

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
28
29
30

/**
* 全部服务端
*/

private final static ConcurrentHashMap<String, Server> SERVER_MAP = new ConcurrentHashMap<String, Server>();

public synchronized static Server getServer(ServerConfig serverConfig) {
try {
Server server = SERVER_MAP.get(Integer.toString(serverConfig.getPort()));
if (server == null) {
// 算下网卡和端口
resolveServerConfig(serverConfig);

ExtensionClass<Server> ext = ExtensionLoaderFactory.getExtensionLoader(Server.class)
.getExtensionClass(serverConfig.getProtocol());
if (ext == null) {
throw ExceptionUtils.buildRuntime("server.protocol", serverConfig.getProtocol(),
"Unsupported protocol of server!");
}
server = ext.getExtInstance();
server.init(serverConfig);
SERVER_MAP.put(serverConfig.getPort() + "", server);
}
return server;
} catch (SofaRpcRuntimeException e) {
throw e;
} catch (Throwable e) {
throw new SofaRpcRuntimeException(e.getMessage(), e);
}
}

getServer默认返回的是一个BoltServer

2.启动server

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
DefaultProviderBootstrap.java
for (ServerConfig serverConfig : serverConfigs) {

try {
Server server = serverConfig.buildIfAbsent();
// 注册序列化接口
server.registerProcessor(providerConfig, providerProxyInvoker);
if (serverConfig.isAutoStart()) {
server.start();
}
} catch (SofaRpcRuntimeException e) {
throw e;
} catch (Exception e) {
LOGGER.errorWithApp(appName, "Catch exception when register processor to server: "
+ serverConfig.getId(), e);
}
}


//BoltServer.java
@Override
public void start() {
if (started) {
return;
}
synchronized (this) {
if (started) {
return;
}
// 生成Server对象
remotingServer = initRemotingServer();
try {
if (remotingServer.start(serverConfig.getBoundHost())) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Bolt server has been bind to {}:{}", serverConfig.getBoundHost(),
serverConfig.getPort());
}
} else {
throw new SofaRpcRuntimeException("Failed to start bolt server, see more detail from bolt log.");
}
started = true;

if (EventBus.isEnable(ServerStartedEvent.class)) {
EventBus.post(new ServerStartedEvent(serverConfig, bizThreadPool));
}

} catch (SofaRpcRuntimeException e) {
throw e;
} catch (Exception e) {
throw new SofaRpcRuntimeException("Failed to start bolt server!", e);
}
}
}

protected RemotingServer initRemotingServer() {
// 绑定到端口
RemotingServer remotingServer = new RpcServer(serverConfig.getPort());
remotingServer.registerUserProcessor(boltServerProcessor);
return remotingServer;
}
  • 启动过程使用了双重检查机制,防止Server重复启动
  • initRemotingServer方法里初始化了netty的一些配置,跟到代码里可以看到我们通常启动一个netty服务端需要的bossGroup(workerGroup在初始化过程里doInit方法里设置好)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    //RpcServer.java ->sofa-bolt项目
    private static final NioEventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2, new NamedThreadFactory("Rpc-netty-server-worker"));

    public RpcServer(int port) {
    super(port);
    this.globalSwitch = new GlobalSwitch();
    this.connectionEventListener = new ConnectionEventListener();
    this.userProcessors = new ConcurrentHashMap(4);
    this.bossGroup = new NioEventLoopGroup(1, new NamedThreadFactory("Rpc-netty-server-boss"));
    }
  • 启动:

    1
    2
    3
    4
    protected boolean doStart(String ip) throws InterruptedException {
    this.channelFuture = this.bootstrap.bind(new InetSocketAddress(ip, this.port)).sync();
    return this.channelFuture.isSuccess();
    }

标准的netty服务端启动模板代码