How-To: Save and get state

Use key value pairs to persist a state

State management is one of the most common needs of any new, legacy, monolith, or microservice application. Dealing with and testing different database libraries and handling retries and faults can be both difficult and time consuming.

In this guide, you’ll learn the basics of using the key/value state API to allow an application to save, get, and delete state.

Example

The code example below loosely describes an application that processes orders with an order processing service which has a Dapr sidecar. The order processing service uses Dapr to store state in a Redis state store.

Diagram showing state management of example service

Set up a state store

A state store component represents a resource that Dapr uses to communicate with a database.

For the purpose of this guide we’ll use a Redis state store, but any state store from the supported list will work.

When you run dapr init in self-hosted mode, Dapr creates a default Redis statestore.yaml and runs a Redis state store on your local machine, located:

  • On Windows, under %UserProfile%\.dapr\components\statestore.yaml
  • On Linux/MacOS, under ~/.dapr/components/statestore.yaml

With the statestore.yaml component, you can easily swap out underlying components without application code changes.

To deploy this into a Kubernetes cluster, fill in the metadata connection details of your state store component in the YAML below, save as statestore.yaml, and run kubectl apply -f statestore.yaml.

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

See how to setup different state stores on Kubernetes.

Important

Set an app-id, as the state keys are prefixed with this value. If you don’t set an app-id, one is generated for you at runtime. The next time you run the command, a new app-id is generated and you will no longer have access to the previously saved state.

Save and retrieve a single state

