基於 dapr cron binding 實現定時任務

這兩天在開發中的一個功能需要用到定時任務,正好最近準備更多使用 dapr,於是想到這個經常重複編寫的代碼看是否可以讓 dapr 代勞,瞭解之後發現可以通過 cron binding 實現,動手之後輕鬆搞定,寫博文記錄一下(基於 kubernetes 部署環境)。

基於 dapr cron binding 實現定時任務的原理很簡單,就是應用無需關心定時,只需暴露執行任務的 api 給 dapr sidecar 調用,定時交由 daprd 處理。

比如我們要實現每天早上 9 點進行文章導入的定時任務,首先在應用中暴露 api

[ApiController]
[ApiVersionNeutral]public class ImportController : ControllerBase{
    [Route("import-articles")]    public async Task<IActionResult> Articles()
    {        //...
    }
}

然後定義 dapr bindings.cron 組件清單

apiVersion: dapr.io/v1alpha1kind: Componentmetadata:
  name: import-articles
  namespace: productionspec:
  type: bindings.cron
  version: v1
  metadata:
  - name: schedule
    value: '0 1 * * *'scopes:- brands-api

如果想查看 cron binding 的調度日誌,需要將 daprd 日誌級別改爲 debug,修改方法是在應用的 deployment 中添加 dapr.io/log-level: debug

spec:
  template:
    metadata:
      annotations:
        dapr.io/app-id: brands-api
        dapr.io/enabled: "true"
        dapr.io/log-level: debug

然後通過 kubectl logs 命令查看日誌

kubectl logs --since 5m deploy/brands-api daprd

日誌輸出如下

time="2022-08-16T04:22:15.192224084Z" level=debug msg="name: import-articles, next run: 44.80779615s" app_id=brands-api instance=brands-api-84b4768b66-rb879 scope=dapr.contrib type=log ver=1.8.3
time="2022-08-16T04:23:00.001030337Z" level=debug msg="name: import-articles, schedule fired: 2022-08-16 04:23:00.000953098 +0000 UTC m=+50.266709169" app_id=brands-api instance=brands-api-84b4768b66-rb879 scope=dapr.contrib type=log ver=1.8.3

需要注意的地方:

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/9ybK7Vqn3U_bQs__Jn7TJw