方法:使用锁

学习如何使用分布式锁来提供对资源的独占访问权限

现在,你已了解 Dapr 分布式锁 构建块提供的功能,请了解它如何在你的服务中工作。 在本指南中,一个示例应用程序将使用 Redis 锁组件获取一个锁,以演示如何锁定资源。 有关支持的锁存储的列表,请参阅此参考页面

在下图中,同一应用程序的两个实例获取了一个锁,其中一个实例成功,另一个实例被拒绝。

The diagram below shows two instances of the same application acquiring a lock, where one instance is successful and the other is denied

下图显示的是同一个应用程序的两个实例,其中一个实例释放了锁,另一个实例就能获取锁。

Diagram showing releasing a lock from multiple instances of same application

下图显示了不同应用程序的两个实例,它们在同一资源上获取了不同的锁。

The diagram below shows two instances of different applications, acquiring different locks on the same resource

配置锁组件

将以下组件文件保存到您的机器上的默认组件文件夹中。

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: lockstore
  5. spec:
  6. type: lock.redis
  7. version: v1
  8. metadata:
  9. - name: redisHost
  10. value: localhost:6379
  11. - name: redisPassword
  12. value: <PASSWORD>

获取锁

  1. curl -X POST http://localhost:3500/v1.0-alpha1/lock/lockstore
  2. -H 'Content-Type: application/json'
  3. -d '{"resourceId":"my_file_name", "lockOwner":"random_id_abc123", "expiryInSeconds": 60}'
  1. using System;
  2. using Dapr.Client;
  3. namespace LockService
  4. {
  5. class Program
  6. {
  7. [Obsolete("Distributed Lock API is in Alpha, this can be removed once it is stable.")]
  8. static async Task Main(string[] args)
  9. {
  10. string DAPR_LOCK_NAME = "lockstore";
  11. string fileName = "my_file_name";
  12. var client = new DaprClientBuilder().Build();
  13. await using (var fileLock = await client.Lock(DAPR_LOCK_NAME, fileName, "random_id_abc123", 60))
  14. {
  15. if (fileLock.Success)
  16. {
  17. Console.WriteLine("Success");
  18. }
  19. else
  20. {
  21. Console.WriteLine($"Failed to lock {fileName}.");
  22. }
  23. }
  24. }
  25. }
  26. }
  1. package main
  2. import (
  3. "fmt"
  4. dapr "github.com/dapr/go-sdk/client"
  5. )
  6. func main() {
  7. client, err := dapr.NewClient()
  8. if err != nil {
  9. panic(err)
  10. }
  11. defer client.Close()
  12. resp, err := client.TryLockAlpha1(ctx, "lockstore", &dapr.LockRequest{
  13. LockOwner: "random_id_abc123",
  14. ResourceID: "my_file_name",
  15. ExpiryInSeconds: 60,
  16. })
  17. fmt.Println(resp.Success)
  18. }

释放现有锁

  1. curl -X POST http://localhost:3500/v1.0-alpha1/unlock/lockstore
  2. -H 'Content-Type: application/json'
  3. -d '{"resourceId":"my_file_name", "lockOwner":"random_id_abc123"}'
  1. using System;
  2. using Dapr.Client;
  3. namespace LockService
  4. {
  5. class Program
  6. {
  7. static async Task Main(string[] args)
  8. {
  9. string DAPR_LOCK_NAME = "lockstore";
  10. var client = new DaprClientBuilder().Build();
  11. var response = await client.Unlock(DAPR_LOCK_NAME, "my_file_name", "random_id_abc123"));
  12. Console.WriteLine(response.status);
  13. }
  14. }
  15. }
  1. package main
  2. import (
  3. "fmt"
  4. dapr "github.com/dapr/go-sdk/client"
  5. )
  6. func main() {
  7. client, err := dapr.NewClient()
  8. if err != nil {
  9. panic(err)
  10. }
  11. defer client.Close()
  12. resp, err := client.UnlockAlpha1(ctx, "lockstore", &UnlockRequest{
  13. LockOwner: "random_id_abc123",
  14. ResourceID: "my_file_name",
  15. })
  16. fmt.Println(resp.Status)
  17. }

下一步

阅读 分布式锁 API 概述 了解更多信息。