java - Azure Function App 的异步 Java 方法?
问题描述
我目前正在创建 EventhubTriggered Java 函数应用程序,它侦听 IotHub 的默认端点。目前按照教程,我没有看到任何用于 Java 函数应用程序异步实现的示例代码,但建议对 C# 函数应用程序使用 async/await。
我应该考虑/是否可以在 Java 中为函数应用程序添加异步实现?有没有我可以参考的示例代码?我应该考虑在函数应用程序中添加并行编程/多线程逻辑吗?
解决方案
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();
}
推荐阅读
- odata - groupby 可以在 OData 中区分大小写吗?
- django-rest-framework - 如何使用队列从 on_message 回调函数跨 django 传递 MQTT 消息对象(包括主题和有效负载)?
- apache-spark - 逗号正在为列中的特定值生成单独的行,同时将表从 pyspark 集群导出到 BigQuery
- reactjs - 在 React 中从 Firebase 请求多个数据的最佳方法是什么
- azure - 使用 powershell 从 Adls gen1 下载文件不起作用
- plotly-dash - plotly dash 网页可在 Raspberry Pi 上运行,但无法通过 LAN 访问它
- snowflake-cloud-data-platform - 雪花 json_extract_path_text 不接受带空格的键
- android - OpenTok 发布者无法在后台模式下发送流视频
- java - 为什么我的 RecyclerViewAdapter 没有显示在视图中?
- c# - 使用 NCRYPT_CERTIFICATE_PROPERTY 从智能卡中删除证书对象