Client

介绍

Dapr客户端允许您与Dapr Sidecar进行通信,并访问其面向客户端的功能,例如发布事件,调用输出绑定,状态管理,机密管理等等。

先决条件

安装和导入 Dapr 的 JS SDK

  1. 使用 npm 安装 SDK:
  1. npm i @dapr/dapr --save
  1. 导入类库:
  1. import { DaprClient, DaprServer, HttpMethod, CommunicationProtocolEnum } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1"; // Dapr Sidecar Host
  3. const daprPort = "3500"; // Dapr Sidecar Port of this Example Server
  4. const serverHost = "127.0.0.1"; // App Host of this Example Server
  5. const serverPort = "50051"; // App Port of this Example Server
  6. // HTTP Example
  7. const client = new DaprClient({ daprHost, daprPort });
  8. // GRPC Example
  9. const client = new DaprClient({ daprHost, daprPort, communicationProtocol: CommunicationProtocolEnum.GRPC });

运行

要运行这些示例,您可以使用两种不同的协议与 Dapr Sidecar 进行交互:HTTP(默认)或 gRPC。

使用 HTTP(默认)

  1. import { DaprClient } from "@dapr/dapr";
  2. const client = new DaprClient({ daprHost, daprPort });
  1. # Using dapr run
  2. dapr run --app-id example-sdk --app-protocol http -- npm run start
  3. # or, using npm script
  4. npm run start:dapr-http

使用 gRPC

由于 HTTP 是默认设置,因此必须调整通信协议才能使用 gRPC。 您可以通过向客户端或服务器构造函数传递一个额外的参数来做到这一点。

  1. import { DaprClient, CommunicationProtocol } from "@dapr/dapr";
  2. const client = new DaprClient({ daprHost, daprPort, communicationProtocol: CommunicationProtocol.GRPC });
  1. # Using dapr run
  2. dapr run --app-id example-sdk --app-protocol grpc -- npm run start
  3. # or, using npm script
  4. npm run start:dapr-grpc

环境变量

Dapr Sidecar 终端点

您可以使用 DAPR_HTTP_ENDPOINTDAPR_GRPC_ENDPOINT 环境变量分别设置 Dapr Sidecar 的 HTTP 和 gRPC 终端。 当这些变量被设置时,daprHostdaprPort不需要在构造函数的选项参数中设置,客户端会自动从提供的端点中解析出它们。

  1. import { DaprClient, CommunicationProtocol } from "@dapr/dapr";
  2. // Using HTTP, when DAPR_HTTP_ENDPOINT is set
  3. const client = new DaprClient();
  4. // Using gRPC, when DAPR_GRPC_ENDPOINT is set
  5. const client = new DaprClient({ communicationProtocol: CommunicationProtocol.GRPC });

如果环境变量已设置,但是daprHostdaprPort的值被传递给构造函数,后者将优先于环境变量。

Dapr API 令牌

您可以使用 DAPR_API_TOKEN 环境变量来设置 Dapr API 令牌。 当这个变量被设置时,daprApiToken不需要在构造函数的选项参数中设置,客户端会自动获取它。

通用

增加 Body 大小

您可以通过使用DaprClient的选项来增加应用程序与侧车通信时使用的主体大小。

  1. import { DaprClient, CommunicationProtocol } from "@dapr/dapr";
  2. // Allow a body size of 10Mb to be used
  3. // The default is 4Mb
  4. const client = new DaprClient({
  5. daprHost,
  6. daprPort,
  7. communicationProtocol: CommunicationProtocol.HTTP,
  8. maxBodySizeMb: 10,
  9. });

代理请求

通过代理请求,我们可以利用 Dapr 的 sidecar 架构带来的独特功能,如服务发现、日志记录等,使我们能够立即”升级”我们的 gRPC 服务。 gRPC代理的这个特性在社区讨论41中进行了演示。

创建代理

要执行gRPC代理,只需调用client.proxy.create()方法创建一个代理:

  1. // As always, create a client to our dapr sidecar
  2. // this client takes care of making sure the sidecar is started, that we can communicate, ...
  3. const clientSidecar = new DaprClient({ daprHost, daprPort, communicationProtocol: CommunicationProtocol.GRPC });
  4. // Create a Proxy that allows us to use our gRPC code
  5. const clientProxy = await clientSidecar.proxy.create<GreeterClient>(GreeterClient);

