[Soul 源碼之旅] 1.8 Soul插件初體驗 (Sofa )

SOFARPC 是螞蟻金服開源的一款基于 Java 實現的 RPC 服務框架,為應用之間提供遠程服務調用能力,具有高可伸縮性,高容錯性,目前螞蟻金服所有的業務的相互間的 RPC 調用都是采用 SOFARPC。SOFARPC 為用戶提供了負載均衡,流量轉發,鏈路追蹤,鏈路數據透傳,故障剔除等功能。

1.8.3.1SOFARPC 配置流程

首先我們在Client 端需要加入 sofaRpc 和 soul-sofa 的依賴。

       <dependency>
           <groupId>com.alipay.sofa</groupId>
           <artifactId>rpc-sofa-boot-starter</artifactId>
           <version>${rpc-sofa-boot-starter.version}</version>
       </dependency>
       <dependency>
           <groupId>org.dromara</groupId>
           <artifactId>soul-spring-boot-starter-client-sofa</artifactId>
           <version>${soul.version}</version>
       </dependency>

我們使用 zk 作為 sofaRpc 的注冊中心,所以需要做如下配置。

com:
 alipay:
   sofa:
     rpc:
       registry-address: zookeeper://127.0.0.1:2181
       bolt-port: 8888

sofaRpc 需要定義一個 xml 文件類似于 dubbo.xml 配置暴露的服務。

    <sofa:service ref="sofaSingleParamService" interface="org.dromara.soul.examples.sofa.api.service.SofaSingleParamService">
        <sofa:binding.bolt/>
    </sofa:service>

    <sofa:service ref="sofaMultiParamService" interface="org.dromara.soul.examples.sofa.api.service.SofaMultiParamService">
        <sofa:binding.bolt/>
    </sofa:service>

最后我們在各個 SofaRpc 服務中加入 @SoulSofaClient 注解即可,這里定義了服務的訪問路徑,當我們注冊成功后就會在 zookeeper 中發現如下服務。并且 soul admin 也會有對應的路徑。


zookeeper

admin

同時我們需要在 soul bootstrap 引入 sofa-plugin 依賴和 zookeeper 的依賴。

1.8.3.2 sofa 插件詳解

還是按慣用流程我們先到 SofaPluginConfiguration ,它定義了 sofaRpc 在 Boostrap 中處理類。其中主要的信息有 BodyParamPlugin SofaPlugin & SofaResponsePlugin 。我們先看一下 BodyParamPlugin, BodyParamPlugin 的getOrder 方法如下,這就是類似于聲明一個前置處理器,根據我們之前的經驗,先看 execute 方法。

    public int getOrder() {
        return PluginEnum.SOFA.getCode() - 1;
    }

excute 主要是根據請求類型,進行參數封裝,分為 application/json 和 x-www-form-urlencoded。

    @Override
    public Mono<Void> execute(final ServerWebExchange exchange, final SoulPluginChain chain) {
        final ServerHttpRequest request = exchange.getRequest();
        // 獲取上下文
        final SoulContext soulContext = exchange.getAttribute(Constants.CONTEXT);
        if (Objects.nonNull(soulContext) && RpcTypeEnum.SOFA.getName().equals(soulContext.getRpcType())) {
            MediaType mediaType = request.getHeaders().getContentType();
            ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
            // 判斷請求參數類型-》application/json
            if (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType)) {
                return body(exchange, serverRequest, chain);
            }
            // x-www-form-urlencoded 類型
            if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(mediaType)) {
                return formData(exchange, serverRequest, chain);
            }
            return query(exchange, serverRequest, chain);
        }
        return chain.execute(exchange);
    }

body 就是將 serverRequest 中的body 內容放到交換區 exchange 中,然后執行下一個 plugin 即 sofaplugin

    private Mono<Void> body(final ServerWebExchange exchange, final ServerRequest serverRequest, final SoulPluginChain chain) {
        return serverRequest.bodyToMono(String.class)
                .switchIfEmpty(Mono.defer(() -> Mono.just(""))) //  為空則使用空字符串
                .flatMap(body -> {
                    exchange.getAttributes().put(Constants.SOFA_PARAMS, body); // 將body 塞入 sofa_param
                    // 執行以下一個插件 即 sofaplugin
                    return chain.execute(exchange);
                });
    }

