新聞中心
分布式應(yīng)用運(yùn)行時(shí) Dapr:萬物皆可 API
作者:張曉輝 2023-02-11 12:47:07
云計(jì)算
云原生 Dapr 是一個分布式系統(tǒng)工具包,通過提供 API 實(shí)現(xiàn)應(yīng)用程序與外圍組件的解耦合,讓開發(fā)人員更加聚焦于業(yè)務(wù)邏輯的研發(fā)。

?Dapr[1] 分布式應(yīng)用運(yùn)行時(shí) Distributed Application Runtime 的首字母縮寫。有關(guān)多運(yùn)行時(shí),可以看下 Bilgin Ibryam 的 Multi-Runtime Microservices Architecture[2],不想看英文的可以看下我之前的翻譯。
Dapr 是一個分布式系統(tǒng)工具包,通過提供 API 實(shí)現(xiàn)應(yīng)用程序與外圍組件的解耦合,讓開發(fā)人員更加聚焦于業(yè)務(wù)邏輯的研發(fā)。解耦也是與傳統(tǒng) SDK 的很大區(qū)別,能力不再是通過應(yīng)用程序中加入庫的方式提供,而是通過應(yīng)用附近的邊車(sidecar)運(yùn)行時(shí)提供(sidecar 不是廣為人知的服務(wù)網(wǎng)格 sidecar - pod 中的容器,而是廣泛使用在系統(tǒng)軟件設(shè)計(jì)中的一種模式,比如操作系統(tǒng)的 initd、日志采集組件,甚至是 Java 中的多線程。)。因此這里說的 Dapr sidecar 可能是個獨(dú)立的進(jìn)程,也可能是 pod 中的一個容器。
在 Dapr 中我們可以看到很多常見 SDK 的能力:
- 如 SpringCloud、Netflix OSS 的 服務(wù)調(diào)用[3],以及超時(shí)、熔斷、重試等 彈性策略[4]
- 如 Spring Data KeyValue 一樣提供 狀態(tài)存儲[5] 的抽象,簡化各種持久存儲的訪問
- 如 Kafka、NATS、MQTT 等消息代理,提供 發(fā)布/訂閱[6] 抽象供服務(wù)通過消息進(jìn)行通信
- 如 Kafka、MQTT、RabbitMQ 提供以事件觸發(fā)應(yīng)用的抽象:綁定[7]
- 如 Redis 一樣的 分布式鎖[8]
- 如 Consul、Kubernetes 等的 名稱解析[9]
- ...
以上能力都是通過 HTTP 和 gRPC API 暴露給應(yīng)用,這些 API 在 Dapr 中被叫做 構(gòu)建塊[10](building blocks),并且也 僅提供抽象,也就是說你可以隨意替換底層實(shí)現(xiàn)(Dapr 中也叫做 組件[11])而無需修改任何應(yīng)用代碼。
比如你的應(yīng)用需要在存儲中保存狀態(tài),在開發(fā)時(shí)可以使用 內(nèi)存[12] 作為存儲組件,其他環(huán)境中可以使用 Mysql[13]、Redis[14] 等持久化組件。
接下來,就借助官方的入門指南體驗(yàn) Dapr 的。Dapr 提供了 多種入門指南[15],這里我選了其中的 hello-kubernetes[16],但實(shí)際操作可能與官方有些許差異,也正式這些差異能讓(坑)我對 Dapr 有更多的了解。
環(huán)境
安裝 Dapr CLI
Dapr CLI 是操作 Dapr 的工具,對可以用來安裝、管理 Dapr 實(shí)例,以及進(jìn)行 debug。參考官方的 安裝文檔[17],我使用的是 macOS 選擇 homebrew 來安裝。
brew install dapr-cli
目前最新的版本是 1.9.1。
dapr version
CLI version: 1.9.1
Runtime version: n/a
創(chuàng)建 Kubernetes 集群
使用 k3s v1.23.8+k3s2 作為實(shí)驗(yàn)環(huán)境集群。
export INSTALL_K3S_VERSION=v1.23.8+k3s2
curl -sfL https://get.k3s.io | sh -s - --disable traefik --disable servicelb --write-kubeconfig-mode 644 --write-kubeconfig ~/.kube/config
安裝 Dapr
執(zhí)行下面的命令將 Dapr 安裝到集群中。
dapr init --kubernetes --wait
檢查組件是否正常運(yùn)行。在 Kubernetes 環(huán)境下,我們的很多命令都要使用 --kubernetes? 或者 -k 參數(shù)。
dapr status -k
NAME NAMESPACE HEALTHY STATUS REPLICAS VERSION AGE CREATED
dapr-dashboard dapr-system True Running 1 0.11.0 47s 2023-02-11 08:30.25
dapr-sentry dapr-system True Running 1 1.9.6 47s 2023-02-11 08:30.25
dapr-sidecar-injector dapr-system True Running 1 1.9.6 47s 2023-02-11 08:30.25
dapr-operator dapr-system True Running 1 1.9.6 47s 2023-02-11 08:30.25
dapr-placement-server dapr-system True Running 1 1.9.6 47s 2023-02-11 08:30.25
示例應(yīng)用
環(huán)境部署好之后,我們來看下要用的示例應(yīng)用。
git clone https://github.com/dapr/quickstarts
cd quickstarts/tutorials/hello-kubernetes
示例中包含了 2 個應(yīng)用 pythonapp? 和 nodeapp,以及 Redis。
- nodeapp 提供 HTTP 端點(diǎn)來創(chuàng)建和查詢訂單,訂單信息保存在 Redis 中
- pythonapp? 會持續(xù)訪問 nodeapp 的 HTTP 端點(diǎn)來創(chuàng)建訂單
用到了 Dapr 的兩個功能:服務(wù)調(diào)用和狀態(tài)存儲。
創(chuàng)建應(yīng)用命名空間
應(yīng)用將部署在 dpar-test 命名空間下。
kubectl create namespace dapr-test
狀態(tài)存儲
狀態(tài)存儲使用 Redis,先部署 Redis 到命名空間 store? 下。簡單起見,只使用單 master 節(jié)點(diǎn),并設(shè)置密碼 changeme。
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
helm install redis bitnami/redis --namespace store --create-namespace \
--set replica.replicaCount=0 \
--set auth.password=changeme
創(chuàng)建組件
由于 Redis 設(shè)置了密碼,需要為 Dapr 提供訪問 Redis 的密碼,通過 Secret 來傳遞。Secret 保存在 dapr-test 下。
kubectl create secret generic redis -n dapr-test --from-literal=redis-password=changeme
根據(jù) Redis store 規(guī)范[18] 在 dapr-test? 下創(chuàng)建組件 statetore:
- 組件類型 type 為 state.redis
- 版本 versinotallow=v1
- 訪問地址 redisHost=redis-master.store:6379
- Redis 的訪問密碼從秘鑰 redis 的鍵 redis-password 獲取
- auth.secretStore 指定秘鑰存儲的類型是 `Kubernetes`[19]
kubectl apply -n dapr-test -f - <apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: statestore
spec:
type: state.redis
version: v1
metadata:
- name: redisHost
value: redis-master.store:6379
- name: redisPassword
secretKeyRef:
name: redis
key: redis-password
auth:
secretStore: kubernetes
EOF
訪問狀態(tài)存儲
通過 Dapr API 訪問狀態(tài)存儲[20],請求格式:POST http://localhost:
下面截取了 nodeapp? 中的部分代碼,stateStoreName? 就是上面創(chuàng)建的 statestore?。應(yīng)用和組件位于同一命名空間下,直接只用 statestore?;否則,就要代碼組件所在的命名空間 storeName.storeNamespace?(由于代碼中硬編碼了組件名 statestore,所以在同命名空間下創(chuàng)建組件)。
const stateStoreName = `statestore`;
const stateUrl = `http://localhost:${daprPort}/v1.0/state/${stateStoreName}`;
const state = [{
key: "order",
value: data
}];
const response = await fetch(stateUrl, {
method: "POST",
body: JSON.stringify(state),
headers: {
"Content-Type": "application/json"
}
});
服務(wù)調(diào)用
調(diào)用方 pythonapp 的代碼。
- 通過 sidecar daprd 的地址 localhost 和端口 3500 訪問 HTTP API。
- 在請求頭中通過 dapr-app-id 指定目標(biāo)應(yīng)用 id nodeapp。應(yīng)用 id 是通過 Kubernetes 注解 dapr.io/app-id 來設(shè)置的,更多注解可參考 文檔[21]。
- 目標(biāo)方法名通過請求路徑來指定:/neworder
dapr_port = os.getenv("DAPR_HTTP_PORT", 3500)
dapr_url = "http://localhost:{}/neworder".format(dapr_port)
n = 0
while True:
n += 1
message = {"data": {"orderId": n}}
try:
response = requests.post(dapr_url, jsnotallow=message, timeout=5, headers = {"dapr-app-id": "nodeapp"} )
if not response.ok:
print("HTTP %d => %s" % (response.status_code,
response.content.decode("utf-8")), flush=True)
except Exception as e:
print(e, flush=True)
time.sleep(1)
部署應(yīng)用
kubectl apply -n dapr-test -f deploy/node.yaml
kubectl wait --for=cnotallow=ready pod -n dapr-test -l app=node --timeout=60s
kubectl apply -n dapr-test -f deploy/python.yaml
kubectl wait --for=cnotallow=ready pod -n dapr-test -l app=python --timeout=60s
檢查 node 容器的日志,可以接收到了來自 pythonapp 的請求,并成功持久化存儲了訂單。
kubectl logs -f -n dapr-test -l app=node -c node
Successfully persisted state for Order ID: 1
Got a new order! Order ID: 1
Successfully persisted state for Order ID: 2
Got a new order! Order ID: 2
Successfully persisted state for Order ID: 3
Got a new order! Order ID: 3
Successfully persisted state for Order ID: 4
Got a new order! Order ID: 4
Debug
原本官方的指南是將 Redis 和應(yīng)用部署在同一個命名空間中,加上 nodeapp 中硬編碼了存儲組件名。而我實(shí)驗(yàn)的時(shí)候講 Redis 部署在了另一個空間下,檢查 node 容器日志時(shí)看到的是:
Got a new order! Order ID: 1
Failed to persist state.
daprd 容器中,只有下面的日志。
time="2023-02-11T02:55:38.166259509Z" level=info msg="HTTP API Called: POST /v1.0/state/statestore" app_id=nodeapp instance=nodeapp-857cf6f985-jnmzw scope=dapr.runtime.http-info type=log useragent="node-fetch/1.0 (+https://github.com/bitinn/node-fetch)" ver=1.9.6
通過為 nodeapp? 的 pod 添加注解 dapr.io/log-level="debug"? 讓 daprd 容器輸出 debug 日志。
time="2023-02-11T03:05:07.663028821Z" level=debug msg="{ERR_STATE_STORE_NOT_CONFIGURED state store is not configured}" app_id=nodeapp instance=nodeapp-59b754ff54-c4x4s scope=dapr.runtime.http type=log ver=1.9.6更多 Debug 方式,參考官方的 Troubleshooting 文檔[22]。
總結(jié)
Dapr 提供了與傳統(tǒng) SDK 方式完成不同的方法來實(shí)現(xiàn)系統(tǒng)集成,讓開發(fā)者可以專注于業(yè)務(wù)邏輯,而無需考慮底層的實(shí)現(xiàn);對組織來說,應(yīng)用變得更加便攜,可以使用不同的云環(huán)境。
但是 Dapr 本身無法跨云跨集群,社區(qū)正在考慮與服務(wù)網(wǎng)格集成來實(shí)現(xiàn)混合多云環(huán)境下的服務(wù)調(diào)用,大家可以期待一下。
參考資料
[1] Dapr: https://dapr.io
[2] Multi-Runtime Microservices Architecture: https://www.infoq.com/articles/multi-runtime-microservice-architecture/
[3] 服務(wù)調(diào)用: https://docs.dapr.io/developing-applications/building-blocks/service-invocation/
[4] 彈性策略: https://docs.dapr.io/operations/resiliency/policies/
[5] 狀態(tài)存儲: https://docs.dapr.io/developing-applications/building-blocks/state-management/
[6] 發(fā)布/訂閱: https://docs.dapr.io/developing-applications/building-blocks/pubsub/
[7] 綁定: https://docs.dapr.io/developing-applications/building-blocks/bindings/
[8] 分布式鎖: https://docs.dapr.io/developing-applications/building-blocks/distributed-lock/distributed-lock-api-overview/
[9] 名稱解析: https://docs.dapr.io/reference/components-reference/supported-name-resolution/
[10] 構(gòu)建塊: https://docs.dapr.io/concepts/building-blocks-concept/
[11] 組件: https://docs.dapr.io/concepts/components-concept/
[12] 內(nèi)存: https://docs.dapr.io/reference/components-reference/supported-state-stores/setup-inmemory/
[13] Mysql: https://docs.dapr.io/reference/components-reference/supported-state-stores/setup-mysql/
[14] Redis: https://docs.dapr.io/reference/components-reference/supported-state-stores/setup-redis/
[15] 多種入門指南: https://github.com/dapr/quickstarts/tree/master/tutorials
[16] hello-kubernetes: https://github.com/dapr/quickstarts/tree/master/tutorials/hello-kubernetes
[17] 安裝文檔: https://docs.dapr.io/getting-started/install-dapr-cli/
[18] Redis store 規(guī)范: https://docs.dapr.io/reference/components-reference/supported-state-stores/
[19] Kubernetes?: https://docs.dapr.io/reference/components-reference/supported-secret-stores/kubernetes-secret-store/
[20] Dapr API 訪問狀態(tài)存儲: https://docs.dapr.io/reference/api/state_api/#save-state
[21] 文檔: https://docs.dapr.io/reference/arguments-annotations-overview/
[22] Troubleshooting 文檔: https://docs.dapr.io/operations/troubleshooting/
當(dāng)前文章:分布式應(yīng)用運(yùn)行時(shí)Dapr:萬物皆可API
文章位置:http://www.dlmjj.cn/article/cdphjjg.html


咨詢
建站咨詢
