代码之家  ›  专栏  ›  技术社区  ›  Tlink

具有多个端点的Azure函数(Java)

  •  0
  • Tlink  · 技术社区  · 6 年前

    这里可以看到一个Azure函数的Java示例:

    /**
     * Azure Functions with HTTP Trigger.
     */
    public class Function {
        @FunctionName("HttpTrigger-Java")
        public HttpResponseMessage<String> httpHandler(
                @HttpTrigger(name = "req", methods = {"get", "post"}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
                final ExecutionContext context
        ) {
            context.getLogger().info("Java HTTP trigger processed a request.");
    
            String query = request.getQueryParameters().get("name");
            String name = request.getBody().orElse(query);
    
            if (name == null) {
                return request.createResponse(400, "Please pass a name on the query string or in the request body");
            } else {
                return request.createResponse(200, "Hello, " + name);
            }
        }
    }
    

    该示例只公开一个端点, 我了解可以使用Azure函数创建多个端点,例如:/name(执行某个方法)和执行不同方法的不同端点/id。

    我怎样才能做到这一点?

    什么是最佳实践,我理解我应该使用Azure函数 bind 注释,如何使用?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Jerry Liu Phantom    6 年前

    使用 route 性质 HttpTrigger 并将其值绑定到 路线 方法签名中的参数。然后我们可以根据传入的路由确定响应。

    @FunctionName("HttpTrigger-Java")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, route="{customRoute}", authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
            @BindingName("customRoute")String route,
            final ExecutionContext context) {
        context.getLogger().info("Java HTTP trigger processed a request.");
    
        if(route.equals("home")){
            return request.createResponseBuilder(HttpStatus.OK).body("Home route request").build();
        }
        else if(route.equals("id")){
            return request.createResponseBuilder(HttpStatus.OK).body("Id route request").build();
        }
        else{
            return request.createResponseBuilder(HttpStatus.NOT_FOUND).body("Not a valid route").build();
        }
    }
    

    此外,函数url默认为这种格式 host/api/{customRoute} . 去掉 api 前缀,集合 routePrefix 空出 host.json .

    {
      "version": "2.0",
      "extensions": {
        "http":{
          "routePrefix":""
        }
      }
    }