??dubbo線程模型分為IO線程和服務(wù)調(diào)用處理線程,IO線程主要是netty的線程,可以在protocol標(biāo)簽中使用iothreads配置,缺省值為處理器核數(shù)+1,服務(wù)處理線程主要是提供端netty接收到請求后,處理業(yè)務(wù)的線程,在dubbo官方文檔關(guān)于服務(wù)調(diào)用處理線程的配置如下:
<dubbo:protocol name="dubbo" dispatcher="all" threadpool="fixed" threads="100" />
重要的參數(shù)有三個(gè)dispatcher、threadpool、threads:
- dispatcher:線程分發(fā)器 all(默認(rèn))、message、direct(不派發(fā))等
- threadpool:具體處理業(yè)務(wù)的線程池
- threads:線程池線程數(shù)
??在消費(fèi)端其實(shí)都是IO線程,并不涉及到服務(wù)調(diào)用處理線程,在此不做分析,重點(diǎn)分析提供端的線程模型:netty IO線程和服務(wù)調(diào)用處理線程。
一、netty的IO線程:
@Override
protected void doOpen() throws Throwable {
//boss線程池 負(fù)責(zé)處理消費(fèi)端的鏈接
ExecutorService boss = Executors.newCachedThreadPool(new
NamedThreadFactory("NettyServerBoss", true));
//worker線程池,負(fù)責(zé)交換數(shù)據(jù)
ExecutorService worker = Executors.newCachedThreadPool(new
NamedThreadFactory("NettyServerWorker", true));
// 限制worker線程池最大線程數(shù),默認(rèn)處理器數(shù)+1
ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
...........
//綁定端口
channel = bootstrap.bind(getBindAddress());
}
boss線程接受了socket連接求后,會(huì)產(chǎn)生一個(gè)channel,此channel要與dubbo的區(qū)分開來,然后將channel交給ServerSocketChannelFactory后,又繼續(xù)接受新的請求,ServerSocketChannelFactory則會(huì)從worker線程池中找出一個(gè)worker線程來繼續(xù)處理這個(gè)請求,worker線程數(shù)可以自定義配置。
<dubbo:protocol name="dubbo" iothreads="100" port="20880"/>
二、服務(wù)調(diào)用處理線程
??當(dāng)消費(fèi)端調(diào)用請求到服務(wù)端后,netty接收到請求后初始化鏈接后,會(huì)調(diào)用NettyHandler.channelConnected()方法:
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
//獲取一個(gè)NettyChannel ctx.getChannel()為boss線程池傳遞過來的
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
try {
if (channel != null) {//沒有直接創(chuàng)建一個(gè) key: ip:port
channels.put(NetUtils.toAddressString((InetSocketAddress) ctx.getChannel().getRemoteAddress()), channel);
}
//handler為NettyHandler初始化時(shí)傳遞過來的
handler.connected(channel);
} finally {
NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
}
}
static NettyChannel getOrAddChannel(org.jboss.netty.channel.Channel ch, URL url, ChannelHandler handler) {
if (ch == null) {
return null;
}
/* 根據(jù)netty中的channel從channelMap中獲取dubbo的 NettyChannel
* org.jboss.netty.channel.Channel --> NettyChannel
* see ConcurrentMap<org.jboss.netty.channel.Channel, NettyChannel> channelMap
*/
NettyChannel ret = channelMap.get(ch);
if (ret == null) {//沒有直接初始化一個(gè),緩存到channelMap中
NettyChannel nc = new NettyChannel(ch, url, handler);
if (ch.isConnected()) {
ret = channelMap.putIfAbsent(ch, nc);
}
if (ret == null) {
ret = nc;
}
}
return ret;
}
NettyHandler.channelConnected()方法最后會(huì)調(diào)用handler.connected(channel)-->AbstractServer.connected(channel):
@Override
public void connected(Channel ch) throws RemotingException {
Collection<Channel> channels = getChannels();
if (accepts > 0 && channels.size() > accepts) {
//服務(wù)端建立的長連接超過限制,直接關(guān)閉,不再進(jìn)行下面的處理
logger.error("Close channel " + ch + ", cause: The server " + ch.getLocalAddress() + " connections greater than max config " + accepts);
ch.close();
return;
}
super.connected(ch);
}
上面的方法主要是檢查服務(wù)提供者接收的長連接數(shù)是否超出限制,消費(fèi)端建立的tcp長連接太多,建立多余的鏈接會(huì)拒絕,消費(fèi)端會(huì)接收到異常,配置的長連接不會(huì)像JDK中的線程池那樣按需來建立,而是在消費(fèi)者啟動(dòng)后就全部創(chuàng)建好。消費(fèi)端參數(shù)為connections,服務(wù)端為accepts
com.alibaba.dubbo.rpc.protocol.dubbo.DubboProtocol
private ExchangeClient[] getClients(URL url){
//是否共享連接
boolean service_share_connect = false;
int connections = url.getParameter(Constants.CONNECTIONS_KEY, 0);//從url獲取connections
//如果connections不配置,則共享連接,否則每服務(wù)每連接
if (connections == 0){
service_share_connect = true;
connections = 1;
}
ExchangeClient[] clients = new ExchangeClient[connections];
for (int i = 0; i < clients.length; i++) {//根據(jù)connections初始化
if (service_share_connect){
clients[i] = getSharedClient(url);
} else {
clients[i] = initClient(url);
}
}
return clients;
}
鏈接建立完畢之后,調(diào)用NettyHandler.messageReceived()方法:
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
//根據(jù)netty的channel取出一個(gè)dubbo的NettyChannel
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
try {
handler.received(channel, e.getMessage());//參數(shù)分別為NettyChannel RpcInvocation
} finally {//處理完成之后將channel移除
NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
}
}
handler.received()的handler為nettyServer,初始化的時(shí)候傳進(jìn)去的,進(jìn)而調(diào)用到了AbstractPeer.received():
public void received(Channel ch, Object msg) throws RemotingException {
if (closed) {
return;
}
handler.received(ch, msg);
}
上面的handler為初始化 nettyServer時(shí)設(shè)置的:
public NettyServer(URL url, ChannelHandler handler) throws RemotingException{
super(url, ChannelHandlers.wrap(handler, ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME)));
}
進(jìn)入到ChannelHandlers.wrap(.. , ..)方法,最后調(diào)用到了ChannelHandlers.wrapInternal(.. , ..),在這個(gè)方法里封裝的handler層次比較深
protected ChannelHandler wrapInternal(ChannelHandler handler, URL url) {
return new MultiMessageHandler(new HeartbeatHandler(ExtensionLoader.getExtensionLoader(Dispatcher.class)
.getAdaptiveExtension().dispatch(handler, url)));
}
先看Dispatcher這個(gè)接口:
也是通過SPI機(jī)制進(jìn)行適配的,默認(rèn)實(shí)現(xiàn)是AllDispatcher,其他實(shí)現(xiàn)對(duì)應(yīng)<dubbo:protocol />中dispatcher參數(shù):
- all 所有消息都派發(fā)到線程池,包括請求,響應(yīng),連接事件,斷開事件,心跳等。
- direct 所有消息都不派發(fā)到線程池,全部在 IO 線程上直接執(zhí)行。
- message 只有請求響應(yīng)消息派發(fā)到線程池,其它連接斷開事件,心跳等消息,直接在 IO 線程上執(zhí)行。
- execution 只請求消息派發(fā)到線程池,不含響應(yīng),響應(yīng)和其它連接斷開事件,心跳等消息,直接在 IO 線程上執(zhí)行。
- connection 在 IO 線程上,將連接斷開事件放入隊(duì)列,有序逐個(gè)執(zhí)行,其它消息派發(fā)到線程池。
看AllDispatcher默認(rèn)實(shí)現(xiàn):
/**
* 默認(rèn)的線程池配置
*
* @author chao.liuc
*/
public class AllDispatcher implements Dispatcher {
public static final String NAME = "all";
public ChannelHandler dispatch(ChannelHandler handler, URL url) {
return new AllChannelHandler(handler, url);
}
}
回到ChannelHandlers.wrapInternal(.. , ..),最終這個(gè)handler的封裝層次為:MultiMessageHandler-->HeartbeatHandler-->AllChannelHandler,MultiMessageHandler.received()如果是批量請求,依次調(diào)用下一個(gè)handler處理,HeartbeatHandler處理心跳檢測調(diào)用,下面看看AllChannelHandler.received():
public void received(Channel channel, Object message) throws RemotingException {
ExecutorService cexecutor = getExecutorService();
try {
cexecutor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
} catch (Throwable t) {
throw new ExecutionException(message, channel, getClass() + " error when process received event .", t);
}
}
private ExecutorService getExecutorService() {
ExecutorService cexecutor = executor;//AllChannelHandler初始化的時(shí)候設(shè)置的
if (cexecutor == null || cexecutor.isShutdown()) {
cexecutor = SHARED_EXECUTOR;
}
return cexecutor;
}
接著看cexecutor的初始化過程,在WrappedChannelHandler的構(gòu)造方法中:
public WrappedChannelHandler(ChannelHandler handler, URL url) {
.................................................
executor = (ExecutorService) ExtensionLoader.getExtensionLoader(ThreadPool.class).getAdaptiveExtension().getExecutor(url);
.................................................
}
此處也是spi機(jī)制,根據(jù)url中的threadpool參數(shù),適配出具體的實(shí)現(xiàn):
- CachedThreadPool:此線程池可伸縮,線程空閑一分鐘后回收,新請求重新創(chuàng)建線程
- FixedThreadPool: 此線程池啟動(dòng)時(shí)即創(chuàng)建固定大小的線程數(shù),不做任何伸縮
- LimitedThreadPool: 此線程池一直增長,直到上限,增長后不收縮
進(jìn)入默認(rèn)的FixedThreadPool:
//在Java線程池實(shí)現(xiàn)中對(duì)應(yīng) Executors.newFixedThreadPool()
public class FixedThreadPool implements ThreadPool {
public Executor getExecutor(URL url) {
String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME);
//服務(wù)調(diào)用線程數(shù)
int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);
//等待隊(duì)列里任務(wù)數(shù)
int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES);
//初始化線程池 池內(nèi)線程默認(rèn)200 等待任務(wù)使用SynchronousQueue、LinkedBlockingQueue
return new ThreadPoolExecutor(threads, threads, 0, TimeUnit.MILLISECONDS,
queues == 0 ? new SynchronousQueue<Runnable>() :
(queues < 0 ? new LinkedBlockingQueue<Runnable>()
: new LinkedBlockingQueue<Runnable>(queues)),
new NamedThreadFactory(name, true), new
//線程池資源枯竭后的處理器
AbortPolicyWithReport(name, url));
}
}
在線程池資源枯竭的時(shí)候,會(huì)調(diào)用AbortPolicyWithReport.rejectedExecution()處理,可以看到打印出了日志,并且拋出了異常,消費(fèi)端也可以接收到RpcException,因?yàn)镹ettyCodecAdapter.InternalDecoder.exceptionCaught已經(jīng)對(duì)該異常進(jìn)行了處理,直接輸出到了消費(fèi)者端
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
String msg = String.format("Thread pool is EXHAUSTED!" +
" Thread Name: %s, Pool Size: %d (active: %d, core: %d, max: %d, largest: %d), Task: %d (completed: %d)," +
" Executor status:(isShutdown:%s, isTerminated:%s, isTerminating:%s), in %s://%s:%d!" ,
threadName, e.getPoolSize(), e.getActiveCount(), e.getCorePoolSize(), e.getMaximumPoolSize(), e.getLargestPoolSize(),
e.getTaskCount(), e.getCompletedTaskCount(), e.isShutdown(), e.isTerminated(), e.isTerminating(),
url.getProtocol(), url.getIp(), url.getPort());
logger.warn(msg);
throw new RejectedExecutionException(msg);//throw exception
}
接下里回到AllChannelHandler.received(..,..),初始化一個(gè)任務(wù),丟到線程池執(zhí)行,接下來就是調(diào)用DecodeHandler.received()->HeaderExchangeHandle.received()-->ExchangeHandlerAdapter.reply()
執(zhí)行具體的業(yè)務(wù)。
new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message)
ChannelEventRunnable.run():
public void run() {
.............................
switch (state) {
case RECEIVED:
try{
handler.received(channel, message);
}catch (Exception e) {
logger.warn("ChannelEventRunnable handle " + state + " operation error, channel is " + channel
+ ", message is "+ message,e);
}
break;
.............................
}
}
參考:
http://blog.sina.com.cn/s/blog_60f11afd01010wtp.html
http://blog.csdn.net/manzhizhen/article/details/73436619