Added complete code snippets

This commit is contained in:
Amulya Varote 2021-11-23 11:35:59 -08:00
parent ad20a76b32
commit d635712989
3 changed files with 566 additions and 199 deletions

View File

@ -185,18 +185,42 @@ Below are code examples that leverage Dapr SDKs for service invocation.
```csharp ```csharp
//dependencies //dependencies
using System;
using Dapr.Client; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Dapr.Client;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
//code //code
namespace EventService
{
class Program
{
static async Task Main(string[] args)
{
//Calling service multiple times with 5 seconds gap in between the calls
while(true) {
System.Threading.Thread.Sleep(5000);
Random random = new Random();
int orderId = random.Next(1,1000);
CancellationTokenSource source = new CancellationTokenSource(); CancellationTokenSource source = new CancellationTokenSource();
CancellationToken cancellationToken = source.Token; CancellationToken cancellationToken = source.Token;
//Using Dapr SDK to invoke a method
using var client = new DaprClientBuilder().Build(); using var client = new DaprClientBuilder().Build();
var result = client.CreateInvokeMethodRequest(HttpMethod.Get, "checkout", "checkout/" + orderId, cancellationToken); var result = client.CreateInvokeMethodRequest(HttpMethod.Get, "checkout", "checkout/" + orderId, cancellationToken);
await client.InvokeMethodAsync(result); await client.InvokeMethodAsync(result);
Console.WriteLine("Order requested: " + orderId);
Console.WriteLine("Result: " + result);
}
}
}
}
``` ```
{{% /codetab %}} {{% /codetab %}}
@ -205,15 +229,33 @@ await client.InvokeMethodAsync(result);
```java ```java
//dependencies //dependencies
import io.dapr.client.DaprClient; import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder; import io.dapr.client.DaprClientBuilder;
import io.dapr.client.domain.HttpExtension; import io.dapr.client.domain.HttpExtension;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Random;
import java.util.concurrent.TimeUnit;
//code //code
@SpringBootApplication
public class OrderProcessingServiceApplication {
DaprClient daprClient = new DaprClientBuilder().build(); private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
var result = daprClient.invokeMethod(
public static void main(String[] args) throws InterruptedException{
//Calling service multiple times with 5 seconds gap in between the calls
while(true) {
TimeUnit.MILLISECONDS.sleep(5000);
Random random = new Random();
int orderId = random.nextInt(1000-1) + 1;
//Using Dapr SDK to invoke a method
DaprClient client = new DaprClientBuilder().build();
var result = client.invokeMethod(
"checkout", "checkout",
"checkout/" + orderId, "checkout/" + orderId,
null, null,
@ -221,6 +263,12 @@ var result = daprClient.invokeMethod(
String.class String.class
); );
log.info("Order requested: " + orderId);
log.info("Result: " + result);
}
}
}
``` ```
{{% /codetab %}} {{% /codetab %}}
@ -228,18 +276,31 @@ var result = daprClient.invokeMethod(
```python ```python
#dependencies #dependencies
import random
from time import sleep
import requests
import logging
from dapr.clients import DaprClient from dapr.clients import DaprClient
#code #code
logging.basicConfig(level = logging.INFO)
with DaprClient() as daprClient: #Calling service multiple times with 5 seconds gap in between the calls
result = daprClient.invoke_method( while True:
sleep(random.randrange(50, 5000) / 1000)
orderId = random.randint(1, 1000)
#Using Dapr SDK to invoke a method
with DaprClient() as client:
result = client.invoke_method(
"checkout", "checkout",
f"checkout/{orderId}", f"checkout/{orderId}",
data=b'', data=b'',
http_verb="GET" http_verb="GET"
) )
logging.basicConfig(level = logging.INFO)
logging.info('Order requested: ' + str(orderId))
logging.info('Result: ' + str(result))
``` ```
{{% /codetab %}} {{% /codetab %}}
@ -249,20 +310,38 @@ with DaprClient() as daprClient:
//dependencies //dependencies
import ( import (
"context"
"log"
"math/rand"
"time"
"strconv"
dapr "github.com/dapr/go-sdk/client" dapr "github.com/dapr/go-sdk/client"
) )
//code //code
func main() {
//Calling service multiple times with 5 seconds gap in between the calls
for i := 0; i < 10; i++ {
time.Sleep(5000)
orderId := rand.Intn(1000-1) + 1
//Using Dapr SDK to invoke a method
client, err := dapr.NewClient() client, err := dapr.NewClient()
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer client.Close() defer client.Close()
ctx := context.Background() ctx := context.Background()
result, err := client.InvokeMethod(ctx, "checkout", "checkout/" + strconv.Itoa(orderId), "get") result, err := client.InvokeMethod(ctx, "checkout", "checkout/" + strconv.Itoa(orderId), "get")
log.Println("Order requested: " + strconv.Itoa(orderId))
log.Println("Result: ")
log.Println(result)
}
}
``` ```
{{% /codetab %}} {{% /codetab %}}
@ -270,15 +349,33 @@ result, err := client.InvokeMethod(ctx, "checkout", "checkout/" + strconv.Itoa(o
```javascript ```javascript
//dependencies //dependencies
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client'; import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client';
//code
const daprHost = "127.0.0.1"; const daprHost = "127.0.0.1";
//code
var main = function() {
//Calling service multiple times with 5 seconds gap in between the calls
for(var i=0;i<10;i++) {
sleep(5000);
var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
//Using Dapr SDK to invoke a method
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP); const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
const result = await client.invoker.invoke('checkout' , "checkout/" + orderId , HttpMethod.GET); const result = await client.invoker.invoke('checkout' , "checkout/" + orderId , HttpMethod.GET);
console.log("Order requested: " + orderId);
console.log("Result: " + result);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main();
``` ```
{{% /codetab %}} {{% /codetab %}}

View File

@ -66,7 +66,7 @@ See the instructions [here]({{< ref "setup-state-store" >}}) on how to setup dif
## Step 2: Save and retrieve a single state ## Step 2: Save and retrieve a single state
The following example shows how to a single key/value pair using the Dapr state building block. The following example shows how to save and retrieve a single key/value pair using the Dapr state building block.
{{% alert title="Note" color="warning" %}} {{% alert title="Note" color="warning" %}}
It is important to set an app-id, as the state keys are prefixed with this value. If you don't set it one is generated for you at runtime, and the next time you run the command a new one will be generated and you will no longer be able to access previously saved state. It is important to set an app-id, as the state keys are prefixed with this value. If you don't set it one is generated for you at runtime, and the next time you run the command a new one will be generated and you will no longer be able to access previously saved state.
@ -79,18 +79,43 @@ Below are code examples that leverage Dapr SDKs for saving and retrieving a sing
{{% codetab %}} {{% codetab %}}
```csharp ```csharp
//dependencies
//dependencies
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Dapr.Client; using Dapr.Client;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Text.Json;
//code //code
namespace EventService
{
class Program
{
static async Task Main(string[] args)
{
string DAPR_STORE_NAME = "statestore"; string DAPR_STORE_NAME = "statestore";
//Calling service multiple times with 5 seconds gap in between the calls
while(true) {
System.Threading.Thread.Sleep(5000);
Random random = new Random();
int orderId = random.Next(1,1000);
//Using Dapr SDK to save and get state
using var client = new DaprClientBuilder().Build(); using var client = new DaprClientBuilder().Build();
await client.SaveStateAsync(DAPR_STORE_NAME, "order_1", orderId.ToString()); await client.SaveStateAsync(DAPR_STORE_NAME, "order_1", orderId.ToString());
await client.SaveStateAsync(DAPR_STORE_NAME, "order_2", orderId.ToString());
var result = await client.GetStateAsync<string>(DAPR_STORE_NAME, orderId.ToString()); var result = await client.GetStateAsync<string>(DAPR_STORE_NAME, orderId.ToString());
Console.WriteLine("Result after get: " + result); Console.WriteLine("Result after get: " + result);
}
}
}
}
``` ```
@ -103,23 +128,46 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% /codetab %}} {{% /codetab %}}
{{% codetab %}} {{% codetab %}}
```java ```java
//dependencies
//dependencies
import io.dapr.client.DaprClient; import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder; import io.dapr.client.DaprClientBuilder;
import io.dapr.client.domain.State;
import io.dapr.client.domain.TransactionalStateOperation;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import java.util.Random;
import java.util.concurrent.TimeUnit;
//code //code
@SpringBootApplication
public class OrderProcessingServiceApplication {
private static final String STATE_STORE_NAME = "statestore"; private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
public static void main(String[] args) throws InterruptedException{
String STATE_STORE_NAME = "statestore";
//Calling service multiple times with 5 seconds gap in between the calls
while(true) {
TimeUnit.MILLISECONDS.sleep(5000);
Random random = new Random();
int orderId = random.nextInt(1000-1) + 1;
//Using Dapr SDK to save and get state
DaprClient client = new DaprClientBuilder().build(); DaprClient client = new DaprClientBuilder().build();
client.saveState(STATE_STORE_NAME, "order_1", Integer.toString(orderId)).block(); client.saveState(STATE_STORE_NAME, "order_1", Integer.toString(orderId)).block();
client.saveState(STATE_STORE_NAME, "order_2", Integer.toString(orderId)).block();
Mono<State<String>> result = client.getState(STATE_STORE_NAME, "order_1", String.class); Mono<State<String>> result = client.getState(STATE_STORE_NAME, "order_1", String.class);
log.info("Result after get" + result); log.info("Result after get" + result);
}
}
}
``` ```
@ -135,14 +183,27 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% codetab %}} {{% codetab %}}
```python ```python
#dependencies
#dependencies
import random
from time import sleep
import requests
import logging
from dapr.clients import DaprClient from dapr.clients import DaprClient
from dapr.clients.grpc._state import StateItem
from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType
#code #code
logging.basicConfig(level = logging.INFO)
DAPR_STORE_NAME = "statestore" DAPR_STORE_NAME = "statestore"
#Calling service multiple times with 5 seconds gap in between the calls
while True:
sleep(random.randrange(50, 5000) / 1000)
orderId = random.randint(1, 1000)
#Using Dapr SDK to save and get state
with DaprClient() as client: with DaprClient() as client:
client.save_state(DAPR_STORE_NAME, "order_1", str(orderId)) client.save_state(DAPR_STORE_NAME, "order_1", str(orderId))
result = client.get_state(DAPR_STORE_NAME, "order_1") result = client.get_state(DAPR_STORE_NAME, "order_1")
@ -162,35 +223,49 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% codetab %}} {{% codetab %}}
```go ```go
//dependencies
//dependencies
import ( import (
"context"
"log"
"math/rand"
"time"
"strconv"
dapr "github.com/dapr/go-sdk/client" dapr "github.com/dapr/go-sdk/client"
) )
//code //code
func main() {
client, err := dapr.NewClient()
STATE_STORE_NAME := "statestore" STATE_STORE_NAME := "statestore"
//Calling service multiple times with 5 seconds gap in between the calls
for i := 0; i < 10; i++ {
time.Sleep(5000)
orderId := rand.Intn(1000-1) + 1
//Using Dapr SDK to save and get state
client, err := dapr.NewClient()
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer client.Close() defer client.Close()
ctx := context.Background() ctx := context.Background()
if err := client.SaveState(ctx, store, "order_1", []byte(strconv.Itoa(orderId))); err != nil { if err := client.SaveState(ctx, STATE_STORE_NAME, "order_1", []byte(strconv.Itoa(orderId))); err != nil {
panic(err) panic(err)
} }
result, err := client.GetState(ctx, store, "order_2") result, err := client.GetState(ctx, STATE_STORE_NAME, "order_1")
if err != nil { if err != nil {
panic(err) panic(err)
} }
log.Println("Result after get: ") log.Println("Result after get: ")
log.Println(result) log.Println(result)
}
}
``` ```
@ -206,24 +281,43 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% codetab %}} {{% codetab %}}
```javascript ```javascript
//dependencies
//dependencies
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client'; import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client';
//code //code
const daprHost = "127.0.0.1";
var main = function() {
const STATE_STORE_NAME = "statestore"; const STATE_STORE_NAME = "statestore";
const daprHost = "127.0.0.1"; //Calling service multiple times with 5 seconds gap in between the calls
for(var i=0;i<10;i++) {
sleep(5000);
var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
//Using Dapr SDK to save and get state
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP); const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
await client.state.save(STATE_STORE_NAME, [ await client.state.save(STATE_STORE_NAME, [
{ {
key: "order_1", key: "order_1",
value: orderId.toString() value: orderId.toString()
}]); },
{
key: "order_2",
value: orderId.toString()
}
]);
var result = await client.state.get(STATE_STORE_NAME, "order_1"); var result = await client.state.get(STATE_STORE_NAME, "order_1");
console.log("Result after get: " + result); console.log("Result after get: " + result);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main();
``` ```
@ -290,15 +384,32 @@ Below are code examples that leverage Dapr SDKs for deleting the state.
{{% codetab %}} {{% codetab %}}
```csharp ```csharp
//dependencies
//dependencies
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Dapr.Client; using Dapr.Client;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Text.Json;
//code //code
namespace EventService
{
class Program
{
static async Task Main(string[] args)
{
string DAPR_STORE_NAME = "statestore"; string DAPR_STORE_NAME = "statestore";
//Using Dapr SDK to delete the state
using var client = new DaprClientBuilder().Build();
await client.DeleteStateAsync(DAPR_STORE_NAME, "order_1", cancellationToken: cancellationToken); await client.DeleteStateAsync(DAPR_STORE_NAME, "order_1", cancellationToken: cancellationToken);
}
}
}
``` ```
@ -314,18 +425,33 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% codetab %}} {{% codetab %}}
```java ```java
//dependencies
//dependencies
import io.dapr.client.DaprClient; import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder; import io.dapr.client.DaprClientBuilder;
import io.dapr.client.domain.State;
import io.dapr.client.domain.TransactionalStateOperation;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Random;
import java.util.concurrent.TimeUnit;
//code //code
@SpringBootApplication
public class OrderProcessingServiceApplication {
private static final String STATE_STORE_NAME = "statestore"; private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
public static void main(String[] args) throws InterruptedException{
String STATE_STORE_NAME = "statestore";
//Using Dapr SDK to delete the state
DaprClient client = new DaprClientBuilder().build(); DaprClient client = new DaprClientBuilder().build();
String storedEtag = client.getState(STATE_STORE_NAME, "order_1", String.class).block().getEtag(); String storedEtag = client.getState(STATE_STORE_NAME, "order_1", String.class).block().getEtag();
client.deleteState(STATE_STORE_NAME, "order_1", storedEtag, null).block(); client.deleteState(STATE_STORE_NAME, "order_1", storedEtag, null).block();
}
}
``` ```
@ -341,14 +467,22 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% codetab %}} {{% codetab %}}
```python ```python
#dependencies
#dependencies
import random
from time import sleep
import requests
import logging
from dapr.clients import DaprClient from dapr.clients import DaprClient
from dapr.clients.grpc._state import StateItem
from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType
#code #code
logging.basicConfig(level = logging.INFO)
DAPR_STORE_NAME = "statestore" DAPR_STORE_NAME = "statestore"
#Using Dapr SDK to delete the state
with DaprClient() as client: with DaprClient() as client:
client.delete_state(store_name=DAPR_STORE_NAME, key="order_1") client.delete_state(store_name=DAPR_STORE_NAME, key="order_1")
@ -366,26 +500,31 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% codetab %}} {{% codetab %}}
```go ```go
//dependencies
//dependencies
import ( import (
"context"
dapr "github.com/dapr/go-sdk/client" dapr "github.com/dapr/go-sdk/client"
) )
//code //code
func main() {
client, err := dapr.NewClient()
STATE_STORE_NAME := "statestore" STATE_STORE_NAME := "statestore"
//Using Dapr SDK to delete the state
client, err := dapr.NewClient()
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer client.Close() defer client.Close()
ctx := context.Background() ctx := context.Background()
if err := client.DeleteState(ctx, store, "order_1"); err != nil { if err := client.DeleteState(ctx, STATE_STORE_NAME, "order_1"); err != nil {
panic(err) panic(err)
} }
}
``` ```
@ -401,17 +540,26 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% codetab %}} {{% codetab %}}
```javascript ```javascript
//dependencies
//dependencies
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client'; import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client';
//code //code
const daprHost = "127.0.0.1";
var main = function() {
const STATE_STORE_NAME = "statestore"; const STATE_STORE_NAME = "statestore";
//Using Dapr SDK to save and get state
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP); const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
await client.state.delete(STATE_STORE_NAME, "order_1"); await client.state.delete(STATE_STORE_NAME, "order_1");
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main();
``` ```
@ -450,22 +598,41 @@ Below are code examples that leverage Dapr SDKs for saving and retrieving multip
{{% codetab %}} {{% codetab %}}
```java ```java
//dependencies
//dependencies
import io.dapr.client.DaprClient; import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder; import io.dapr.client.DaprClientBuilder;
import reactor.core.publisher.Mono;
import io.dapr.client.domain.State; import io.dapr.client.domain.State;
import java.util.List; import io.dapr.client.domain.TransactionalStateOperation;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import java.util.Random;
import java.util.concurrent.TimeUnit;
//code //code
@SpringBootApplication
public class OrderProcessingServiceApplication {
private static final String STATE_STORE_NAME = "statestore"; private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
public static void main(String[] args) throws InterruptedException{
String STATE_STORE_NAME = "statestore";
//Calling service multiple times with 5 seconds gap in between the calls
while(true) {
TimeUnit.MILLISECONDS.sleep(5000);
Random random = new Random();
int orderId = random.nextInt(1000-1) + 1;
//Using Dapr SDK to retrieve multiple states
DaprClient client = new DaprClientBuilder().build(); DaprClient client = new DaprClientBuilder().build();
Mono<List<State<String>>> resultBulk = client.getBulkState(STATE_STORE_NAME, Mono<List<State<String>>> resultBulk = client.getBulkState(STATE_STORE_NAME,
Arrays.asList("order_1", "order_2"), String.class); Arrays.asList("order_1", "order_2"), String.class);
log.info("Result after get bulk" + resultBulk); }
}
}
``` ```
@ -481,15 +648,27 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% codetab %}} {{% codetab %}}
```python ```python
#dependencies
#dependencies
import random
from time import sleep
import requests
import logging
from dapr.clients import DaprClient from dapr.clients import DaprClient
from dapr.clients.grpc._state import StateItem from dapr.clients.grpc._state import StateItem
from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType
#code #code
logging.basicConfig(level = logging.INFO)
DAPR_STORE_NAME = "statestore" DAPR_STORE_NAME = "statestore"
#Calling service multiple times with 5 seconds gap in between the calls
while True:
sleep(random.randrange(50, 5000) / 1000)
orderId = random.randint(1, 1000)
#Using Dapr SDK to save and retrieve multiple states
with DaprClient() as client: with DaprClient() as client:
client.save_bulk_state(store_name=DAPR_STORE_NAME, states=[StateItem(key="order_2", value=str(orderId))]) client.save_bulk_state(store_name=DAPR_STORE_NAME, states=[StateItem(key="order_2", value=str(orderId))])
result = client.get_bulk_state(store_name=DAPR_STORE_NAME, keys=["order_1", "order_2"], states_metadata={"metakey": "metavalue"}).items result = client.get_bulk_state(store_name=DAPR_STORE_NAME, keys=["order_1", "order_2"], states_metadata={"metakey": "metavalue"}).items
@ -510,14 +689,23 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% codetab %}} {{% codetab %}}
```javascript ```javascript
//dependencies
//dependencies
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client'; import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client';
//code //code
const daprHost = "127.0.0.1";
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP); var main = function() {
const STATE_STORE_NAME = "statestore"; const STATE_STORE_NAME = "statestore";
//Calling service multiple times with 5 seconds gap in between the calls
for(var i=0;i<10;i++) {
sleep(5000);
var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
//Using Dapr SDK to save and retrieve multiple states
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
await client.state.save(STATE_STORE_NAME, [ await client.state.save(STATE_STORE_NAME, [
{ {
key: "order_1", key: "order_1",
@ -530,6 +718,14 @@ await client.state.save(STATE_STORE_NAME, [
]); ]);
result = await client.state.getBulk(STATE_STORE_NAME, ["order_1", "order_2"]); result = await client.state.getBulk(STATE_STORE_NAME, ["order_1", "order_2"]);
console.log("Result after get bulk: " + result); console.log("Result after get bulk: " + result);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main();
``` ```
@ -581,24 +777,46 @@ Below are code examples that leverage Dapr SDKs for performing state transaction
{{% codetab %}} {{% codetab %}}
```csharp ```csharp
//dependencies
//dependencies
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Dapr.Client; using Dapr.Client;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Text.Json;
//code //code
namespace EventService
{
class Program
{
static async Task Main(string[] args)
{
string DAPR_STORE_NAME = "statestore"; string DAPR_STORE_NAME = "statestore";
//Calling service multiple times with 5 seconds gap in between the calls
while(true) {
System.Threading.Thread.Sleep(5000);
Random random = new Random();
int orderId = random.Next(1,1000);
//Using Dapr SDK to perform the state transactions
using var client = new DaprClientBuilder().Build(); using var client = new DaprClientBuilder().Build();
var requests = new List<StateTransactionRequest>() var requests = new List<StateTransactionRequest>()
{ {
new StateTransactionRequest("order_3", JsonSerializer.SerializeToUtf8Bytes(orderId.ToString()), StateOperationType.Upsert), new StateTransactionRequest("order_3", JsonSerializer.SerializeToUtf8Bytes(orderId.ToString()), StateOperationType.Upsert),
new StateTransactionRequest("order_2", null, StateOperationType.Delete) new StateTransactionRequest("order_2", null, StateOperationType.Delete)
}; };
CancellationTokenSource source = new CancellationTokenSource(); CancellationTokenSource source = new CancellationTokenSource();
CancellationToken cancellationToken = source.Token; CancellationToken cancellationToken = source.Token;
await client.ExecuteStateTransactionAsync(DAPR_STORE_NAME, requests, cancellationToken: cancellationToken); await client.ExecuteStateTransactionAsync(DAPR_STORE_NAME, requests, cancellationToken: cancellationToken);
}
}
}
}
``` ```
@ -614,17 +832,38 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% codetab %}} {{% codetab %}}
```java ```java
//dependencies
//dependencies
import io.dapr.client.DaprClient; import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder; import io.dapr.client.DaprClientBuilder;
import io.dapr.client.domain.State; import io.dapr.client.domain.State;
import io.dapr.client.domain.TransactionalStateOperation; import io.dapr.client.domain.TransactionalStateOperation;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import reactor.core.publisher.Mono;
import java.util.Random;
import java.util.concurrent.TimeUnit;
//code //code
@SpringBootApplication
public class OrderProcessingServiceApplication {
private static final String STATE_STORE_NAME = "statestore"; private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
public static void main(String[] args) throws InterruptedException{
String STATE_STORE_NAME = "statestore";
//Calling service multiple times with 5 seconds gap in between the calls
while(true) {
TimeUnit.MILLISECONDS.sleep(5000);
Random random = new Random();
int orderId = random.nextInt(1000-1) + 1;
//Using Dapr SDK to perform the state transactions
DaprClient client = new DaprClientBuilder().build(); DaprClient client = new DaprClientBuilder().build();
List<TransactionalStateOperation<?>> operationList = new ArrayList<>(); List<TransactionalStateOperation<?>> operationList = new ArrayList<>();
operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.OperationType.UPSERT, operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.OperationType.UPSERT,
@ -632,6 +871,9 @@ operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.
operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.OperationType.DELETE, operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.OperationType.DELETE,
new State<>("order_2"))); new State<>("order_2")));
client.executeStateTransaction(STATE_STORE_NAME, operationList).block(); client.executeStateTransaction(STATE_STORE_NAME, operationList).block();
}
}
}
``` ```
@ -647,15 +889,27 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% codetab %}} {{% codetab %}}
```python ```python
#dependencies
#dependencies
import random
from time import sleep
import requests
import logging
from dapr.clients import DaprClient from dapr.clients import DaprClient
from dapr.clients.grpc._state import StateItem from dapr.clients.grpc._state import StateItem
from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType
#code #code
logging.basicConfig(level = logging.INFO)
DAPR_STORE_NAME = "statestore" DAPR_STORE_NAME = "statestore"
#Calling service multiple times with 5 seconds gap in between the calls
while True:
sleep(random.randrange(50, 5000) / 1000)
orderId = random.randint(1, 1000)
#Using Dapr SDK to perform the state transactions
with DaprClient() as client: with DaprClient() as client:
client.execute_state_transaction(store_name=DAPR_STORE_NAME, operations=[ client.execute_state_transaction(store_name=DAPR_STORE_NAME, operations=[
TransactionalStateOperation( TransactionalStateOperation(
@ -684,14 +938,22 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
{{% codetab %}} {{% codetab %}}
```javascript ```javascript
//dependencies
//dependencies
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client'; import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client';
//code //code
const daprHost = "127.0.0.1";
var main = function() {
const STATE_STORE_NAME = "statestore"; const STATE_STORE_NAME = "statestore";
//Calling service multiple times with 5 seconds gap in between the calls
for(var i=0;i<10;i++) {
sleep(5000);
var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
//Using Dapr SDK to save and retrieve multiple states
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP); const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
await client.state.transaction(STATE_STORE_NAME, [ await client.state.transaction(STATE_STORE_NAME, [
{ {
@ -708,6 +970,14 @@ await client.state.transaction(STATE_STORE_NAME, [
} }
} }
]); ]);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main();
``` ```

View File

@ -92,7 +92,7 @@ You can then interact with the server using the client port: `localhost:4222`.
{{% /codetab %}} {{% /codetab %}}
{{% codetab %}} {{% codetab %}}
Install NATS on Kubernetes by using the [kubectl](https://docs.nats.io/nats-on-kubernetes/minimal-setup): Install NATS on Kubernetes by using the [kubectl](https://docs.nats.io/running-a-nats-service/introduction/running/nats-kubernetes/minimal-setup#minimal-nats-setup):
```bash ```bash
# Single server NATS # Single server NATS