我们现在可以调用在我们的GreeterClient接口中定义的方法(在这个例子中是来自Hello World example

幕后原理(技术工作)

架构

  1. gRPC 服务在 Dapr 中启动。 我们通过 --app-port 告诉 Dapr 这个 gRPC 服务器运行在哪个端口,并使用 --app-id <APP_ID_HERE> 给它一个唯一的 Dapr 应用程序 ID
  2. 现在我们可以通过一个客户端来调用 Dapr Sidecar,该客户端将连接到 Sidecar
  3. 在调用 Dapr Sidecar 时,我们提供一个名为 dapr-app-id 的元数据键,其值为我们在 Dapr 中启动的 gRPC 服务器的名称(例如,在我们的示例中为 server
  4. Dapr 现在会将调用转发到配置的 gRPC 服务器

构建块

JavaScript 客户端 SDK 允许您与所有Dapr 构建块 专注于客户端到 Sidecar 功能。

调用 API

调用服务

  1. import { DaprClient, HttpMethod } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1";
  3. const daprPort = "3500";
  4. async function start() {
  5. const client = new DaprClient({ daprHost, daprPort });
  6. const serviceAppId = "my-app-id";
  7. const serviceMethod = "say-hello";
  8. // POST Request
  9. const response = await client.invoker.invoke(serviceAppId, serviceMethod, HttpMethod.POST, { hello: "world" });
  10. // POST Request with headers
  11. const response = await client.invoker.invoke(
  12. serviceAppId,
  13. serviceMethod,
  14. HttpMethod.POST,
  15. { hello: "world" },
  16. { headers: { "X-User-ID": "123" } },
  17. );
  18. // GET Request
  19. const response = await client.invoker.invoke(serviceAppId, serviceMethod, HttpMethod.GET);
  20. }
  21. start().catch((e) => {
  22. console.error(e);
  23. process.exit(1);
  24. });

有关服务调用的完整指南,请访问操作方法: 调用服务

状态管理 API

保存、获取和删除应用程序状态

  1. import { DaprClient } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1";
  3. const daprPort = "3500";
  4. async function start() {
  5. const client = new DaprClient({ daprHost, daprPort });
  6. const serviceStoreName = "my-state-store-name";
  7. // Save State
  8. const response = await client.state.save(
  9. serviceStoreName,
  10. [
  11. {
  12. key: "first-key-name",
  13. value: "hello",
  14. metadata: {
  15. foo: "bar",
  16. },
  17. },
  18. {
  19. key: "second-key-name",
  20. value: "world",
  21. },
  22. ],
  23. {
  24. metadata: {
  25. ttlInSeconds: "3", // this should override the ttl in the state item
  26. },
  27. },
  28. );
  29. // Get State
  30. const response = await client.state.get(serviceStoreName, "first-key-name");
  31. // Get Bulk State
  32. const response = await client.state.getBulk(serviceStoreName, ["first-key-name", "second-key-name"]);
  33. // State Transactions
  34. await client.state.transaction(serviceStoreName, [
  35. {
  36. operation: "upsert",
  37. request: {
  38. key: "first-key-name",
  39. value: "new-data",
  40. },
  41. },
  42. {
  43. operation: "delete",
  44. request: {
  45. key: "second-key-name",
  46. },
  47. },
  48. ]);
  49. // Delete State
  50. const response = await client.state.delete(serviceStoreName, "first-key-name");
  51. }
  52. start().catch((e) => {
  53. console.error(e);
  54. process.exit(1);
  55. });

有关状态操作的完整列表,请访问 操作方法:获取和保存状态.

查询状态:

  1. import { DaprClient } from "@dapr/dapr";
  2. async function start() {
  3. const client = new DaprClient({ daprHost, daprPort });
  4. const res = await client.state.query("state-mongodb", {
  5. filter: {
  6. OR: [
  7. {
  8. EQ: { "person.org": "Dev Ops" },
  9. },
  10. {
  11. AND: [
  12. {
  13. EQ: { "person.org": "Finance" },
  14. },
  15. {
  16. IN: { state: ["CA", "WA"] },
  17. },
  18. ],
  19. },
  20. ],
  21. },
  22. sort: [
  23. {
  24. key: "state",
  25. order: "DESC",
  26. },
  27. ],
  28. page: {
  29. limit: 10,
  30. },
  31. });
  32. console.log(res);
  33. }
  34. start().catch((e) => {
  35. console.error(e);
  36. process.exit(1);
  37. });

Pub/Sub API

发布消息

  1. import { DaprClient } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1";
  3. const daprPort = "3500";
  4. async function start() {
  5. const client = new DaprClient({ daprHost, daprPort });
  6. const pubSubName = "my-pubsub-name";
  7. const topic = "topic-a";
  8. // Publish message to topic as text/plain
  9. // Note, the content type is inferred from the message type unless specified explicitly
  10. const response = await client.pubsub.publish(pubSubName, topic, "hello, world!");
  11. // If publish fails, response contains the error
  12. console.log(response);
  13. // Publish message to topic as application/json
  14. await client.pubsub.publish(pubSubName, topic, { hello: "world" });
  15. // Publish a JSON message as plain text
  16. const options = { contentType: "text/plain" };
  17. await client.pubsub.publish(pubSubName, topic, { hello: "world" }, options);
  18. // Publish message to topic as application/cloudevents+json
  19. // You can also use the cloudevent SDK to create cloud events https://github.com/cloudevents/sdk-javascript
  20. const cloudEvent = {
  21. specversion: "1.0",
  22. source: "/some/source",
  23. type: "example",
  24. id: "1234",
  25. };
  26. await client.pubsub.publish(pubSubName, topic, cloudEvent);
  27. // Publish a cloudevent as raw payload
  28. const options = { metadata: { rawPayload: true } };
  29. await client.pubsub.publish(pubSubName, topic, "hello, world!", options);
  30. // Publish multiple messages to a topic as text/plain
  31. await client.pubsub.publishBulk(pubSubName, topic, ["message 1", "message 2", "message 3"]);
  32. // Publish multiple messages to a topic as application/json
  33. await client.pubsub.publishBulk(pubSubName, topic, [
  34. { hello: "message 1" },
  35. { hello: "message 2" },
  36. { hello: "message 3" },
  37. ]);
  38. // Publish multiple messages with explicit bulk publish messages
  39. const bulkPublishMessages = [
  40. {
  41. entryID: "entry-1",
  42. contentType: "application/json",
  43. event: { hello: "foo message 1" },
  44. },
  45. {
  46. entryID: "entry-2",
  47. contentType: "application/cloudevents+json",
  48. event: { ...cloudEvent, data: "foo message 2", datacontenttype: "text/plain" },
  49. },
  50. {
  51. entryID: "entry-3",
  52. contentType: "text/plain",
  53. event: "foo message 3",
  54. },
  55. ];
  56. await client.pubsub.publishBulk(pubSubName, topic, bulkPublishMessages);
  57. }
  58. start().catch((e) => {
  59. console.error(e);
  60. process.exit(1);
  61. });

Bindings API

调用输出绑定

输出绑定

  1. import { DaprClient } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1";
  3. const daprPort = "3500";
  4. async function start() {
  5. const client = new DaprClient({ daprHost, daprPort });
  6. const bindingName = "my-binding-name";
  7. const bindingOperation = "create";
  8. const message = { hello: "world" };
  9. const response = await client.binding.send(bindingName, bindingOperation, message);
  10. }
  11. start().catch((e) => {
  12. console.error(e);
  13. process.exit(1);
  14. });

有关输出绑定的完整指南,请访问操作方法:使用绑定

密钥 API

检索密钥

  1. import { DaprClient } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1";
  3. const daprPort = "3500";
  4. async function start() {
  5. const client = new DaprClient({ daprHost, daprPort });
  6. const secretStoreName = "my-secret-store";
  7. const secretKey = "secret-key";
  8. // Retrieve a single secret from secret store
  9. const response = await client.secret.get(secretStoreName, secretKey);
  10. // Retrieve all secrets from secret store
  11. const response = await client.secret.getBulk(secretStoreName);
  12. }
  13. start().catch((e) => {
  14. console.error(e);
  15. process.exit(1);
  16. });

有关秘密的完整指南,请访问操作方法: 检索秘密

配置 API

获取配置键

  1. import { DaprClient } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1";
  3. async function start() {
  4. const client = new DaprClient({
  5. daprHost,
  6. daprPort: process.env.DAPR_GRPC_PORT,
  7. communicationProtocol: CommunicationProtocolEnum.GRPC,
  8. });
  9. const config = await client.configuration.get("config-store", ["key1", "key2"]);
  10. console.log(config);
  11. }
  12. start().catch((e) => {
  13. console.error(e);
  14. process.exit(1);
  15. });

示例输出

  1. {
  2. items: {
  3. key1: { key: 'key1', value: 'foo', version: '', metadata: {} },
  4. key2: { key: 'key2', value: 'bar2', version: '', metadata: {} }
  5. }
  6. }

订阅配置更新

  1. import { DaprClient } from "@dapr/dapr";
  2. const daprHost = "127.0.0.1";
  3. async function start() {
  4. const client = new DaprClient({
  5. daprHost,
  6. daprPort: process.env.DAPR_GRPC_PORT,
  7. communicationProtocol: CommunicationProtocolEnum.GRPC,
  8. });
  9. // Subscribes to config store changes for keys "key1" and "key2"
  10. const stream = await client.configuration.subscribeWithKeys("config-store", ["key1", "key2"], async (data) => {
  11. console.log("Subscribe received updates from config store: ", data);
  12. });
  13. // Wait for 60 seconds and unsubscribe.
  14. await new Promise((resolve) => setTimeout(resolve, 60000));
  15. stream.stop();
  16. }
  17. start().catch((e) => {
  18. console.error(e);
  19. process.exit(1);
  20. });

示例输出

  1. Subscribe received updates from config store: {
  2. items: { key2: { key: 'key2', value: 'bar', version: '', metadata: {} } }
  3. }
  4. Subscribe received updates from config store: {
  5. items: { key1: { key: 'key1', value: 'foobar', version: '', metadata: {} } }
  6. }

加密 API

对加密 API 的支持仅在 JavaScript SDK 中的 gRPC 客户端上可用。

  1. import { createReadStream, createWriteStream } from "node:fs";
  2. import { readFile, writeFile } from "node:fs/promises";
  3. import { pipeline } from "node:stream/promises";
  4. import { DaprClient, CommunicationProtocolEnum } from "@dapr/dapr";
  5. const daprHost = "127.0.0.1";
  6. const daprPort = "50050"; // Dapr Sidecar Port of this example server
  7. async function start() {
  8. const client = new DaprClient({
  9. daprHost,
  10. daprPort,
  11. communicationProtocol: CommunicationProtocolEnum.GRPC,
  12. });
  13. // Encrypt and decrypt a message using streams
  14. await encryptDecryptStream(client);
  15. // Encrypt and decrypt a message from a buffer
  16. await encryptDecryptBuffer(client);
  17. }
  18. async function encryptDecryptStream(client: DaprClient) {
  19. // First, encrypt the message
  20. console.log("== Encrypting message using streams");
  21. console.log("Encrypting plaintext.txt to ciphertext.out");
  22. await pipeline(
  23. createReadStream("plaintext.txt"),
  24. await client.crypto.encrypt({
  25. componentName: "crypto-local",
  26. keyName: "symmetric256",
  27. keyWrapAlgorithm: "A256KW",
  28. }),
  29. createWriteStream("ciphertext.out"),
  30. );
  31. // Decrypt the message
  32. console.log("== Decrypting message using streams");
  33. console.log("Encrypting ciphertext.out to plaintext.out");
  34. await pipeline(
  35. createReadStream("ciphertext.out"),
  36. await client.crypto.decrypt({
  37. componentName: "crypto-local",
  38. }),
  39. createWriteStream("plaintext.out"),
  40. );
  41. }
  42. async function encryptDecryptBuffer(client: DaprClient) {
  43. // Read "plaintext.txt" so we have some content
  44. const plaintext = await readFile("plaintext.txt");
  45. // First, encrypt the message
  46. console.log("== Encrypting message using buffers");
  47. const ciphertext = await client.crypto.encrypt(plaintext, {
  48. componentName: "crypto-local",
  49. keyName: "my-rsa-key",
  50. keyWrapAlgorithm: "RSA",
  51. });
  52. await writeFile("test.out", ciphertext);
  53. // Decrypt the message
  54. console.log("== Decrypting message using buffers");
  55. const decrypted = await client.crypto.decrypt(ciphertext, {
  56. componentName: "crypto-local",
  57. });
  58. // The contents should be equal
  59. if (plaintext.compare(decrypted) !== 0) {
  60. throw new Error("Decrypted message does not match original message");
  61. }
  62. }
  63. start().catch((e) => {
  64. console.error(e);
  65. process.exit(1);
  66. });

有关密码学的完整指南,请访问操作方法:密码学

分布式锁 API

尝试锁定和解锁API

  1. import { CommunicationProtocolEnum, DaprClient } from "@dapr/dapr";
  2. import { LockStatus } from "@dapr/dapr/types/lock/UnlockResponse";
  3. const daprHost = "127.0.0.1";
  4. const daprPortDefault = "3500";
  5. async function start() {
  6. const client = new DaprClient({ daprHost, daprPort });
  7. const storeName = "redislock";
  8. const resourceId = "resourceId";
  9. const lockOwner = "owner1";
  10. let expiryInSeconds = 1000;
  11. console.log(`Acquiring lock on ${storeName}, ${resourceId} as owner: ${lockOwner}`);
  12. const lockResponse = await client.lock.lock(storeName, resourceId, lockOwner, expiryInSeconds);
  13. console.log(lockResponse);
  14. console.log(`Unlocking on ${storeName}, ${resourceId} as owner: ${lockOwner}`);
  15. const unlockResponse = await client.lock.unlock(storeName, resourceId, lockOwner);
  16. console.log("Unlock API response: " + getResponseStatus(unlockResponse.status));
  17. }
  18. function getResponseStatus(status: LockStatus) {
  19. switch (status) {
  20. case LockStatus.Success:
  21. return "Success";
  22. case LockStatus.LockDoesNotExist:
  23. return "LockDoesNotExist";
  24. case LockStatus.LockBelongsToOthers:
  25. return "LockBelongsToOthers";
  26. default:
  27. return "InternalError";
  28. }
  29. }
  30. start().catch((e) => {
  31. console.error(e);
  32. process.exit(1);
  33. });

了解有关使用分布式锁的完整指南:操作方法:使用分布式锁.

工作流 API

工作流管理

  1. import { DaprClient } from "@dapr/dapr";
  2. async function start() {
  3. const client = new DaprClient();
  4. // Start a new workflow instance
  5. const instanceId = await client.workflow.start("OrderProcessingWorkflow", {
  6. Name: "Paperclips",
  7. TotalCost: 99.95,
  8. Quantity: 4,
  9. });
  10. console.log(`Started workflow instance ${instanceId}`);
  11. // Get a workflow instance
  12. const workflow = await client.workflow.get(instanceId);
  13. console.log(
  14. `Workflow ${workflow.workflowName}, created at ${workflow.createdAt.toUTCString()}, has status ${
  15. workflow.runtimeStatus
  16. }`,
  17. );
  18. console.log(`Additional properties: ${JSON.stringify(workflow.properties)}`);
  19. // Pause a workflow instance
  20. await client.workflow.pause(instanceId);
  21. console.log(`Paused workflow instance ${instanceId}`);
  22. // Resume a workflow instance
  23. await client.workflow.resume(instanceId);
  24. console.log(`Resumed workflow instance ${instanceId}`);
  25. // Terminate a workflow instance
  26. await client.workflow.terminate(instanceId);
  27. console.log(`Terminated workflow instance ${instanceId}`);
  28. // Purge a workflow instance
  29. await client.workflow.purge(instanceId);
  30. console.log(`Purged workflow instance ${instanceId}`);
  31. }
  32. start().catch((e) => {
  33. console.error(e);
  34. process.exit(1);
  35. });

相关链接