sofa-bolt 远程调用

一、概述

soft-bolt提供了同步、Future、CallBack调用,大概调用流程如下图:


image.png

二、同步调用

同步调用示例代码:

public class MyClient {
    private static RpcClient client;
​
    public static void start() {
        // 创建 RpcClient 实例
        client = new RpcClient();
        // 初始化 netty 客户端:此时还没有真正的与 netty 服务端进行连接
        client.init();
    }
​
    public static void main(String[] args) throws RemotingException, InterruptedException {
        MyClient.start();
        // 构造请求体
        RaftRequest request = new RaftRequest();
        request.setContent("hello, bolt-server");
​
        // 同步调用
        RaftResponse response = (RaftResponse) client.invokeSync("127.0.0.1:8888", request, 30 * 1000);
        System.out.println("result = " + response);
    }
}

在分析soft-bolt的调用过程之前,首先有了解一下InvokeFuture的结构:

public class DefaultInvokeFuture implements InvokeFuture {
    // 请求唯一id
    private int                      invokeId;
    // listener
    private InvokeCallbackListener   callbackListener;
    // 提供给callback机制
    private InvokeCallback           callback;
    // 响应信息
    private volatile ResponseCommand responseCommand;
    // 设置响应信息的时候,调用countDown()方法
    private final CountDownLatch     countDownLatch          = new CountDownLatch(1);
    // 是否调用过callback
    private final AtomicBoolean      executeCallbackOnlyOnce = new AtomicBoolean(false);
    // 超时任务
    private Timeout                  timeout;
    // 异常
    private Throwable                cause;
    // 协议类型
    private byte                     protocol;
    // 调用上下文
    private InvokeContext            invokeContext;
}

从Client端发起同步调用,调用实现如下:

public Object invokeSync(Url url, Object request, InvokeContext invokeContext, int timeoutMillis)throws RemotingException{
    // 获取Connection(底层是使用netty框架)
    final Connection conn = getConnectionAndInitInvokeContext(url, invokeContext);
    this.connectionManager.check(conn);
    // 发起远程调用
    return this.invokeSync(conn, request, invokeContext, timeoutMillis);
}

client先获取到与server端的连接,获取的连接以后调用invokeSync()发起远程调用,最终调用的BaseRemoting.invokeSync实现如下:

    protected RemotingCommand invokeSync(final Connection conn, final RemotingCommand request,
                                         final int timeoutMillis) throws RemotingException,
                                                                 InterruptedException {
        // 将请求相关信息封装为InvokeFuture                                                           
        final InvokeFuture future = createInvokeFuture(request, request.getInvokeContext());
        // 将InvokeFuture添加到请求容器                                                           
        conn.addInvokeFuture(future);
        try {
            conn.getChannel().writeAndFlush(request).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    // 如果请求失败,填充InvokeFuture失败响应
                    if (!f.isSuccess()) {
                        conn.removeInvokeFuture(request.getId());
                        future.putResponse(commandFactory.createSendFailedResponse(
                            conn.getRemoteAddress(), f.cause()));
                        logger.error("Invoke send failed, id={}", request.getId(), f.cause());
                    }
                }
            });
        } catch (Exception e) {
            // 发生异常,填充InvokeFuture异常响应
            conn.removeInvokeFuture(request.getId());
            if (future != null) {
                future.putResponse(commandFactory.createSendFailedResponse(conn.getRemoteAddress(), e));
            }
            logger.error("Exception caught when sending invocation, id={}", request.getId(), e);
        }
        RemotingCommand response = future.waitResponse(timeoutMillis);
        // 如果超时以后,响应为空,设置超时响应                                                          
        if (response == null) {
            conn.removeInvokeFuture(request.getId());
            response = this.commandFactory.createTimeoutResponse(conn.getRemoteAddress());
            logger.warn("Wait response, request id={} timeout!", request.getId());
        }
​
        return response;
    }

如果请求正常发送到服务端,并且服务端正常处理并响应,那么在客户端收到响应以后,就会将响应信息设置到对应的InvokeFuture中,具体实现如下:

public class RpcResponseRpcResponseProcessorProcessor extends AbstractRemotingProcessor<RemotingCommand> {
​
    public void doProcess(RemotingContext ctx, RemotingCommand cmd) {
        // 获取Connection
        Connection conn = ctx.getChannelContext().channel().attr(Connection.CONNECTION).get();
        // 从容器中,获取到InvokeFuture
        InvokeFuture future = conn.removeInvokeFuture(cmd.getId());
        ClassLoader oldClassLoader = null;
        try {
            if (future != null) {
                if (future.getAppClassLoader() != null) {
                    oldClassLoader = Thread.currentThread().getContextClassLoader();
                    Thread.currentThread().setContextClassLoader(future.getAppClassLoader());
                }
                // 设置响应信息
                future.putResponse(cmd);
                // 取消超时定时任务
                future.cancelTimeout();
                try {
                    // 执行callback逻辑,下面callback调用会进行分析
                    future.executeInvokeCallback();
                } catch (Exception e) {
                    logger.error("Exception caught when executing invoke callback, id={}", cmd.getId(), e);
                }
            } else {
                logger.warn("Cannot find InvokeFuture, maybe already timeout, id={}, from={} ",
                        cmd.getId(), RemotingUtil.parseRemoteAddress(ctx.getChannelContext().channel()));
            }
        } finally {
            if (null != oldClassLoader) {
                Thread.currentThread().setContextClassLoader(oldClassLoader);
            }
        }
    }
}

