首页 > 解决方案 > Azure Function App 的异步 Java 方法?

问题描述

我目前正在创建 EventhubTriggered Java 函数应用程序,它侦听 IotHub 的默认端点。目前按照教程,我没有看到任何用于 Java 函数应用程序异步实现的示例代码,但建议对 C# 函数应用程序使用 async/await。

我应该考虑/是否可以在 Java 中为函数应用程序添加异步实现?有没有我可以参考的示例代码?我应该考虑在函数应用程序中添加并行编程/多线程逻辑吗?

https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs-trigger?tabs=java#example

https://docs.microsoft.com/en-us/java/api/com.microsoft.azure.functions.annotation.eventhubtrigger?view=azure-java-stable

标签: javaazureazure-functions

解决方案


Java 没有 async/await 但它有reactive/webflux

当您创建默认项目 azure 函数时,它应该与响应式一起打包,因此您只需要以响应式方式进行调用。

因此,假设您想对外部源进行一些调用,您的代码将如下所示

public Mono<ResponseEntity<WishlistDto>> getList(String profileId, String listId) {
    return service.getWishList(profileId, listId)
            .map(w -> ResponseEntity.ok().body(DtoMapper.convertToDto(w, true)))
            .defaultIfEmpty(ResponseEntity.notFound().build());
}

但我建议您尽可能多地使用输入/输出绑定

 @FunctionName("DocByIdFromQueryString")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req",
              methods = {HttpMethod.GET, HttpMethod.POST},
              authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> request,
            @CosmosDBInput(name = "database",
              databaseName = "ToDoList",
              collectionName = "Items",
              id = "{Query.id}",
              partitionKey = "{Query.partitionKeyValue}",
              connectionStringSetting = "Cosmos_DB_Connection_String")
            Optional<String> item,
            final ExecutionContext context) 

在这种情况下,您无需过多担心响应式,因为您的函数会在一切准备就绪后立即启动,java sdk 会处理它

另一个使用输出绑定的例子

@FunctionName("sbtopicsend")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
            @ServiceBusTopicOutput(name = "message", topicName = "mytopicname", subscriptionName = "mysubscription", connection = "ServiceBusConnection") OutputBinding<String> message,
            final ExecutionContext context) {
        
        String name = request.getBody().orElse("Azure Functions");

        message.setValue(name);
        return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();
        
    }

推荐阅读