在 Blob 触发的 Azure 函数中针对特定错误实现重试机制 - java

问题描述 投票:0回答:1

我有一个blob触发的Azure函数,我想实现一个重试机制来处理函数在执行过程中由于特定错误而失败的场景。

要求如下:

  • 遇到特定错误时,该函数应自动重试处理相同的 blob。
  • 我不想手动将文件重新加载到容器中以重新触发该功能。

如何在 Azure Functions 中设置这样的重试机制?

任何指导或示例将不胜感激!

各个触发器扩展的内置重试行为

azure azure-functions spring-cloud-function
1个回答
0
投票

按照以下步骤在 Java Azure Function 中设置重试机制:

  1. 使用下面的代码配置重试策略,处理功能代码中的错误并在遇到特定错误时抛出异常。这将根据配置的策略触发重试机制,请参阅MSDOC

代码片段:

public class BlobTriggerJava {
    @FunctionName("BlobTriggerJava")
    @StorageAccount("storageConnection")
    @FixedDelayRetry(maxRetryCount = 4, delayInterval = "00:00:10")
    public void run(
        @BlobTrigger(name = "content", path = "testkp/{name}", dataType = "binary") byte[] content,
        @BindingName("name") String name,
        final ExecutionContext context
    ) {
        context.getLogger().info("Processing blob: " + name);
        try {
            if (name.contains("error")) {
                throw new Exception("Simulated error");
            }
        } catch (Exception e) {
            context.getLogger().severe("Error processing blob: " + e.getMessage());
            throw new RuntimeException(e);
        }    }
}
  1. host.json
    文件中定义重试策略,用于控制 Azure Function 的隐式重试。例如,您可以使用固定延迟或指数退避策略进行重试,请参阅 @JesseSquireMSDOCSO 答案

主机.json:

{  
  "version": "2.0",  
  "extensions": {  
    "blobs": {  
      "poisonBlobThreshold": 1,  
      "maxDegreeOfParallelism": 4  
  }  
  },  
  "retry": {  
    "strategy": "fixedDelay",  
    "maxRetryCount": 3,  
    "delayInterval": "00:00:10"  
  }  
}

控制台输出:

Functions:

    BlobTriggerJava: blobTrigger

For detailed output, run func with --verbose flag.
[2024-12-23T07:35:43.571Z] Host lock lease acquired by instance ID '000000000000000000000000F72731CC'.
[2024-12-23T07:35:46.945Z] Executing 'Functions.BlobTriggerJava' (Reason='New blob detected(LogsAndContainerScan): test/Hello World.txt', Id=b2ee3ba8-fc36-46ae-b8f5-31fc8e95201a)
[2024-12-23T07:35:46.947Z] Trigger Details: MessageId: 440a3afb-45a5-44a3-8b01-1ebe946874e6, DequeueCount: 1, InsertedOn: 2024-12-23T07:35:42.000+00:00, BlobCreated: 2024-12-23T06:47:20.000+00:00, BlobLastModified: 2024-12-23T06:56:54.000+00:00
[2024-12-23T07:35:47.236Z] Processing blob: Hello World.txt
[2024-12-23T07:35:47.236Z] Function "BlobTriggerJava" (Id: b2ee3ba8-fc36-46ae-b8f5-31fc8e95201a) invoked by Java Worker
[2024-12-23T07:35:47.262Z] Executed 'Functions.BlobTriggerJava' (Succeeded, Id=b2ee3ba8-fc36-46ae-b8f5-31fc8e95201a, Duration=1341ms)
© www.soinside.com 2019 - 2024. All rights reserved.