How-To: Use a lock

    Now that you’ve learned what the Dapr distributed lock API building block provides, learn how it can work in your service. In this guide, an example application acquires a lock using the Redis lock component to demonstrate how to lock resources. For a list of supported lock stores, see .

    In the diagram below, two instances of the same application acquire a lock, where one instance is successful and the other is denied.

    The diagram below shows two instances of the same application, where one instance releases the lock and the other instance is then able to acquire the lock.

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

    Save the following component file to the on your machine.

    1. -H 'Content-Type: application/json'
    2. -d '{"resourceId":"my_file_name", "lockOwner":"random_id_abc123", "expiryInSeconds": 60}'
    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. }
    10. defer client.Close()
    11. resp, err := client.TryLockAlpha1(ctx, "lockstore", &dapr.LockRequest{
    12. LockOwner: "random_id_abc123",
    13. ResourceID: "my_file_name",
    14. ExpiryInSeconds: 60,
    15. })
    16. fmt.Println(resp.Success)
    17. }
    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. }