Solon

二、强化 Gateway 模式

</> markdown

一般可以从这几方面对 Gateway 模式进行强化:

  • 定制异常状态码
  • 定制基类
  • 将一些处理独立封装成类
  • 接口只返回数据部份,异常状态用抛

强化之后,具体的网关即简单,又功能强大。同时会对团队开发形成一定的风格和约束。

API_0(异常状态用抛)

@Component(tag = "api")
public class API_0 {
    @Mapping
    public void exec() {
        throw ApiCodes.CODE_4001011;
    }
}

API_hello_world(接口只返回数据部份)

@Component(tag = "api")
public class API_hello_world {
    @Mapping("hello")
    public String exec(String name) {
        return "Hello " + name;
    }
}

ApiGateway(将一些处理独立封装成类,简化网关)

@Mapping("/api/**")
@Component
public class ApiGateway extends ApiGatewayBase {
    @Override
    protected void register() {

        //添加个前置处理
        before(new TokenHandler());

        //添加Bean
        addBeans(bw -> "api".equals(bw.tag()));
    }
}

1、定制网关基类

/**
 * 自定义一个网关基类,对结果做了处理的转换处理
 */
public abstract class ApiGatewayBase extends Gateway {
    @Override
    public void render(Object obj, Context c) throws Throwable {
        if (c.getRendered()) {
            return;
        }

        c.setRendered(true);

        //
        // 有可能根本没数据过来
        //
        if (obj instanceof ModelAndView) {
            //如果有模板,则直接渲染
            //
            c.result = obj;
        } else {
            //如果没有按Result tyle 渲染
            //
            Result result = null;
            if (obj instanceof ApiCode) {
                //处理标准的状态码
                ApiCode apiCode = (ApiCode) obj;

                result = Result.failure(apiCode.getCode(), apiCode.getDescription());
            } else if (obj instanceof Throwable) {
                //处理未知异常
                ApiCode apiCode = ApiCodes.CODE_400;

                result = Result.failure(apiCode.getCode(), apiCode.getDescription());
            } else if (obj instanceof ONode) {
                //处理ONode数据(为兼容旧的)
                result = Result.succeed(obj);
            } else if (obj instanceof Result) {
                //处理Result结构
                result = (Result) obj;
            } else {
                //处理java bean数据(为扩展新的)
                result = Result.succeed(obj);
            }

            c.result = result;
        }


        //如果想对输出时间点做控制,可以不在这里渲染(由后置处理进行渲染)
        c.render(c.result);
    }
}

2、对比演进参考:

https://gitee.com/noear/solon_api_demo

3、其它演示参考:

https://gitee.com/noear/solon-examples/tree/main/6.Solon-Api/demo6013-step3