我是靠谱客的博主 听话书本,最近开发中收集的这篇文章主要介绍Soul网关源码学习【第四篇】-sofa示例,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

sofa示例演示

什么是sofa

sofa是一个高可扩展性、高性能、生产级的 Java RPC 框架。在蚂蚁金服 SOFARPC 已经经历了十多年及五代版本的发展。SOFARPC 致力于简化应用之间的 RPC 调用,为应用提供方便透明、稳定高效的点对点远程服务调用方案。为了用户和开发者方便的进行功能扩展,SOFARPC 提供了丰富的模型抽象和可扩展接口,包括过滤器、路由、负载均衡等等。同时围绕 SOFARPC 框架及其周边组件提供丰富的微服务治理方案。

功能特性

  • 透明化、高性能的远程服务调用
  • 支持多种服务路由及负载均衡策略
  • 支持多种注册中心的集成
  • 支持多种协议,包括 Bolt、Rest、Dubbo 等
  • 支持同步、单向、回调、泛化等多种调用方式
  • 支持集群容错、服务预热、自动故障隔离
  • 强大的扩展功能,可以按需扩展各个功能组件
Soul网关对于sofa的支持
  1. 在我们网关的项目soul-bootstrap中增加如下依赖:
    	   <dependency>
               <groupId>com.alipay.sofa</groupId>
               <artifactId>sofa-rpc-all</artifactId>
               <version>5.7.6</version>
           </dependency>
           <dependency>
               <groupId>org.apache.curator</groupId>
               <artifactId>curator-client</artifactId>
               <version>4.0.1</version>
           </dependency>
           <dependency>
               <groupId>org.apache.curator</groupId>
               <artifactId>curator-framework</artifactId>
               <version>4.0.1</version>
           </dependency>
           <dependency>
               <groupId>org.apache.curator</groupId>
               <artifactId>curator-recipes</artifactId>
               <version>4.0.1</version>
           </dependency>
           <dependency>
               <groupId>org.dromara</groupId>
               <artifactId>soul-spring-boot-starter-plugin-sofa</artifactId>
               <version>${last.version}</version>
           </dependency>
    
  2. 在我们的后台管理系统开启sofa插件
    • 首先在 soul-admin 插件管理中,把sofa 插件设置为开启。
    • 其次在 sofa 插件中配置你的注册地址或者其他注册中心的地址.
      {"protocol":"zookeeper","register":"127.0.0.1:2181"}
      
sofa示例项目:soul-examples-sofa
  1. 引入Soul的依赖
        <dependency>
           <groupId>org.dromara</groupId>
           <artifactId>soul-spring-boot-starter-client-sofa</artifactId>
           <version>${soul.version}</version>
       </dependency>
    
  2. 配置Soul,在yml文件中新增如下配置
     soul:
       sofa:
         adminUrl: http://localhost:9095
         contextPath: /sofa
         appName: sofa
      # adminUrl: 为你启动的soul-admin 项目的ip + 端口,注意要加 http://
      # contextPath: 为你的这个项目在soul网关的路由前缀,这个你应该懂意思把? 比如/order ,/product 等等,网关会根据你的这个前缀来进行路由.
      # appName:你的应用名称,不配置的话,会默认取sofa配置中application 中的名称
    
  3. 接口注册到网关
    你sofa服务实现类的,方法上加上 @SoulSofaClient 注解,表示该接口方法注册到网关。
  4. 启动示例项目,输出日志 sofa client register success,且sofa接口已经发布到 soul网关,大功告成。
调试

通过Debug跟踪调用方法,可以发现存在以下的调用链

SoulWebHandler.execute() --> AbstractSoulPlugin.execute() --> SofaPlugin.doExecute() --> SofaProxyService.genericInvoker() --> 调用到我们定义的方法。