The following example shows how to save and retrieve a single key/value pair using the Dapr state management API.

  1. //dependencies
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Net.Http;
  5. using System.Net.Http.Headers;
  6. using System.Threading.Tasks;
  7. using Dapr.Client;
  8. using Microsoft.AspNetCore.Mvc;
  9. using System.Threading;
  10. using System.Text.Json;
  11. //code
  12. namespace EventService
  13. {
  14. class Program
  15. {
  16. static async Task Main(string[] args)
  17. {
  18. string DAPR_STORE_NAME = "statestore";
  19. while(true) {
  20. System.Threading.Thread.Sleep(5000);
  21. using var client = new DaprClientBuilder().Build();
  22. Random random = new Random();
  23. int orderId = random.Next(1,1000);
  24. //Using Dapr SDK to save and get state
  25. await client.SaveStateAsync(DAPR_STORE_NAME, "order_1", orderId.ToString());
  26. await client.SaveStateAsync(DAPR_STORE_NAME, "order_2", orderId.ToString());
  27. var result = await client.GetStateAsync<string>(DAPR_STORE_NAME, "order_1");
  28. Console.WriteLine("Result after get: " + result);
  29. }
  30. }
  31. }
  32. }

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 dotnet run
  1. //dependencies
  2. import io.dapr.client.DaprClient;
  3. import io.dapr.client.DaprClientBuilder;
  4. import io.dapr.client.domain.State;
  5. import io.dapr.client.domain.TransactionalStateOperation;
  6. import org.springframework.boot.autoconfigure.SpringBootApplication;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import reactor.core.publisher.Mono;
  10. import java.util.Random;
  11. import java.util.concurrent.TimeUnit;
  12. //code
  13. @SpringBootApplication
  14. public class OrderProcessingServiceApplication {
  15. private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
  16. private static final String STATE_STORE_NAME = "statestore";
  17. public static void main(String[] args) throws InterruptedException{
  18. while(true) {
  19. TimeUnit.MILLISECONDS.sleep(5000);
  20. Random random = new Random();
  21. int orderId = random.nextInt(1000-1) + 1;
  22. DaprClient client = new DaprClientBuilder().build();
  23. //Using Dapr SDK to save and get state
  24. client.saveState(STATE_STORE_NAME, "order_1", Integer.toString(orderId)).block();
  25. client.saveState(STATE_STORE_NAME, "order_2", Integer.toString(orderId)).block();
  26. Mono<State<String>> result = client.getState(STATE_STORE_NAME, "order_1", String.class);
  27. log.info("Result after get" + result);
  28. }
  29. }
  30. }

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 mvn spring-boot:run
  1. #dependencies
  2. import random
  3. from time import sleep
  4. import requests
  5. import logging
  6. from dapr.clients import DaprClient
  7. from dapr.clients.grpc._state import StateItem
  8. from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType
  9. #code
  10. logging.basicConfig(level = logging.INFO)
  11. DAPR_STORE_NAME = "statestore"
  12. while True:
  13. sleep(random.randrange(50, 5000) / 1000)
  14. orderId = random.randint(1, 1000)
  15. with DaprClient() as client:
  16. #Using Dapr SDK to save and get state
  17. client.save_state(DAPR_STORE_NAME, "order_1", str(orderId))
  18. result = client.get_state(DAPR_STORE_NAME, "order_1")
  19. logging.info('Result after get: ' + result.data.decode('utf-8'))

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 -- python3 OrderProcessingService.py
  1. // dependencies
  2. import (
  3. "context"
  4. "log"
  5. "math/rand"
  6. "strconv"
  7. "time"
  8. dapr "github.com/dapr/go-sdk/client"
  9. )
  10. // code
  11. func main() {
  12. const STATE_STORE_NAME = "statestore"
  13. rand.Seed(time.Now().UnixMicro())
  14. for i := 0; i < 10; i++ {
  15. orderId := rand.Intn(1000-1) + 1
  16. client, err := dapr.NewClient()
  17. if err != nil {
  18. panic(err)
  19. }
  20. defer client.Close()
  21. ctx := context.Background()
  22. err = client.SaveState(ctx, STATE_STORE_NAME, "order_1", []byte(strconv.Itoa(orderId)), nil)
  23. if err != nil {
  24. panic(err)
  25. }
  26. result, err := client.GetState(ctx, STATE_STORE_NAME, "order_1", nil)
  27. if err != nil {
  28. panic(err)
  29. }
  30. log.Println("Result after get:", string(result.Value))
  31. time.Sleep(2 * time.Second)
  32. }
  33. }

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 go run OrderProcessingService.go
  1. //dependencies
  2. import { DaprClient, HttpMethod, CommunicationProtocolEnum } from '@dapr/dapr';
  3. //code
  4. const daprHost = "127.0.0.1";
  5. var main = function() {
  6. for(var i=0;i<10;i++) {
  7. sleep(5000);
  8. var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
  9. start(orderId).catch((e) => {
  10. console.error(e);
  11. process.exit(1);
  12. });
  13. }
  14. }
  15. async function start(orderId) {
  16. const client = new DaprClient({
  17. daprHost,
  18. daprPort: process.env.DAPR_HTTP_PORT,
  19. communicationProtocol: CommunicationProtocolEnum.HTTP,
  20. });
  21. const STATE_STORE_NAME = "statestore";
  22. //Using Dapr SDK to save and get state
  23. await client.state.save(STATE_STORE_NAME, [
  24. {
  25. key: "order_1",
  26. value: orderId.toString()
  27. },
  28. {
  29. key: "order_2",
  30. value: orderId.toString()
  31. }
  32. ]);
  33. var result = await client.state.get(STATE_STORE_NAME, "order_1");
  34. console.log("Result after get: " + result);
  35. }
  36. function sleep(ms) {
  37. return new Promise(resolve => setTimeout(resolve, ms));
  38. }
  39. main();

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 npm start

Launch a Dapr sidecar:

  1. dapr run --app-id orderprocessing --dapr-http-port 3601

In a separate terminal, save a key/value pair into your statestore:

  1. curl -X POST -H "Content-Type: application/json" -d '[{ "key": "order_1", "value": "250"}]' http://localhost:3601/v1.0/state/statestore

Now get the state you just saved:

  1. curl http://localhost:3601/v1.0/state/statestore/order_1

