mirror of https://github.com/dapr/docs.git
Merge pull request #2026 from amulyavarote/patch/add_full_code_snippets
Added complete code snippets of building blocks for all SDKs
This commit is contained in:
commit
bcb4a2baac
|
@ -201,8 +201,11 @@ Below are code examples that leverage Dapr SDKs to subscribe to a topic.
|
|||
{{% codetab %}}
|
||||
|
||||
```csharp
|
||||
|
||||
//dependencies
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Dapr;
|
||||
using Dapr.Client;
|
||||
|
||||
|
@ -212,7 +215,7 @@ namespace CheckoutService.controller
|
|||
[ApiController]
|
||||
public class CheckoutServiceController : Controller
|
||||
{
|
||||
//Subscribe to a topic
|
||||
//Subscribe to a topic
|
||||
[Topic("order_pub_sub", "orders")]
|
||||
[HttpPost("checkout")]
|
||||
public void getCheckout([FromBody] int orderId)
|
||||
|
@ -237,6 +240,10 @@ dapr run --app-id checkout --app-port 6002 --dapr-http-port 3602 --dapr-grpc-por
|
|||
//dependencies
|
||||
import io.dapr.Topic;
|
||||
import io.dapr.client.domain.CloudEvent;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
//code
|
||||
|
@ -244,7 +251,7 @@ import reactor.core.publisher.Mono;
|
|||
public class CheckoutServiceController {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(CheckoutServiceController.class);
|
||||
//Subscribe to a topic
|
||||
//Subscribe to a topic
|
||||
@Topic(name = "orders", pubsubName = "order_pub_sub")
|
||||
@PostMapping(path = "/checkout")
|
||||
public Mono<Void> getCheckout(@RequestBody(required = false) CloudEvent<String> cloudEvent) {
|
||||
|
@ -273,11 +280,12 @@ dapr run --app-id checkout --app-port 6002 --dapr-http-port 3602 --dapr-grpc-por
|
|||
#dependencies
|
||||
from cloudevents.sdk.event import v1
|
||||
from dapr.ext.grpc import App
|
||||
import logging
|
||||
import json
|
||||
|
||||
#code
|
||||
app = App()
|
||||
logging.basicConfig(level = logging.INFO)
|
||||
|
||||
#Subscribe to a topic
|
||||
@app.subscribe(pubsub_name='order_pub_sub', topic='orders')
|
||||
def mytopic(event: v1.Event) -> None:
|
||||
|
@ -317,7 +325,7 @@ var sub = &common.Subscription{
|
|||
|
||||
func main() {
|
||||
s := daprd.NewService(":6002")
|
||||
//Subscribe to a topic
|
||||
//Subscribe to a topic
|
||||
if err := s.AddTopicEventHandler(sub, eventHandler); err != nil {
|
||||
log.Fatalf("error adding topic subscription: %v", err)
|
||||
}
|
||||
|
@ -330,7 +338,6 @@ func eventHandler(ctx context.Context, e *common.TopicEvent) (retry bool, err er
|
|||
log.Printf("Subscriber received: %s", e.Data)
|
||||
return false, nil
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -344,7 +351,6 @@ dapr run --app-id checkout --app-port 6002 --dapr-http-port 3602 --dapr-grpc-por
|
|||
{{% codetab %}}
|
||||
|
||||
```javascript
|
||||
|
||||
//dependencies
|
||||
import { DaprServer, CommunicationProtocolEnum } from 'dapr-client';
|
||||
|
||||
|
@ -365,14 +371,13 @@ async function start(orderId) {
|
|||
daprHost,
|
||||
process.env.DAPR_HTTP_PORT,
|
||||
CommunicationProtocolEnum.HTTP
|
||||
);
|
||||
//Subscribe to a topic
|
||||
);
|
||||
//Subscribe to a topic
|
||||
await server.pubsub.subscribe("order_pub_sub", "orders", async (orderId) => {
|
||||
console.log(`Subscriber received: ${JSON.stringify(orderId)}`)
|
||||
});
|
||||
await server.startServer();
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -389,8 +394,6 @@ The `/checkout` endpoint matches the `route` defined in the subscriptions and th
|
|||
|
||||
## Step 3: Publish a topic
|
||||
|
||||
To publish a topic you need to run an instance of a Dapr sidecar to use the pubsub Redis component. You can use the default Redis component installed into your local environment.
|
||||
|
||||
Start an instance of Dapr with an app-id called `orderprocessing`:
|
||||
|
||||
```bash
|
||||
|
@ -432,9 +435,15 @@ Below are code examples that leverage Dapr SDKs to publish a topic.
|
|||
{{% codetab %}}
|
||||
|
||||
```csharp
|
||||
|
||||
//dependencies
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
using Dapr.Client;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Threading;
|
||||
|
||||
//code
|
||||
namespace EventService
|
||||
|
@ -443,19 +452,22 @@ namespace EventService
|
|||
{
|
||||
static async Task Main(string[] args)
|
||||
{
|
||||
string PUBSUB_NAME = "order_pub_sub";
|
||||
string TOPIC_NAME = "orders";
|
||||
int orderId = 100;
|
||||
CancellationTokenSource source = new CancellationTokenSource();
|
||||
CancellationToken cancellationToken = source.Token;
|
||||
using var client = new DaprClientBuilder().Build();
|
||||
//Using Dapr SDK to publish a topic
|
||||
await client.PublishEventAsync(PUBSUB_NAME, TOPIC_NAME, orderId, cancellationToken);
|
||||
Console.WriteLine("Published data: " + orderId);
|
||||
string PUBSUB_NAME = "order_pub_sub";
|
||||
string TOPIC_NAME = "orders";
|
||||
while(true) {
|
||||
System.Threading.Thread.Sleep(5000);
|
||||
Random random = new Random();
|
||||
int orderId = random.Next(1,1000);
|
||||
CancellationTokenSource source = new CancellationTokenSource();
|
||||
CancellationToken cancellationToken = source.Token;
|
||||
using var client = new DaprClientBuilder().Build();
|
||||
//Using Dapr SDK to publish a topic
|
||||
await client.PublishEventAsync(PUBSUB_NAME, TOPIC_NAME, orderId, cancellationToken);
|
||||
Console.WriteLine("Published data: " + orderId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -474,29 +486,38 @@ import io.dapr.client.DaprClient;
|
|||
import io.dapr.client.DaprClientBuilder;
|
||||
import io.dapr.client.domain.Metadata;
|
||||
import static java.util.Collections.singletonMap;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
//code
|
||||
@SpringBootApplication
|
||||
public class OrderProcessingServiceApplication {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException{
|
||||
String MESSAGE_TTL_IN_SECONDS = "1000";
|
||||
String TOPIC_NAME = "orders";
|
||||
String PUBSUB_NAME = "order_pub_sub";
|
||||
private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
|
||||
|
||||
int orderId = 100;
|
||||
DaprClient client = new DaprClientBuilder().build();
|
||||
//Using Dapr SDK to publish a topic
|
||||
client.publishEvent(
|
||||
PUBSUB_NAME,
|
||||
TOPIC_NAME,
|
||||
orderId,
|
||||
singletonMap(Metadata.TTL_IN_SECONDS, MESSAGE_TTL_IN_SECONDS)).block();
|
||||
log.info("Published data:" + orderId);
|
||||
}
|
||||
public static void main(String[] args) throws InterruptedException{
|
||||
String MESSAGE_TTL_IN_SECONDS = "1000";
|
||||
String TOPIC_NAME = "orders";
|
||||
String PUBSUB_NAME = "order_pub_sub";
|
||||
|
||||
while(true) {
|
||||
TimeUnit.MILLISECONDS.sleep(5000);
|
||||
Random random = new Random();
|
||||
int orderId = random.nextInt(1000-1) + 1;
|
||||
DaprClient client = new DaprClientBuilder().build();
|
||||
//Using Dapr SDK to publish a topic
|
||||
client.publishEvent(
|
||||
PUBSUB_NAME,
|
||||
TOPIC_NAME,
|
||||
orderId,
|
||||
singletonMap(Metadata.TTL_IN_SECONDS, MESSAGE_TTL_IN_SECONDS)).block();
|
||||
log.info("Published data:" + orderId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -511,22 +532,29 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
|
||||
```python
|
||||
#dependencies
|
||||
import random
|
||||
from time import sleep
|
||||
import requests
|
||||
import logging
|
||||
import json
|
||||
from dapr.clients import DaprClient
|
||||
|
||||
#code
|
||||
logging.basicConfig(level = logging.INFO)
|
||||
|
||||
orderId = 100
|
||||
with DaprClient() as client:
|
||||
#Using Dapr SDK to publish a topic
|
||||
result = client.publish_event(
|
||||
pubsub_name='order_pub_sub',
|
||||
topic_name='orders',
|
||||
data=json.dumps(orderId),
|
||||
data_content_type='application/json',
|
||||
)
|
||||
logging.info('Published data: ' + str(orderId))
|
||||
|
||||
while True:
|
||||
sleep(random.randrange(50, 5000) / 1000)
|
||||
orderId = random.randint(1, 1000)
|
||||
PUBSUB_NAME = 'order_pub_sub'
|
||||
TOPIC_NAME = 'orders'
|
||||
with DaprClient() as client:
|
||||
#Using Dapr SDK to publish a topic
|
||||
result = client.publish_event(
|
||||
pubsub_name=PUBSUB_NAME,
|
||||
topic_name=TOPIC_NAME,
|
||||
data=json.dumps(orderId),
|
||||
data_content_type='application/json',
|
||||
)
|
||||
logging.info('Published data: ' + str(orderId))
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -542,35 +570,39 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --app-pr
|
|||
```go
|
||||
//dependencies
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"strconv"
|
||||
dapr "github.com/dapr/go-sdk/client"
|
||||
|
||||
"context"
|
||||
"log"
|
||||
"math/rand"
|
||||
"time"
|
||||
"strconv"
|
||||
dapr "github.com/dapr/go-sdk/client"
|
||||
)
|
||||
|
||||
//code
|
||||
var (
|
||||
PUBSUB_NAME = "order_pub_sub"
|
||||
TOPIC_NAME = "orders"
|
||||
PUBSUB_NAME = "order_pub_sub"
|
||||
TOPIC_NAME = "orders"
|
||||
)
|
||||
|
||||
func main() {
|
||||
orderId := 100
|
||||
client, err := dapr.NewClient()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer client.Close()
|
||||
ctx := context.Background()
|
||||
for i := 0; i < 10; i++ {
|
||||
time.Sleep(5000)
|
||||
orderId := rand.Intn(1000-1) + 1
|
||||
client, err := dapr.NewClient()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer client.Close()
|
||||
ctx := context.Background()
|
||||
//Using Dapr SDK to publish a topic
|
||||
if err := client.PublishEvent(ctx, PUBSUB_NAME, TOPIC_NAME, []byte(strconv.Itoa(orderId)));
|
||||
err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Println("Published data: " + strconv.Itoa(orderId))
|
||||
if err := client.PublishEvent(ctx, PUBSUB_NAME, TOPIC_NAME, []byte(strconv.Itoa(orderId)));
|
||||
err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
log.Println("Published data: " + strconv.Itoa(orderId))
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -587,26 +619,33 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
//dependencies
|
||||
import { DaprServer, DaprClient, CommunicationProtocolEnum } from 'dapr-client';
|
||||
|
||||
//code
|
||||
const daprHost = "127.0.0.1";
|
||||
|
||||
var main = function() {
|
||||
var orderId = 100;
|
||||
start(orderId).catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
for(var i=0;i<10;i++) {
|
||||
sleep(5000);
|
||||
var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
|
||||
start(orderId).catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function start(orderId) {
|
||||
const PUBSUB_NAME = "order_pub_sub"
|
||||
const TOPIC_NAME = "orders"
|
||||
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
|
||||
console.log("Published data:" + orderId)
|
||||
//Using Dapr SDK to publish a topic
|
||||
await client.pubsub.publish("order_pub_sub", "orders", orderId);
|
||||
await client.pubsub.publish(PUBSUB_NAME, TOPIC_NAME, orderId);
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
main();
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
|
|
@ -55,7 +55,6 @@ To configure a different kind of secret store see the guidance on [how to config
|
|||
|
||||
Run the Dapr sidecar with the application.
|
||||
|
||||
|
||||
{{< tabs Dotnet Java Python Go Javascript>}}
|
||||
|
||||
{{% codetab %}}
|
||||
|
@ -110,9 +109,16 @@ Once you have a secret store, call Dapr to get the secrets from your application
|
|||
|
||||
{{% codetab %}}
|
||||
```csharp
|
||||
|
||||
//dependencies
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
using Dapr.Client;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Threading;
|
||||
using System.Text.Json;
|
||||
|
||||
//code
|
||||
namespace EventService
|
||||
|
@ -126,54 +132,59 @@ namespace EventService
|
|||
//Using Dapr SDK to get a secret
|
||||
var secret = await client.GetSecretAsync(SECRET_STORE_NAME, "secret");
|
||||
Console.WriteLine($"Result: {string.Join(", ", secret)}");
|
||||
Console.WriteLine($"Result for bulk: {string.Join(", ", secret.Keys)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
{{% /codetab %}}
|
||||
|
||||
{{% codetab %}}
|
||||
|
||||
```java
|
||||
|
||||
//dependencies
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.dapr.client.DaprClient;
|
||||
import io.dapr.client.DaprClientBuilder;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
//code
|
||||
@SpringBootApplication
|
||||
public class OrderProcessingServiceApplication {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
|
||||
private static final ObjectMapper JSON_SERIALIZER = new ObjectMapper();
|
||||
private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
|
||||
private static final ObjectMapper JSON_SERIALIZER = new ObjectMapper();
|
||||
|
||||
private static final String SECRET_STORE_NAME = "localsecretstore";
|
||||
private static final String SECRET_STORE_NAME = "localsecretstore";
|
||||
|
||||
public static void main(String[] args) throws InterruptedException, JsonProcessingException {
|
||||
DaprClient client = new DaprClientBuilder().build();
|
||||
public static void main(String[] args) throws InterruptedException, JsonProcessingException {
|
||||
DaprClient client = new DaprClientBuilder().build();
|
||||
//Using Dapr SDK to get a secret
|
||||
Map<String, String> secret = client.getSecret(SECRET_STORE_NAME, "secret").block();
|
||||
log.info("Result: " + JSON_SERIALIZER.writeValueAsString(secret));
|
||||
}
|
||||
Map<String, String> secret = client.getSecret(SECRET_STORE_NAME, "secret").block();
|
||||
log.info("Result: " + JSON_SERIALIZER.writeValueAsString(secret));
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
{{% /codetab %}}
|
||||
|
||||
{{% codetab %}}
|
||||
|
||||
```python
|
||||
|
||||
#dependencies
|
||||
import random
|
||||
from time import sleep
|
||||
import requests
|
||||
import logging
|
||||
from dapr.clients import DaprClient
|
||||
from dapr.clients.grpc._state import StateItem
|
||||
from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType
|
||||
|
||||
#code
|
||||
logging.basicConfig(level = logging.INFO)
|
||||
|
||||
DAPR_STORE_NAME = "localsecretstore"
|
||||
key = 'secret'
|
||||
|
||||
|
@ -182,21 +193,21 @@ with DaprClient() as client:
|
|||
secret = client.get_secret(store_name=DAPR_STORE_NAME, key=key)
|
||||
logging.info('Result: ')
|
||||
logging.info(secret.secret)
|
||||
#Using Dapr SDK to get bulk secrets
|
||||
secret = client.get_bulk_secret(store_name=DAPR_STORE_NAME)
|
||||
logging.info('Result for bulk secret: ')
|
||||
logging.info(sorted(secret.secrets.items()))
|
||||
|
||||
```
|
||||
{{% /codetab %}}
|
||||
|
||||
{{% codetab %}}
|
||||
|
||||
```go
|
||||
|
||||
//dependencies
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
dapr "github.com/dapr/go-sdk/client"
|
||||
)
|
||||
|
||||
|
@ -209,35 +220,26 @@ func main() {
|
|||
}
|
||||
defer client.Close()
|
||||
ctx := context.Background()
|
||||
|
||||
//Using Dapr SDK to get a secret
|
||||
secret, err := client.GetSecret(ctx, SECRET_STORE_NAME, "secret", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Got error for accessing key")
|
||||
}
|
||||
|
||||
if secret != nil {
|
||||
log.Println("Result : ")
|
||||
log.Println(secret)
|
||||
}
|
||||
|
||||
secretRandom, err := client.GetBulkSecret(ctx, SECRET_STORE_NAME, nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Got error for accessing key")
|
||||
}
|
||||
//Using Dapr SDK to get bulk secrets
|
||||
secretBulk, err := client.GetBulkSecret(ctx, SECRET_STORE_NAME, nil)
|
||||
|
||||
if secret != nil {
|
||||
log.Println("Result for bulk: ")
|
||||
log.Println(secretRandom)
|
||||
log.Println(secretBulk)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
{{% /codetab %}}
|
||||
|
||||
{{% codetab %}}
|
||||
|
||||
```javascript
|
||||
|
||||
//dependencies
|
||||
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client';
|
||||
|
||||
|
@ -247,14 +249,15 @@ const daprHost = "127.0.0.1";
|
|||
async function main() {
|
||||
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
|
||||
const SECRET_STORE_NAME = "localsecretstore";
|
||||
//Using Dapr SDK to get a secret
|
||||
var secret = await client.secret.get(SECRET_STORE_NAME, "secret");
|
||||
console.log("Result: " + secret);
|
||||
//Using Dapr SDK to get bulk secrets
|
||||
secret = await client.secret.getBulk(SECRET_STORE_NAME);
|
||||
console.log("Result for bulk: " + secret);
|
||||
}
|
||||
|
||||
main();
|
||||
|
||||
```
|
||||
{{% /codetab %}}
|
||||
|
||||
|
@ -267,4 +270,4 @@ main();
|
|||
- [Configure a secret store]({{<ref setup-secret-store>}})
|
||||
- [Supported secrets]({{<ref supported-secret-stores>}})
|
||||
- [Using secrets in components]({{<ref component-secrets>}})
|
||||
- [Secret stores quickstart](https://github.com/dapr/quickstarts/tree/master/secretstore)
|
||||
- [Secret stores quickstart](https://github.com/dapr/quickstarts/tree/master/secretstore)
|
||||
|
|
|
@ -183,9 +183,15 @@ Below are code examples that leverage Dapr SDKs for service invocation.
|
|||
|
||||
{{% codetab %}}
|
||||
```csharp
|
||||
|
||||
//dependencies
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
using Dapr.Client;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Threading;
|
||||
|
||||
//code
|
||||
namespace EventService
|
||||
|
@ -194,113 +200,165 @@ namespace EventService
|
|||
{
|
||||
static async Task Main(string[] args)
|
||||
{
|
||||
int orderId = 100;
|
||||
CancellationTokenSource source = new CancellationTokenSource();
|
||||
CancellationToken cancellationToken = source.Token;
|
||||
//Using Dapr SDK to invoke a method
|
||||
using var client = new DaprClientBuilder().Build();
|
||||
var result = client.CreateInvokeMethodRequest(HttpMethod.Get, "checkout", "checkout/" + orderId, cancellationToken);
|
||||
await client.InvokeMethodAsync(result);
|
||||
while(true) {
|
||||
System.Threading.Thread.Sleep(5000);
|
||||
Random random = new Random();
|
||||
int orderId = random.Next(1,1000);
|
||||
CancellationTokenSource source = new CancellationTokenSource();
|
||||
CancellationToken cancellationToken = source.Token;
|
||||
using var client = new DaprClientBuilder().Build();
|
||||
//Using Dapr SDK to invoke a method
|
||||
var result = client.CreateInvokeMethodRequest(HttpMethod.Get, "checkout", "checkout/" + orderId, cancellationToken);
|
||||
await client.InvokeMethodAsync(result);
|
||||
Console.WriteLine("Order requested: " + orderId);
|
||||
Console.WriteLine("Result: " + result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
{{% /codetab %}}
|
||||
|
||||
|
||||
{{% codetab %}}
|
||||
```java
|
||||
|
||||
//dependencies
|
||||
import io.dapr.client.DaprClient;
|
||||
import io.dapr.client.DaprClientBuilder;
|
||||
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
|
||||
@SpringBootApplication
|
||||
public class OrderProcessingServiceApplication {
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
int orderId = 100;
|
||||
//Using Dapr SDK to invoke a method
|
||||
DaprClient client = new DaprClientBuilder().build();
|
||||
var result = client.invokeMethod(
|
||||
"checkout",
|
||||
"checkout/" + orderId,
|
||||
null,
|
||||
HttpExtension.GET,
|
||||
String.class
|
||||
);
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
|
||||
|
||||
public static void main(String[] args) throws InterruptedException{
|
||||
while(true) {
|
||||
TimeUnit.MILLISECONDS.sleep(5000);
|
||||
Random random = new Random();
|
||||
int orderId = random.nextInt(1000-1) + 1;
|
||||
DaprClient daprClient = new DaprClientBuilder().build();
|
||||
//Using Dapr SDK to invoke a method
|
||||
var result = daprClient.invokeMethod(
|
||||
"checkout",
|
||||
"checkout/" + orderId,
|
||||
null,
|
||||
HttpExtension.GET,
|
||||
String.class
|
||||
);
|
||||
log.info("Order requested: " + orderId);
|
||||
log.info("Result: " + result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
{{% /codetab %}}
|
||||
|
||||
{{% codetab %}}
|
||||
```python
|
||||
|
||||
#dependencies
|
||||
import random
|
||||
from time import sleep
|
||||
import requests
|
||||
import logging
|
||||
from dapr.clients import DaprClient
|
||||
|
||||
#code
|
||||
orderId = 100
|
||||
#Using Dapr SDK to invoke a method
|
||||
with DaprClient() as client:
|
||||
result = client.invoke_method(
|
||||
"checkout",
|
||||
f"checkout/{orderId}",
|
||||
data=b'',
|
||||
http_verb="GET"
|
||||
)
|
||||
|
||||
logging.basicConfig(level = logging.INFO)
|
||||
while True:
|
||||
sleep(random.randrange(50, 5000) / 1000)
|
||||
orderId = random.randint(1, 1000)
|
||||
with DaprClient() as daprClient:
|
||||
#Using Dapr SDK to invoke a method
|
||||
result = daprClient.invoke_method(
|
||||
"checkout",
|
||||
f"checkout/{orderId}",
|
||||
data=b'',
|
||||
http_verb="GET"
|
||||
)
|
||||
logging.basicConfig(level = logging.INFO)
|
||||
logging.info('Order requested: ' + str(orderId))
|
||||
logging.info('Result: ' + str(result))
|
||||
```
|
||||
{{% /codetab %}}
|
||||
|
||||
{{% codetab %}}
|
||||
```go
|
||||
|
||||
//dependencies
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"math/rand"
|
||||
"time"
|
||||
"strconv"
|
||||
dapr "github.com/dapr/go-sdk/client"
|
||||
|
||||
)
|
||||
|
||||
//code
|
||||
func main() {
|
||||
orderId := 100
|
||||
//Using Dapr SDK to invoke a method
|
||||
client, err := dapr.NewClient()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer client.Close()
|
||||
ctx := context.Background()
|
||||
result, err := client.InvokeMethod(ctx, "checkout", "checkout/" + strconv.Itoa(orderId), "get")
|
||||
type Order struct {
|
||||
orderName string
|
||||
orderNum string
|
||||
}
|
||||
|
||||
func main() {
|
||||
for i := 0; i < 10; i++ {
|
||||
time.Sleep(5000)
|
||||
orderId := rand.Intn(1000-1) + 1
|
||||
client, err := dapr.NewClient()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer client.Close()
|
||||
ctx := context.Background()
|
||||
//Using Dapr SDK to invoke a method
|
||||
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 %}}
|
||||
```javascript
|
||||
|
||||
//dependencies
|
||||
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client';
|
||||
|
||||
//code
|
||||
const daprHost = "127.0.0.1";
|
||||
const daprHost = "127.0.0.1";
|
||||
|
||||
var main = function() {
|
||||
var orderId = 100;
|
||||
//Using Dapr SDK to invoke a method
|
||||
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
|
||||
const result = await client.invoker.invoke('checkout' , "checkout/" + orderId , HttpMethod.GET);
|
||||
for(var i=0;i<10;i++) {
|
||||
sleep(5000);
|
||||
var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
|
||||
start(orderId).catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function start(orderId) {
|
||||
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
|
||||
//Using Dapr SDK to invoke a method
|
||||
const result = await client.invoker.invoke('checkoutservice' , "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 %}}
|
||||
|
||||
|
|
|
@ -81,7 +81,15 @@ Below are code examples that leverage Dapr SDKs for saving and retrieving a sing
|
|||
```csharp
|
||||
|
||||
//dependencies
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
using Dapr.Client;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Threading;
|
||||
using System.Text.Json;
|
||||
|
||||
//code
|
||||
namespace EventService
|
||||
|
@ -91,17 +99,20 @@ namespace EventService
|
|||
static async Task Main(string[] args)
|
||||
{
|
||||
string DAPR_STORE_NAME = "statestore";
|
||||
|
||||
int orderId = 100;
|
||||
//Using Dapr SDK to save and get state
|
||||
using var client = new DaprClientBuilder().Build();
|
||||
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());
|
||||
while(true) {
|
||||
System.Threading.Thread.Sleep(5000);
|
||||
using var client = new DaprClientBuilder().Build();
|
||||
Random random = new Random();
|
||||
int orderId = random.Next(1,1000);
|
||||
//Using Dapr SDK to save and get state
|
||||
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());
|
||||
Console.WriteLine("Result after get: " + result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -116,12 +127,17 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
{{% codetab %}}
|
||||
|
||||
```java
|
||||
|
||||
//dependencies
|
||||
import io.dapr.client.DaprClient;
|
||||
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
|
||||
@SpringBootApplication
|
||||
|
@ -129,18 +145,23 @@ public class OrderProcessingServiceApplication {
|
|||
|
||||
private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
String STATE_STORE_NAME = "statestore";
|
||||
private static final String STATE_STORE_NAME = "statestore";
|
||||
|
||||
int orderId = 100;
|
||||
//Using Dapr SDK to save and get state
|
||||
DaprClient client = new DaprClientBuilder().build();
|
||||
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);
|
||||
public static void main(String[] args) throws InterruptedException{
|
||||
while(true) {
|
||||
TimeUnit.MILLISECONDS.sleep(5000);
|
||||
Random random = new Random();
|
||||
int orderId = random.nextInt(1000-1) + 1;
|
||||
DaprClient client = new DaprClientBuilder().build();
|
||||
//Using Dapr SDK to save and get state
|
||||
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);
|
||||
log.info("Result after get" + result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -155,22 +176,26 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
{{% codetab %}}
|
||||
|
||||
```python
|
||||
|
||||
#dependencies
|
||||
import random
|
||||
from time import sleep
|
||||
import requests
|
||||
import logging
|
||||
from dapr.clients import DaprClient
|
||||
from dapr.clients.grpc._state import StateItem
|
||||
from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType
|
||||
|
||||
#code
|
||||
logging.basicConfig(level = logging.INFO)
|
||||
|
||||
DAPR_STORE_NAME = "statestore"
|
||||
|
||||
orderId = 100
|
||||
#Using Dapr SDK to save and get state
|
||||
with DaprClient() as client:
|
||||
client.save_state(DAPR_STORE_NAME, "order_1", str(orderId))
|
||||
result = client.get_state(DAPR_STORE_NAME, "order_1")
|
||||
logging.info('Result after get: ' + str(result))
|
||||
|
||||
while True:
|
||||
sleep(random.randrange(50, 5000) / 1000)
|
||||
orderId = random.randint(1, 1000)
|
||||
with DaprClient() as client:
|
||||
#Using Dapr SDK to save and get state
|
||||
client.save_state(DAPR_STORE_NAME, "order_1", str(orderId))
|
||||
result = client.get_state(DAPR_STORE_NAME, "order_1")
|
||||
logging.info('Result after get: ' + str(result))
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -185,7 +210,6 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
{{% codetab %}}
|
||||
|
||||
```go
|
||||
|
||||
//dependencies
|
||||
import (
|
||||
"context"
|
||||
|
@ -194,34 +218,32 @@ import (
|
|||
"time"
|
||||
"strconv"
|
||||
dapr "github.com/dapr/go-sdk/client"
|
||||
|
||||
)
|
||||
|
||||
//code
|
||||
func main() {
|
||||
|
||||
STATE_STORE_NAME := "statestore"
|
||||
|
||||
orderId := 100
|
||||
|
||||
//Using Dapr SDK to save and get state
|
||||
client, err := dapr.NewClient()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer client.Close()
|
||||
ctx := context.Background()
|
||||
|
||||
if err := client.SaveState(ctx, STATE_STORE_NAME, "order_1", []byte(strconv.Itoa(orderId))); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
result, err := client.GetState(ctx, STATE_STORE_NAME, "order_1")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
for i := 0; i < 10; i++ {
|
||||
time.Sleep(5000)
|
||||
orderId := rand.Intn(1000-1) + 1
|
||||
client, err := dapr.NewClient()
|
||||
STATE_STORE_NAME := "statestore"
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer client.Close()
|
||||
ctx := context.Background()
|
||||
//Using Dapr SDK to save and get state
|
||||
if err := client.SaveState(ctx, STATE_STORE_NAME, "order_1", []byte(strconv.Itoa(orderId))); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
result, err := client.GetState(ctx, STATE_STORE_NAME, "order_2")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
log.Println("Result after get: ")
|
||||
log.Println(result)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -236,19 +258,26 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
{{% codetab %}}
|
||||
|
||||
```javascript
|
||||
|
||||
//dependencies
|
||||
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client';
|
||||
|
||||
//code
|
||||
const daprHost = "127.0.0.1";
|
||||
|
||||
var main = function() {
|
||||
const STATE_STORE_NAME = "statestore";
|
||||
for(var i=0;i<10;i++) {
|
||||
sleep(5000);
|
||||
var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
|
||||
start(orderId).catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
var orderId = 100;
|
||||
//Using Dapr SDK to save and get state
|
||||
async function start(orderId) {
|
||||
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
|
||||
const STATE_STORE_NAME = "statestore";
|
||||
//Using Dapr SDK to save and get state
|
||||
await client.state.save(STATE_STORE_NAME, [
|
||||
{
|
||||
key: "order_1",
|
||||
|
@ -260,10 +289,14 @@ var main = function() {
|
|||
}
|
||||
]);
|
||||
var result = await client.state.get(STATE_STORE_NAME, "order_1");
|
||||
console.log("Result after get: " + result);
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
main();
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -329,7 +362,6 @@ Below are code examples that leverage Dapr SDKs for deleting the state.
|
|||
{{% codetab %}}
|
||||
|
||||
```csharp
|
||||
|
||||
//dependencies
|
||||
using Dapr.Client;
|
||||
|
||||
|
@ -347,7 +379,6 @@ namespace EventService
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -362,10 +393,10 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
{{% codetab %}}
|
||||
|
||||
```java
|
||||
|
||||
//dependencies
|
||||
import io.dapr.client.DaprClient;
|
||||
import io.dapr.client.DaprClientBuilder;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
//code
|
||||
@SpringBootApplication
|
||||
|
@ -379,7 +410,6 @@ public class OrderProcessingServiceApplication {
|
|||
client.deleteState(STATE_STORE_NAME, "order_1", storedEtag, null).block();
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -394,19 +424,16 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
{{% codetab %}}
|
||||
|
||||
```python
|
||||
|
||||
#dependencies
|
||||
from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType
|
||||
|
||||
#code
|
||||
logging.basicConfig(level = logging.INFO)
|
||||
|
||||
DAPR_STORE_NAME = "statestore"
|
||||
|
||||
#Using Dapr SDK to delete the state
|
||||
with DaprClient() as client:
|
||||
client.delete_state(store_name=DAPR_STORE_NAME, key="order_1")
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -421,7 +448,6 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
{{% codetab %}}
|
||||
|
||||
```go
|
||||
|
||||
//dependencies
|
||||
import (
|
||||
"context"
|
||||
|
@ -431,9 +457,7 @@ import (
|
|||
|
||||
//code
|
||||
func main() {
|
||||
|
||||
STATE_STORE_NAME := "statestore"
|
||||
|
||||
//Using Dapr SDK to delete the state
|
||||
client, err := dapr.NewClient()
|
||||
if err != nil {
|
||||
|
@ -446,7 +470,6 @@ func main() {
|
|||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -461,23 +484,19 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
{{% codetab %}}
|
||||
|
||||
```javascript
|
||||
|
||||
//dependencies
|
||||
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client';
|
||||
|
||||
//code
|
||||
const daprHost = "127.0.0.1";
|
||||
|
||||
var main = function() {
|
||||
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);
|
||||
await client.state.delete(STATE_STORE_NAME, "order_1");
|
||||
}
|
||||
|
||||
main();
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -515,11 +534,11 @@ Below are code examples that leverage Dapr SDKs for saving and retrieving multip
|
|||
{{% codetab %}}
|
||||
|
||||
```java
|
||||
|
||||
//dependencies
|
||||
import io.dapr.client.DaprClient;
|
||||
import io.dapr.client.DaprClientBuilder;
|
||||
import io.dapr.client.domain.State;
|
||||
import java.util.Arrays;
|
||||
|
||||
//code
|
||||
@SpringBootApplication
|
||||
|
@ -529,15 +548,12 @@ public class OrderProcessingServiceApplication {
|
|||
|
||||
public static void main(String[] args) throws InterruptedException{
|
||||
String STATE_STORE_NAME = "statestore";
|
||||
|
||||
int orderId = 100;
|
||||
//Using Dapr SDK to retrieve multiple states
|
||||
DaprClient client = new DaprClientBuilder().build();
|
||||
Mono<List<State<String>>> resultBulk = client.getBulkState(STATE_STORE_NAME,
|
||||
Arrays.asList("order_1", "order_2"), String.class);
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -548,27 +564,22 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
|
||||
{{% /codetab %}}
|
||||
|
||||
|
||||
{{% codetab %}}
|
||||
|
||||
```python
|
||||
|
||||
#dependencies
|
||||
from dapr.clients import DaprClient
|
||||
from dapr.clients.grpc._state import StateItem
|
||||
|
||||
#code
|
||||
logging.basicConfig(level = logging.INFO)
|
||||
|
||||
DAPR_STORE_NAME = "statestore"
|
||||
|
||||
orderId = 100
|
||||
#Using Dapr SDK to save and retrieve multiple states
|
||||
with DaprClient() as client:
|
||||
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
|
||||
logging.info('Result after get bulk: ' + str(result))
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -579,21 +590,16 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
|
||||
{{% /codetab %}}
|
||||
|
||||
|
||||
|
||||
{{% codetab %}}
|
||||
|
||||
```javascript
|
||||
|
||||
//dependencies
|
||||
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client';
|
||||
|
||||
//code
|
||||
const daprHost = "127.0.0.1";
|
||||
|
||||
var main = function() {
|
||||
const STATE_STORE_NAME = "statestore";
|
||||
|
||||
var orderId = 100;
|
||||
//Using Dapr SDK to save and retrieve multiple states
|
||||
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
|
||||
|
@ -611,7 +617,6 @@ var main = function() {
|
|||
}
|
||||
|
||||
main();
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -662,9 +667,16 @@ Below are code examples that leverage Dapr SDKs for performing state transaction
|
|||
{{% codetab %}}
|
||||
|
||||
```csharp
|
||||
|
||||
//dependencies
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
using Dapr.Client;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Threading;
|
||||
using System.Text.Json;
|
||||
|
||||
//code
|
||||
namespace EventService
|
||||
|
@ -674,22 +686,26 @@ namespace EventService
|
|||
static async Task Main(string[] args)
|
||||
{
|
||||
string DAPR_STORE_NAME = "statestore";
|
||||
|
||||
int orderId = 100;
|
||||
//Using Dapr SDK to perform the state transactions
|
||||
using var client = new DaprClientBuilder().Build();
|
||||
var requests = new List<StateTransactionRequest>()
|
||||
{
|
||||
new StateTransactionRequest("order_3", JsonSerializer.SerializeToUtf8Bytes(orderId.ToString()), StateOperationType.Upsert),
|
||||
new StateTransactionRequest("order_2", null, StateOperationType.Delete)
|
||||
};
|
||||
CancellationTokenSource source = new CancellationTokenSource();
|
||||
CancellationToken cancellationToken = source.Token;
|
||||
await client.ExecuteStateTransactionAsync(DAPR_STORE_NAME, requests, cancellationToken: cancellationToken);
|
||||
while(true) {
|
||||
System.Threading.Thread.Sleep(5000);
|
||||
Random random = new Random();
|
||||
int orderId = random.Next(1,1000);
|
||||
using var client = new DaprClientBuilder().Build();
|
||||
var requests = new List<StateTransactionRequest>()
|
||||
{
|
||||
new StateTransactionRequest("order_3", JsonSerializer.SerializeToUtf8Bytes(orderId.ToString()), StateOperationType.Upsert),
|
||||
new StateTransactionRequest("order_2", null, StateOperationType.Delete)
|
||||
};
|
||||
CancellationTokenSource source = new CancellationTokenSource();
|
||||
CancellationToken cancellationToken = source.Token;
|
||||
//Using Dapr SDK to perform the state transactions
|
||||
await client.ExecuteStateTransactionAsync(DAPR_STORE_NAME, requests, cancellationToken: cancellationToken);
|
||||
Console.WriteLine("Order requested: " + orderId);
|
||||
Console.WriteLine("Result: " + result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -704,13 +720,19 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
{{% codetab %}}
|
||||
|
||||
```java
|
||||
|
||||
//dependencies
|
||||
import io.dapr.client.DaprClient;
|
||||
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.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
//code
|
||||
@SpringBootApplication
|
||||
|
@ -718,21 +740,26 @@ public class OrderProcessingServiceApplication {
|
|||
|
||||
private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
|
||||
|
||||
private static final String STATE_STORE_NAME = "statestore";
|
||||
|
||||
public static void main(String[] args) throws InterruptedException{
|
||||
String STATE_STORE_NAME = "statestore";
|
||||
|
||||
int orderId = 100;
|
||||
//Using Dapr SDK to perform the state transactions
|
||||
DaprClient client = new DaprClientBuilder().build();
|
||||
List<TransactionalStateOperation<?>> operationList = new ArrayList<>();
|
||||
operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.OperationType.UPSERT,
|
||||
new State<>("order_3", Integer.toString(orderId), "")));
|
||||
operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.OperationType.DELETE,
|
||||
new State<>("order_2")));
|
||||
client.executeStateTransaction(STATE_STORE_NAME, operationList).block();
|
||||
while(true) {
|
||||
TimeUnit.MILLISECONDS.sleep(5000);
|
||||
Random random = new Random();
|
||||
int orderId = random.nextInt(1000-1) + 1;
|
||||
DaprClient client = new DaprClientBuilder().build();
|
||||
List<TransactionalStateOperation<?>> operationList = new ArrayList<>();
|
||||
operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.OperationType.UPSERT,
|
||||
new State<>("order_3", Integer.toString(orderId), "")));
|
||||
operationList.add(new TransactionalStateOperation<>(TransactionalStateOperation.OperationType.DELETE,
|
||||
new State<>("order_2")));
|
||||
//Using Dapr SDK to perform the state transactions
|
||||
client.executeStateTransaction(STATE_STORE_NAME, operationList).block();
|
||||
log.info("Order requested: " + orderId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -743,37 +770,42 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
|
||||
{{% /codetab %}}
|
||||
|
||||
|
||||
{{% codetab %}}
|
||||
|
||||
```python
|
||||
|
||||
#dependencies
|
||||
import random
|
||||
from time import sleep
|
||||
import requests
|
||||
import logging
|
||||
from dapr.clients import DaprClient
|
||||
from dapr.clients.grpc._state import StateItem
|
||||
from dapr.clients.grpc._request import TransactionalStateOperation, TransactionOperationType
|
||||
|
||||
#code
|
||||
logging.basicConfig(level = logging.INFO)
|
||||
|
||||
logging.basicConfig(level = logging.INFO)
|
||||
DAPR_STORE_NAME = "statestore"
|
||||
while True:
|
||||
sleep(random.randrange(50, 5000) / 1000)
|
||||
orderId = random.randint(1, 1000)
|
||||
with DaprClient() as client:
|
||||
#Using Dapr SDK to perform the state transactions
|
||||
client.execute_state_transaction(store_name=DAPR_STORE_NAME, operations=[
|
||||
TransactionalStateOperation(
|
||||
operation_type=TransactionOperationType.upsert,
|
||||
key="order_3",
|
||||
data=str(orderId)),
|
||||
TransactionalStateOperation(key="order_3", data=str(orderId)),
|
||||
TransactionalStateOperation(
|
||||
operation_type=TransactionOperationType.delete,
|
||||
key="order_2",
|
||||
data=str(orderId)),
|
||||
TransactionalStateOperation(key="order_2", data=str(orderId))
|
||||
])
|
||||
|
||||
orderId = 100
|
||||
#Using Dapr SDK to perform the state transactions
|
||||
with DaprClient() as client:
|
||||
client.execute_state_transaction(store_name=DAPR_STORE_NAME, operations=[
|
||||
TransactionalStateOperation(
|
||||
operation_type=TransactionOperationType.upsert,
|
||||
key="order_3",
|
||||
data=str(orderId)),
|
||||
TransactionalStateOperation(key="order_3", data=str(orderId)),
|
||||
TransactionalStateOperation(
|
||||
operation_type=TransactionOperationType.delete,
|
||||
key="order_2",
|
||||
data=str(orderId)),
|
||||
TransactionalStateOperation(key="order_2", data=str(orderId))
|
||||
])
|
||||
|
||||
client.delete_state(store_name=DAPR_STORE_NAME, key="order_1")
|
||||
logging.basicConfig(level = logging.INFO)
|
||||
logging.info('Order requested: ' + str(orderId))
|
||||
logging.info('Result: ' + str(result))
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
@ -788,38 +820,48 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
|
|||
{{% codetab %}}
|
||||
|
||||
```javascript
|
||||
|
||||
//dependencies
|
||||
import { DaprClient, HttpMethod, CommunicationProtocolEnum } from 'dapr-client';
|
||||
|
||||
//code
|
||||
const daprHost = "127.0.0.1";
|
||||
|
||||
var main = function() {
|
||||
const STATE_STORE_NAME = "statestore";
|
||||
for(var i=0;i<10;i++) {
|
||||
sleep(5000);
|
||||
var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
|
||||
start(orderId).catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
var orderId = 100;
|
||||
//Using Dapr SDK to save and retrieve multiple states
|
||||
async function start(orderId) {
|
||||
const client = new DaprClient(daprHost, process.env.DAPR_HTTP_PORT, CommunicationProtocolEnum.HTTP);
|
||||
const STATE_STORE_NAME = "statestore";
|
||||
//Using Dapr SDK to save and retrieve multiple states
|
||||
await client.state.transaction(STATE_STORE_NAME, [
|
||||
{
|
||||
operation: "upsert",
|
||||
request: {
|
||||
key: "order_3",
|
||||
value: orderId.toString()
|
||||
}
|
||||
operation: "upsert",
|
||||
request: {
|
||||
key: "order_3",
|
||||
value: orderId.toString()
|
||||
}
|
||||
},
|
||||
{
|
||||
operation: "delete",
|
||||
request: {
|
||||
key: "order_2"
|
||||
}
|
||||
operation: "delete",
|
||||
request: {
|
||||
key: "order_2"
|
||||
}
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
main();
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
Navigate to the directory containing the above code, then run the following command to launch a Dapr sidecar and run the application:
|
||||
|
|
Loading…
Reference in New Issue