Soul网关第5天:体验代理SOFA服务

800 阅读2分钟

今天是最后一天体验Soul网关代理服务了,目前还支持代理腾讯的Tars

一、准备工作

1、启动zk

有了代理 SpringCloud 的经验,其实主要是公司用的就是 Spring 全家桶框架搭的微服务,用过 SpringCloud 才很快跑起来了,但是 SOFA 没用过,let me see see.

看了看 soul-example 中的 SOFA 服务示例代码配置文件,发现要像 Dubbo、SpringCloud 先依赖一个注册中心,SOFA 是 zookeeper

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

2、打开 SOFA 插件

有了之前的经验,插件要在两个地方打开,一个是 soul-admin 管理后台中打开;另一个是 soul-bootstrap 网关服务要依赖SOFA插件。

执行 curl http://localhost:9195/sofa/findById\?id\=1 返回空。

又到了可以提pr的地方啦^_^ !!!当 soul-bootstrap 网关服务没有依赖SOFA插件时,不报错也不打印错误日志,接口返回空,这不科学,体验不好。

定位一下错误,Soul是插件化责任链默认,所以在网关链式调用的地方 SoulWebHandler#execute 打一个断点,发现并没有SOFA插件,这不是重点,重点是要找到为什么不报错而返回空。

网关没有 SOFA 插件,但接入的请求能够处理,去哪处理了?

  1. 在第一个插件 GlobalPlugin 中,根据请求路径生成soulContext上下文中写入了后端管理系统中的元数据。

  1. soulContext 上下文已经将请求打上了 rpcType = sofa 标签,divide 插件的 rpcType = http,调过去不执行了。 DividePlugin#skip 方法
 @Override
    public Boolean skip(final ServerWebExchange exchange) {
        final SoulContext soulContext = exchange.getAttribute(Constants.CONTEXT);
        return !Objects.equals(Objects.requireNonNull(soulContext).getRpcType(), RpcTypeEnum.HTTP.getName());
    }

而 SofaPlugin 插件并没有加载进来,所以请求流量一顿插件处理后,什么也没做,返回了空。

体验 SOFA

控制台打开 SOFA 插件,在 soul-bootstrap 中添加 SOFA 插件依赖,重启。需要添加的依赖坐标详见官方文档:dromara.org/zh-cn/docs/…

大体上是 zk 客户端 、 SOFA插件 、sofa 官方依赖,zk 客户端之前体验 Dubbo 已经添加了。

       <dependency>
           <groupId>org.dromara</groupId>
           <artifactId>soul-spring-boot-starter-plugin-sofa</artifactId>
           <version>${last.version}</version>
       </dependency>
       <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>

启动 soul-example 中的 sofa 例子,执行 curl http://localhost:9195/sofa/findAll 得到结果 {"code":200,"message":"Access to success!","data":{"name":"hello world Soul Sofa , findAll","id":"278174738"}}