Restart your sidecar and try retrieving state again to observe that state persists separately from the app.

Launch a Dapr sidecar:

  1. dapr --app-id orderprocessing --dapr-http-port 3601 run

In a separate terminal, save a key/value pair into your statestore:

  1. Invoke-RestMethod -Method Post -ContentType 'application/json' -Body '[{"key": "order_1", "value": "250"}]' -Uri 'http://localhost:3601/v1.0/state/statestore'

Now get the state you just saved:

  1. Invoke-RestMethod -Uri 'http://localhost:3601/v1.0/state/statestore/order_1'

Restart your sidecar and try retrieving state again to observe that state persists separately from the app.

Delete state

Below are code examples that leverage Dapr SDKs for deleting the state.

  1. //dependencies
  2. using Dapr.Client;
  3. //code
  4. namespace EventService
  5. {
  6. class Program
  7. {
  8. static async Task Main(string[] args)
  9. {
  10. string DAPR_STORE_NAME = "statestore";
  11. //Using Dapr SDK to delete the state
  12. using var client = new DaprClientBuilder().Build();
  13. await client.DeleteStateAsync(DAPR_STORE_NAME, "order_1", cancellationToken: cancellationToken);
  14. }
  15. }
  16. }

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 dotnet run
  1. //dependencies
  2. import io.dapr.client.DaprClient;
  3. import io.dapr.client.DaprClientBuilder;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. //code
  6. @SpringBootApplication
  7. public class OrderProcessingServiceApplication {
  8. public static void main(String[] args) throws InterruptedException{
  9. String STATE_STORE_NAME = "statestore";
  10. //Using Dapr SDK to delete the state
  11. DaprClient client = new DaprClientBuilder().build();
  12. String storedEtag = client.getState(STATE_STORE_NAME, "order_1", String.class).block().getEtag();
  13. client.deleteState(STATE_STORE_NAME, "order_1", storedEtag, null).block();
  14. }
  15. }

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 mvn spring-boot:run
  1. #dependencies
  2. from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType
  3. #code
  4. logging.basicConfig(level = logging.INFO)
  5. DAPR_STORE_NAME = "statestore"
  6. #Using Dapr SDK to delete the state
  7. with DaprClient() as client:
  8. client.delete_state(store_name=DAPR_STORE_NAME, key="order_1")

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 -- python3 OrderProcessingService.py
  1. //dependencies
  2. import (
  3. "context"
  4. dapr "github.com/dapr/go-sdk/client"
  5. )
  6. //code
  7. func main() {
  8. STATE_STORE_NAME := "statestore"
  9. //Using Dapr SDK to delete the state
  10. client, err := dapr.NewClient()
  11. if err != nil {
  12. panic(err)
  13. }
  14. defer client.Close()
  15. ctx := context.Background()
  16. if err := client.DeleteState(ctx, STATE_STORE_NAME, "order_1"); err != nil {
  17. panic(err)
  18. }
  19. }

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 go run OrderProcessingService.go
  1. //dependencies
  2. import { DaprClient, HttpMethod, CommunicationProtocolEnum } from '@dapr/dapr';
  3. //code
  4. const daprHost = "127.0.0.1";
  5. var main = function() {
  6. const STATE_STORE_NAME = "statestore";
  7. //Using Dapr SDK to save and get state
  8. const client = new DaprClient({
  9. daprHost,
  10. daprPort: process.env.DAPR_HTTP_PORT,
  11. communicationProtocol: CommunicationProtocolEnum.HTTP,
  12. });
  13. await client.state.delete(STATE_STORE_NAME, "order_1");
  14. }
  15. main();

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 npm start

With the same Dapr instance running from above, run:

  1. curl -X DELETE 'http://localhost:3601/v1.0/state/statestore/order_1'

Try getting state again. Note that no value is returned.

With the same Dapr instance running from above, run:

  1. Invoke-RestMethod -Method Delete -Uri 'http://localhost:3601/v1.0/state/statestore/order_1'

