microservice-sdk

微服务Serverless化SDK项目

一、microservice-sdk-functionclient

1.1 项目介绍

在FunctionGraph平台部署Serverless化的微服务后,为了让用户更好地调用该微服务的相关方法,设计实现函数调用SDK(以下称SDK),提供用户类似本地调用方法的开发套件。

在传统的Java程序中,如果需要调用一个目标对象的目标方法,可直接本地调用:

public class Target {
    public String doSomeThings(int a, String b) {
    }
}

public class Local {
    public void test() {
        // 本地调用
        Target target = new Target();
        String ret = target.doSomeThings(1, "str");
    }
}

当目标对象以及目标方法部署FunctionGraph平台的Serverless函数之后,则不能再使用这种本地调用的方式。则只能去触发函数的API触发器等方式来调用,调用过程稍显麻烦。

因此,提供SDK来简化这种调用,如:

public class Local {
    public void test() {
        // SDK调用
        FunctionClient client = FunctionClient.newBuilder().build();
        FunctionRequest<String> req = new FunctionRequest<>("/myFunc", "myService", "myMethod", String.class, new Object[]{1, "str"});
        String ret = client.invoke(req);
    }
}

1.2 如何使用

1.2.1 引入Maven依赖坐标

如果是SpringBoot微服务,引入:

<dependency>
    <groupId>org.yuanrong.m2s</groupId>
    <artifactId>microservice-sdk-functionclient-starter</artifactId>
    <version>1.0.0</version>
</dependency>

否则,引入:

<dependency>
    <groupId>org.yuanrong.m2s</groupId>
    <artifactId>microservice-sdk-functionclient</artifactId>
    <version>1.0.0</version>
</dependency>

1.2.2 使用functionclient调用Serverless函数的指定方法

提示:

使用functionclient调用Serverless函数的前提是,先在Serverless函数的里将被调用的Service、Method通过@FunctionService、@FunctionHandler注解暴露出来。

以LiveData平台通过API触发器调用为例:

// 通过LiveData函数平台API Endpoint、appCode鉴权信息构建FunctionClient
FunctionClient functionClient = FunctionClient.newBuilder()
    .withApiEndpoint("https://apigw-beta.apache.com/api")
    .withAppCredential(new AppCredential("org.apache.demo", "******"))
    .build();

// 通过指定的Serverless函数(API网关触发器地址,如:/demo)Service、Method、返回值类型,Method实参列表,构建请求对象
Object[] invokeArgs = {"aaa", 123};
FunctionRequest<String> req = new FunctionRequest<>("/demo", "myService", "myMethod", String.class, invokeArgs);

// 调用函数
String ret = functionClient.invoke(req);

1.2.3 使用functionclient传递实参之外的数据

使用functionclient调用Serverless函数时,除了函数实参还希望传递某些自定义字段。

在functionclient侧,可以通过withParameters()设置需要传递的字段:

Object[] invokeArgs = {"aaa", 123};
FunctionRequest<String> req = new FunctionRequest<>("/demo", "myService", "myMethod", String.class, invokeArgs);

// 定义透传字段
Map<String, String> params = new HashMap<>();
params.put("foo", "bar");

// 设置透传字段到请求对象
req.addExtraParams(params);

这些字段会以请求头的方式传递到Serverless函数中,因此,在Serverless函数侧,可以在Filter使用HttpServletRequest来获取这些字段:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    // 获取透传过来的字段
    Enumeration<String> bar = req.getHeaders("foo");
    chain.doFilter(request, response);
}