sofaplugin 的 excute 上節已經解析過,即先匹配條件是否符合 然后執行插件的 doexecute 方法。我們看看 doExecute 方法,我們可以看到最后它調用的是 sofaProxyService 的 genericInvoker , 嗯有點 dubbo 泛化調用的意思了。

    @Override
    protected Mono<Void> doExecute(final ServerWebExchange exchange, final SoulPluginChain chain, final SelectorData selector, final RuleData rule) {
        // 取出參數
        String body = exchange.getAttribute(Constants.SOFA_PARAMS);
        // 取出上下文對象
        SoulContext soulContext = exchange.getAttribute(Constants.CONTEXT);
        assert soulContext != null;
        MetaData metaData = exchange.getAttribute(Constants.META_DATA);
        // 校驗元數據
        if (!checkMetaData(metaData)) {
            assert metaData != null;
            log.error(" path is :{}, meta data have error.... {}", soulContext.getPath(), metaData.toString());
            exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            Object error = SoulResultWrap.error(SoulResultEnum.META_DATA_ERROR.getCode(), SoulResultEnum.META_DATA_ERROR.getMsg(), null);
            return WebFluxResultUtils.result(exchange, error);
        }
        // 檢測是否為空
        if (StringUtils.isNoneBlank(metaData.getParameterTypes()) && StringUtils.isBlank(body)) {
            exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            Object error = SoulResultWrap.error(SoulResultEnum.SOFA_HAVE_BODY_PARAM.getCode(), SoulResultEnum.SOFA_HAVE_BODY_PARAM.getMsg(), null);
            return WebFluxResultUtils.result(exchange, error);
        }
        // 調用 sofaProxyService 獲取返回結果
        final Mono<Object> result = sofaProxyService.genericInvoker(body, metaData, exchange);
        return result.then(chain.execute(exchange));
    }

其主要代碼如下,sofa 的調用和 dubbo 調用類似,就是通過泛化調用的方式進行調用,然后將返回結果放到交換區。

     public Mono<Object> genericInvoker(final String body, final MetaData metaData, final ServerWebExchange exchange) throws SoulException {
        // 構造 genericService
        GenericService genericService = reference.refer();
        Pair<String[], Object[]> pair;
       // 構造參數   
        pair = sofaParamResolveService.buildParameter(body, metaData.getParameterTypes());
        CompletableFuture<Object> future = new CompletableFuture<>();
        RpcInvokeContext.getContext().setResponseCallback(new SofaResponseCallback<Object>() {
            @Override
            public void onAppResponse(final Object o, final String s, final RequestBase requestBase) {
                // 通知future獲取結果
                future.complete(o);
            }
        });
        // 真正調用服務
        genericService.$genericInvoke(metaData.getMethodName(), pair.getLeft(), pair.getRight());
        return Mono.fromFuture(future.thenApply(ret -> {
            // 獲取到真正結果
            GenericObject genericObject = (GenericObject) ret;
            // 將結果寫入交換區
            exchange.getAttributes().put(Constants.SOFA_RPC_RESULT, genericObject.getFields());
            // 設置狀態
            exchange.getAttributes().put(Constants.CLIENT_RESPONSE_RESULT_TYPE, ResultEnum.SUCCESS.getName());
            return ret;
        })).onErrorMap(SoulException::new);
    }

我們最后看一下 SofaResponsePlugin 插件,其主要是doexecute 方法

    @Override
    public Mono<Void> execute(final ServerWebExchange exchange, final SoulPluginChain chain) {
        return chain.execute(exchange).then(Mono.defer(() -> {
            final Object result = exchange.getAttribute(Constants.SOFA_RPC_RESULT); // 獲取返回結果
            if (Objects.isNull(result)) {  // 結果為空則改為錯誤
                Object error = SoulResultWrap.error(SoulResultEnum.SERVICE_RESULT_ERROR.getCode(), SoulResultEnum.SERVICE_RESULT_ERROR.getMsg(), null);
                return WebFluxResultUtils.result(exchange, error);
            }
            Object success = SoulResultWrap.success(SoulResultEnum.SUCCESS.getCode(), SoulResultEnum.SUCCESS.getMsg(), JsonUtils.removeClass(result)); // 構造成功結果
            return WebFluxResultUtils.result(exchange, success);//返回結果
        }));
    }

至此,整個請求的流程就走完了。

1.8.3.3 總結

在這節里我們學習了 soul 集成 sofaRpc 的流程,sofaRpc 的整個流程和 Dubbo 的非常像,稍微有區別是參數的構造這方面。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容