Try getting state again. Note that no value is returned.

Save and retrieve multiple states

Below are code examples that leverage Dapr SDKs for saving and retrieving multiple states.

  1. //dependencies
  2. using Dapr.Client;
  3. //code
  4. namespace EventService
  5. {
  6. class Program
  7. {
  8. static async Task Main(string[] args)
  9. {
  10. string DAPR_STORE_NAME = "statestore";
  11. //Using Dapr SDK to retrieve multiple states
  12. using var client = new DaprClientBuilder().Build();
  13. IReadOnlyList<BulkStateItem> mulitpleStateResult = await client.GetBulkStateAsync(DAPR_STORE_NAME, new List<string> { "order_1", "order_2" }, parallelism: 1);
  14. }
  15. }
  16. }

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 dotnet run

The above example returns a BulkStateItem with the serialized format of the value you saved to state. If you prefer that the value be deserialized by the SDK across each of your bulk response items, you can instead use the following:

  1. //dependencies
  2. using Dapr.Client;
  3. //code
  4. namespace EventService
  5. {
  6. class Program
  7. {
  8. static async Task Main(string[] args)
  9. {
  10. string DAPR_STORE_NAME = "statestore";
  11. //Using Dapr SDK to retrieve multiple states
  12. using var client = new DaprClientBuilder().Build();
  13. IReadOnlyList<BulkStateItem<Widget>> mulitpleStateResult = await client.GetBulkStateAsync<Widget>(DAPR_STORE_NAME, new List<string> { "widget_1", "widget_2" }, parallelism: 1);
  14. }
  15. }
  16. class Widget
  17. {
  18. string Size { get; set; }
  19. string Color { get; set; }
  20. }
  21. }
  1. //dependencies
  2. import io.dapr.client.DaprClient;
  3. import io.dapr.client.DaprClientBuilder;
  4. import io.dapr.client.domain.State;
  5. import java.util.Arrays;
  6. //code
  7. @SpringBootApplication
  8. public class OrderProcessingServiceApplication {
  9. private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
  10. public static void main(String[] args) throws InterruptedException{
  11. String STATE_STORE_NAME = "statestore";
  12. //Using Dapr SDK to retrieve multiple states
  13. DaprClient client = new DaprClientBuilder().build();
  14. Mono<List<State<String>>> resultBulk = client.getBulkState(STATE_STORE_NAME,
  15. Arrays.asList("order_1", "order_2"), String.class);
  16. }
  17. }

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 mvn spring-boot:run
  1. #dependencies
  2. from dapr.clients import DaprClient
  3. from dapr.clients.grpc._state import StateItem
  4. #code
  5. logging.basicConfig(level = logging.INFO)
  6. DAPR_STORE_NAME = "statestore"
  7. orderId = 100
  8. #Using Dapr SDK to save and retrieve multiple states
  9. with DaprClient() as client:
  10. client.save_bulk_state(store_name=DAPR_STORE_NAME, states=[StateItem(key="order_2", value=str(orderId))])
  11. result = client.get_bulk_state(store_name=DAPR_STORE_NAME, keys=["order_1", "order_2"], states_metadata={"metakey": "metavalue"}).items
  12. logging.info('Result after get bulk: ' + str(result))

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 -- python3 OrderProcessingService.py
  1. // dependencies
  2. import (
  3. "context"
  4. "log"
  5. "math/rand"
  6. "strconv"
  7. "time"
  8. dapr "github.com/dapr/go-sdk/client"
  9. )
  10. // code
  11. func main() {
  12. const STATE_STORE_NAME = "statestore"
  13. rand.Seed(time.Now().UnixMicro())
  14. for i := 0; i < 10; i++ {
  15. orderId := rand.Intn(1000-1) + 1
  16. client, err := dapr.NewClient()
  17. if err != nil {
  18. panic(err)
  19. }
  20. defer client.Close()
  21. ctx := context.Background()
  22. err = client.SaveState(ctx, STATE_STORE_NAME, "order_1", []byte(strconv.Itoa(orderId)), nil)
  23. if err != nil {
  24. panic(err)
  25. }
  26. keys := []string{"key1", "key2", "key3"}
  27. items, err := client.GetBulkState(ctx, STATE_STORE_NAME, keys, nil, 100)
  28. if err != nil {
  29. panic(err)
  30. }
  31. for _, item := range items {
  32. log.Println("Item from GetBulkState:", string(item.Value))
  33. }
  34. }
  35. }

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 go run OrderProcessingService.go
  1. //dependencies
  2. import { DaprClient, HttpMethod, CommunicationProtocolEnum } from '@dapr/dapr';
  3. //code
  4. const daprHost = "127.0.0.1";
  5. var main = function() {
  6. const STATE_STORE_NAME = "statestore";
  7. var orderId = 100;
  8. //Using Dapr SDK to save and retrieve multiple states
  9. const client = new DaprClient({
  10. daprHost,
  11. daprPort: process.env.DAPR_HTTP_PORT,
  12. communicationProtocol: CommunicationProtocolEnum.HTTP,
  13. });
  14. await client.state.save(STATE_STORE_NAME, [
  15. {
  16. key: "order_1",
  17. value: orderId.toString()
  18. },
  19. {
  20. key: "order_2",
  21. value: orderId.toString()
  22. }
  23. ]);
  24. result = await client.state.getBulk(STATE_STORE_NAME, ["order_1", "order_2"]);
  25. }
  26. main();

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 npm start