soft-bolt中,通过RpcResponseProcessor类来处理响应,主要逻辑是从请求容器中获取InvokeFuture,并调用putResponse方法设置响应信息,取消超时定时任务。如果设置了callback,调用callback逻辑。

三、Future调用

Future调动示例如下:

public class MyClient {
    private static RpcClient client;
​
    public static void start() {
        // 创建 RpcClient 实例
        client = new RpcClient();
        client.init();
    }
​
    public static void main(String[] args) throws RemotingException, InterruptedException {
        MyClient.start();
        // 构造请求体
        RaftRequest request = new RaftRequest();
        request.setContent("hello, bolt-server");
        // 发起future调用
        RpcResponseFuture future = client.invokeWithFuture("127.0.0.1:8888", request, 30 * 1000);
        System.out.println("result = " + future.get());
    }
}

Future调用逻辑和同步调用逻辑类似,只不过Future调用是将InvokeFuture对象返回,并将InvokeFuture封装为RpcResponseFuture返回给用户,RpcResponseFuture结构如下:

public class RpcResponseFuture {
    private InvokeFuture future;
  
    public boolean isDone() {
        return this.future.isDone();
    }
    // 获取响应,设置超时时间
    public Object get(int timeoutMillis) throws InvokeTimeoutException, RemotingException,
                                        InterruptedException {
        this.future.waitResponse(timeoutMillis);
        if (!isDone()) {
            throw new InvokeTimeoutException("Future get result timeout!");
        }
        ResponseCommand responseCommand = (ResponseCommand) this.future.waitResponse();
        responseCommand.setInvokeContext(this.future.getInvokeContext());
        return RpcResponseResolver.resolveResponseObject(responseCommand, addr);
    }
    // 获取响应
    public Object get() throws RemotingException, InterruptedException {
        ResponseCommand responseCommand = (ResponseCommand) this.future.waitResponse();
        responseCommand.setInvokeContext(this.future.getInvokeContext());
        return RpcResponseResolver.resolveResponseObject(responseCommand, addr);
    }
}

四、Callback调用

callback调用示例如下:

public class MyClient {
    private static RpcClient client;
​
    public static void start() {
        // 创建 RpcClient 实例
        client = new RpcClient();
        client.init();
    }
​
    public static void main(String[] args) throws RemotingException, InterruptedException {
        MyClient.start();
        // 构造请求体
        RaftRequest request = new RaftRequest();
        request.setContent("hello, bolt-server");
        // callback调用 
        client.invokeWithCallback("127.0.0.1:8888", request, new InvokeCallback() {
            @Override
            public void onResponse(Object result) {
                System.out.println("result = " + result);
            }
            // 处理异常
            @Override
            public void onException(Throwable e) {
                System.out.println(e);
            }
            // 获取executor,可以为callback设置单独的线程池
            @Override
            public Executor getExecutor() {
                return null;
            }
        }, 30 * 1000);
      
        Thread.sleep(1000 * 60);
    }
}

关于callback的调用逻辑逻辑上与同步操作基本一致,在服务端处理请求以后,客户端的RpcResponseProcessor对响应信息进行处理,并调用InvokeFuture.executeInvokeCallback,具体实现如下:

public void executeInvokeCallback() {
    if (callbackListener != null) {
        // 通过cas机制,保证callback逻辑只执行一次
        if (this.executeCallbackOnlyOnce.compareAndSet(false, true)) {
            // 调用 callback逻辑
            callbackListener.onResponse(this);
        }
    }
}

上面的代码中通过cas机制,保证了callback只执行一次,callback调用逻辑具体如下:

public void onResponse(InvokeFuture future) {
    InvokeCallback callback = future.getInvokeCallback();
    if (callback != null) {
        // 封装成任务
        CallbackTask task = new CallbackTask(this.getRemoteAddress(), future);
        // 获取callback的线程池,如果不为空,在线程池中去执行callback逻辑
        if (callback.getExecutor() != null) {
            try {
                callback.getExecutor().execute(task);
            } catch (RejectedExecutionException e) {
                logger.warn("Callback thread pool busy.");
            }
        } else {
            // 在netty的work线程中执行callback逻辑
            task.run();
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,829评论 1 331
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,603评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,846评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,600评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,780评论 3 272
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,695评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,136评论 2 293
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,862评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,453评论 0 229
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,942评论 2 233
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,347评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,790评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,293评论 3 221
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,839评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,448评论 0 181
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,564评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,623评论 2 249

推荐阅读更多精彩内容

  • 简介摘要SOFARPC服务调用创建服务引用配置ConsumerConfig,自定义设置接口名称、调用协议、直连调用...
    鋒Nic阅读 9,339评论 1 7
  • 雅思口语最实用最全面7分干货 本文帮助过众多万年5.5考鸭得到6或6.5甚至7分,在紧张到大脑缺氧的考场里,你看的...
    雅思简化课堂阅读 457评论 0 1
  • 通俗讲解傅里叶级数 【原文:http://wenku.baidu.com/view/a8cb3548336c1eb...
    崔冬明阅读 386评论 0 0
  • 转载:https://www.jianshu.com/p/2a65912b56f7 iOS中延迟执行和取消的几种方...
    月沉眠love阅读 2,443评论 0 0
  • 《山海经》里传说有一种以食梦为生的神兽。人们说把它的摆件挂在床头可以帮你吃掉不好的恶梦,让你一夜安稳睡到天...
    温浩先森阅读 280评论 1 1