前面两步就不看了,是Soul匹配插件的一个过程,我们从SofaPlugin.doExecute()开始看。

  • 首先获取Body,里面是我们的参数(如果有参数的话)
  • 然后拿到我们注册的MetaData,里面就是我们的方法。
    在这里插入图片描述
  • 如果MetaData为空,或者MateData里面的ServiceName和methodName为空,就返回错误。
  • 如果参数类型不为空,但是Body为空,就返回错误。
  • 调用SofaProxyService,返回相应。
    @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);
        }
        final Mono<Object> result = sofaProxyService.genericInvoker(body, metaData, exchange);
        return result.then(chain.execute(exchange));
    }

接下来我们再看以下sofa代理类怎么处理的。

  • 首先就是拿到reference,里面有调用的类和方法名,以及参数等信息。
  • 非空校验
  • 通过RpcInvokeContext调用我们的服务接口,返回一个Mono。

    在debug中看到这里调用的是这个类,也就是我们所定义方法类的接口。
    org.dromara.soul.examples.dubbo.api.service.DubboTestService

	/**
     * Generic invoker object.
     *
     * @param body     the body
     * @param metaData the meta data
     * @param exchange the exchange
     * @return the object
     * @throws SoulException the soul exception
     */
    public Mono<Object> genericInvoker(final String body, final MetaData metaData, final ServerWebExchange exchange) throws SoulException {
        ConsumerConfig<GenericService> reference = ApplicationConfigCache.getInstance().get(metaData.getPath());
        if (Objects.isNull(reference) || StringUtils.isEmpty(reference.getInterfaceId())) {
            ApplicationConfigCache.getInstance().invalidate(metaData.getServiceName());
            reference = ApplicationConfigCache.getInstance().initRef(metaData);
        }
        GenericService genericService = reference.refer();
        Pair<String[], Object[]> pair;
        if (null == body || "".equals(body) || "{}".equals(body) || "null".equals(body)) {
            pair = new ImmutablePair<>(new String[]{}, new Object[]{});
        } else {
            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.complete(o);
            }

            @Override
            public void onAppException(final Throwable throwable, final String s, final RequestBase requestBase) {
                future.completeExceptionally(throwable);
            }

            @Override
            public void onSofaException(final SofaRpcException e, final String s, final RequestBase requestBase) {
                future.completeExceptionally(e);
            }
        });
        genericService.$invoke(metaData.getMethodName(), pair.getLeft(), pair.getRight());
        return Mono.fromFuture(future.thenApply(ret -> {
            if (Objects.isNull(ret)) {
                ret = Constants.SOFA_RPC_RESULT_EMPTY;
            }
            exchange.getAttributes().put(Constants.SOFA_RPC_RESULT, ret);
            exchange.getAttributes().put(Constants.CLIENT_RESPONSE_RESULT_TYPE, ResultEnum.SUCCESS.getName());
            return ret;
        })).onErrorMap(SoulException::new);
    }
记录一个坑(个人感觉是个Bug)
  • 现象
    启动soul-admin,网关soul-bootstrap,以及我们的sofa项目soul-examples-sofa。顺利启动,没有报错,并且我们的Soul网关顺利的将sofa插件的选择器和元数据都注册上来了。
    在这里插入图片描述
    在这里插入图片描述
    但是。。。我们访问网关的时候任何反应都没有。。。连报错信息也没有。
    在这里插入图片描述
  • 问题点
    后面通过阅读Soul的官方文档发现是我的网关里没有添加sofa的依赖,把sofa的依赖加入到网关,重启就OK了。
小节

今天所分享的只是Soul的大的处理思路,具体细节的实现需要掌握很多只是,今天顺便了解了以下响应式编程。
Soul采用的响应式编程,对于响应式编程不是很清楚,可以参照下面一篇文章:使用 Reactor 进行反应式编程

最后

以上就是听话书本为你收集整理的Soul网关源码学习【第四篇】-sofa示例的全部内容,希望文章能够帮你解决Soul网关源码学习【第四篇】-sofa示例所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部