With the same Dapr instance running from above, save two key/value pairs into your statestore:

  1. curl -X POST -H "Content-Type: application/json" -d '[{ "key": "order_1", "value": "250"}, { "key": "order_2", "value": "550"}]' http://localhost:3601/v1.0/state/statestore

Now get the states you just saved:

  1. curl -X POST -H "Content-Type: application/json" -d '{"keys":["order_1", "order_2"]}' http://localhost:3601/v1.0/state/statestore/bulk

With the same Dapr instance running from above, save two key/value pairs into your statestore:

  1. Invoke-RestMethod -Method Post -ContentType 'application/json' -Body '[{ "key": "order_1", "value": "250"}, { "key": "order_2", "value": "550"}]' -Uri 'http://localhost:3601/v1.0/state/statestore'

Now get the states you just saved:

  1. Invoke-RestMethod -Method Post -ContentType 'application/json' -Body '{"keys":["order_1", "order_2"]}' -Uri 'http://localhost:3601/v1.0/state/statestore/bulk'

Perform state transactions

Note

State transactions require a state store that supports multi-item transactions. See the supported state stores page for a full list.

Below are code examples that leverage Dapr SDKs for performing state transactions.

  1. //dependencies
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Net.Http;
  5. using System.Net.Http.Headers;
  6. using System.Threading.Tasks;
  7. using Dapr.Client;
  8. using Microsoft.AspNetCore.Mvc;
  9. using System.Threading;
  10. using System.Text.Json;
  11. //code
  12. namespace EventService
  13. {
  14. class Program
  15. {
  16. static async Task Main(string[] args)
  17. {
  18. string DAPR_STORE_NAME = "statestore";
  19. while(true) {
  20. System.Threading.Thread.Sleep(5000);
  21. Random random = new Random();
  22. int orderId = random.Next(1,1000);
  23. using var client = new DaprClientBuilder().Build();
  24. var requests = new List<StateTransactionRequest>()
  25. {
  26. new StateTransactionRequest("order_3", JsonSerializer.SerializeToUtf8Bytes(orderId.ToString()), StateOperationType.Upsert),
  27. new StateTransactionRequest("order_2", null, StateOperationType.Delete)
  28. };
  29. CancellationTokenSource source = new CancellationTokenSource();
  30. CancellationToken cancellationToken = source.Token;
  31. //Using Dapr SDK to perform the state transactions
  32. await client.ExecuteStateTransactionAsync(DAPR_STORE_NAME, requests, cancellationToken: cancellationToken);
  33. Console.WriteLine("Order requested: " + orderId);
  34. Console.WriteLine("Result: " + result);
  35. }
  36. }
  37. }
  38. }

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 dotnet run
  1. //dependencies
  2. import io.dapr.client.DaprClient;
  3. import io.dapr.client.DaprClientBuilder;
  4. import io.dapr.client.domain.State;
  5. import io.dapr.client.domain.TransactionalStateOperation;
  6. import org.springframework.boot.autoconfigure.SpringBootApplication;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import reactor.core.publisher.Mono;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.util.Random;
  13. import java.util.concurrent.TimeUnit;
  14. //code
  15. @SpringBootApplication
  16. public class OrderProcessingServiceApplication {
  17. private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
  18. private static final String STATE_STORE_NAME = "statestore";
  19. public static void main(String[] args) throws InterruptedException{
  20. while(true) {
  21. TimeUnit.MILLISECONDS.sleep(5000);
  22. Random random = new Random();
  23. int orderId = random.nextInt(1000-1) + 1;
  24. DaprClient client = new DaprClientBuilder().build();
  25. List<TransactionalStateOperation<?>> operationList = new ArrayList<>();
  26. operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.OperationType.UPSERT,
  27. new State<>("order_3", Integer.toString(orderId), "")));
  28. operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.OperationType.DELETE,
  29. new State<>("order_2")));
  30. //Using Dapr SDK to perform the state transactions
  31. client.executeStateTransaction(STATE_STORE_NAME, operationList).block();
  32. log.info("Order requested: " + orderId);
  33. }
  34. }
  35. }

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 mvn spring-boot:run
  1. #dependencies
  2. import random
  3. from time import sleep
  4. import requests
  5. import logging
  6. from dapr.clients import DaprClient
  7. from dapr.clients.grpc._state import StateItem
  8. from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType
  9. #code
  10. logging.basicConfig(level = logging.INFO)
  11. DAPR_STORE_NAME = "statestore"
  12. while True:
  13. sleep(random.randrange(50, 5000) / 1000)
  14. orderId = random.randint(1, 1000)
  15. with DaprClient() as client:
  16. #Using Dapr SDK to perform the state transactions
  17. client.execute_state_transaction(store_name=DAPR_STORE_NAME, operations=[
  18. TransactionalStateOperation(
  19. operation_type=TransactionOperationType.upsert,
  20. key="order_3",
  21. data=str(orderId)),
  22. TransactionalStateOperation(key="order_3", data=str(orderId)),
  23. TransactionalStateOperation(
  24. operation_type=TransactionOperationType.delete,
  25. key="order_2",
  26. data=str(orderId)),
  27. TransactionalStateOperation(key="order_2", data=str(orderId))
  28. ])
  29. client.delete_state(store_name=DAPR_STORE_NAME, key="order_1")
  30. logging.basicConfig(level = logging.INFO)
  31. logging.info('Order requested: ' + str(orderId))
  32. logging.info('Result: ' + str(result))

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 -- python3 OrderProcessingService.py
  1. // dependencies
  2. package main
  3. import (
  4. "context"
  5. "log"
  6. "math/rand"
  7. "strconv"
  8. "time"
  9. dapr "github.com/dapr/go-sdk/client"
  10. )
  11. // code
  12. func main() {
  13. const STATE_STORE_NAME = "statestore"
  14. rand.Seed(time.Now().UnixMicro())
  15. for i := 0; i < 10; i++ {
  16. orderId := rand.Intn(1000-1) + 1
  17. client, err := dapr.NewClient()
  18. if err != nil {
  19. panic(err)
  20. }
  21. defer client.Close()
  22. ctx := context.Background()
  23. err = client.SaveState(ctx, STATE_STORE_NAME, "order_1", []byte(strconv.Itoa(orderId)), nil)
  24. if err != nil {
  25. panic(err)
  26. }
  27. result, err := client.GetState(ctx, STATE_STORE_NAME, "order_1", nil)
  28. if err != nil {
  29. panic(err)
  30. }
  31. ops := make([]*dapr.StateOperation, 0)
  32. data1 := "data1"
  33. data2 := "data2"
  34. op1 := &dapr.StateOperation{
  35. Type: dapr.StateOperationTypeUpsert,
  36. Item: &dapr.SetStateItem{
  37. Key: "key1",
  38. Value: []byte(data1),
  39. },
  40. }
  41. op2 := &dapr.StateOperation{
  42. Type: dapr.StateOperationTypeDelete,
  43. Item: &dapr.SetStateItem{
  44. Key: "key2",
  45. Value: []byte(data2),
  46. },
  47. }
  48. ops = append(ops, op1, op2)
  49. meta := map[string]string{}
  50. err = client.ExecuteStateTransaction(ctx, STATE_STORE_NAME, meta, ops)
  51. log.Println("Result after get:", string(result.Value))
  52. time.Sleep(2 * time.Second)
  53. }
  54. }

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 go run OrderProcessingService.go
  1. //dependencies
  2. import { DaprClient, HttpMethod, CommunicationProtocolEnum } from '@dapr/dapr';
  3. //code
  4. const daprHost = "127.0.0.1";
  5. var main = function() {
  6. for(var i=0;i<10;i++) {
  7. sleep(5000);
  8. var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
  9. start(orderId).catch((e) => {
  10. console.error(e);
  11. process.exit(1);
  12. });
  13. }
  14. }
  15. async function start(orderId) {
  16. const client = new DaprClient({
  17. daprHost,
  18. daprPort: process.env.DAPR_HTTP_PORT,
  19. communicationProtocol: CommunicationProtocolEnum.HTTP,
  20. });
  21. const STATE_STORE_NAME = "statestore";
  22. //Using Dapr SDK to save and retrieve multiple states
  23. await client.state.transaction(STATE_STORE_NAME, [
  24. {
  25. operation: "upsert",
  26. request: {
  27. key: "order_3",
  28. value: orderId.toString()
  29. }
  30. },
  31. {
  32. operation: "delete",
  33. request: {
  34. key: "order_2"
  35. }
  36. }
  37. ]);
  38. }
  39. function sleep(ms) {
  40. return new Promise(resolve => setTimeout(resolve, ms));
  41. }
  42. main();

To launch a Dapr sidecar for the above example application, run a command similar to the following:

  1. dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-grpc-port 60001 npm start

With the same Dapr instance running from above, perform two state transactions:

  1. curl -X POST -H "Content-Type: application/json" -d '{"operations": [{"operation":"upsert", "request": {"key": "order_1", "value": "250"}}, {"operation":"delete", "request": {"key": "order_2"}}]}' http://localhost:3601/v1.0/state/statestore/transaction

Now see the results of your state transactions:

  1. curl -X POST -H "Content-Type: application/json" -d '{"keys":["order_1", "order_2"]}' http://localhost:3601/v1.0/state/statestore/bulk

With the same Dapr instance running from above, save two key/value pairs into your statestore:

  1. Invoke-RestMethod -Method Post -ContentType 'application/json' -Body '{"operations": [{"operation":"upsert", "request": {"key": "order_1", "value": "250"}}, {"operation":"delete", "request": {"key": "order_2"}}]}' -Uri 'http://localhost:3601/v1.0/state/statestore/transaction'

Now see the results of your state transactions:

  1. Invoke-RestMethod -Method Post -ContentType 'application/json' -Body '{"keys":["order_1", "order_2"]}' -Uri 'http://localhost:3601/v1.0/state/statestore/bulk'

Next steps

Last modified October 11, 2024: Fixed typo (#4389) (fe17926)