Skip to content

Commit

Permalink
State Management quickstarts examples added. (#528)
Browse files Browse the repository at this point in the history
* State Management quickstarts examples modified

Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>

* Bug fixes in all readme and dotnet and go

Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>

* Modified examples based on the suggestions

Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>

* Removed communication protocol from js example

Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>

* Changes based on the review comments

Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>

* Changes to retain consistency

Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>

* Changes based on the review comments. Changed key and added components

Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>

* Changed readme for pubsub

Signed-off-by: Amulya Varote <[email protected]>
Signed-off-by: Amulya Varote <[email protected]>

* Changes based on the key review comment

Signed-off-by: Amulya Varote <[email protected]>

* Modified log messages based on the review comment

Signed-off-by: Amulya Varote <[email protected]>

* Modifications based on the review comments

Signed-off-by: Amulya Varote <[email protected]>

Co-authored-by: Amulya Varote <[email protected]>
Co-authored-by: Amulya Varote <[email protected]>
  • Loading branch information
3 people authored and artursouza committed Feb 14, 2022
1 parent 5161696 commit d799eb0
Show file tree
Hide file tree
Showing 35 changed files with 4,322 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pub_sub/python/sdk/checkout/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
logging.basicConfig(level=logging.INFO)

while True:
order = {'orderid': random.randint(1, 1000)}
order = {'orderId': random.randint(1, 1000)}

with DaprClient() as client:
# Publish an event/message using Dapr PubSub
Expand Down
2 changes: 1 addition & 1 deletion pub_sub/python/sdk/order-processor/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def subscribe():
@app.route('/orders', methods=['POST'])
def orders_subscriber():
event = from_http(request.headers, request.get_data())
print('Subscriber received : ' + event.data['orderid'], flush=True)
print('Subscriber received : ' + event.data['orderId'], flush=True)
return json.dumps({'success': True}), 200, {
'ContentType': 'application/json'}

Expand Down
14 changes: 14 additions & 0 deletions state_management/components/statestore.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: statestore
spec:
type: state.redis
version: v1
metadata:
- name: redisHost
value: localhost:6379
- name: redisPassword
value: ""
- name: actorStateStore
value: "true"
39 changes: 39 additions & 0 deletions state_management/csharp/http/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Dapr state management (HTTP Client)

In this quickstart, you'll create a microservice to demonstrate Dapr's state management API. The service generates messages to store in a state store. See [Why state management](#why-state-management) to understand when to use this API.

Visit [this](https://docs.dapr.io/developing-applications/building-blocks/state-management/) link for more information about Dapr and State Management.

> **Note:** This example leverages HTTP `requests` only. If you are looking for the example using the Dapr Client SDK (recommended) [click here](../sdk/).
This quickstart includes one service:

- Dotnet client service `order-processor`

### Run Dotnet service with Dapr

1. Open a new terminal window and navigate to `order-processor` directory:

```bash
cd order-processor
```

2. Install dependencies:

<!-- STEP
name: Install Dotnet dependencies
working_dir: ./order-processor
-->

```bash
dotnet restore
dotnet build
```

3. Run the Dotnet service app with Dapr:

```bash
dapr run --app-id order-processor --components-path ../../../components/ -- dotnet run
```

<!-- END_STEP -->
41 changes: 41 additions & 0 deletions state_management/csharp/http/order-processor/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

var baseURL = (Environment.GetEnvironmentVariable("BASE_URL") ?? "http://localhost") + ":"
+ (Environment.GetEnvironmentVariable("DAPR_HTTP_PORT") ?? "3500");
const string DAPR_STATE_STORE = "statestore";

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

while (true) {
Random random = new Random();
var orderId = random.Next(1,1000);
var order = new Order(orderId);
var orderJson = JsonSerializer.Serialize(
new[] {
new {
key = orderId.ToString(),
value = order
}
}
);
var state = new StringContent(orderJson, Encoding.UTF8, "application/json");

// Save state into a state store
await httpClient.PostAsync($"{baseURL}/v1.0/state/{DAPR_STATE_STORE}", state);
Console.WriteLine("Saving Order: " + order);

// Get state from a state store
var response = await httpClient.GetStringAsync($"{baseURL}/v1.0/state/{DAPR_STATE_STORE}/{orderId.ToString()}");
Console.WriteLine("Getting Order: " + response);

// Delete state from the state store
await httpClient.DeleteAsync($"{baseURL}/v1.0/state/{DAPR_STATE_STORE}/{orderId.ToString()}");
Console.WriteLine("Deleting Order: " + order);

await Task.Delay(TimeSpan.FromSeconds(1));
}

public record Order([property: JsonPropertyName("orderId")] int orderId);
10 changes: 10 additions & 0 deletions state_management/csharp/http/order-processor/Program.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

</Project>
39 changes: 39 additions & 0 deletions state_management/csharp/sdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Dapr state management

In this quickstart, you'll create a microservice to demonstrate Dapr's state management API. The service generates messages to store data in a state store. See [Why state management](#why-state-management) to understand when this pattern might be a good choice for your software architecture.

Visit [this](https://docs.dapr.io/developing-applications/building-blocks/state-management/) link for more information about Dapr and State Management.

> **Note:** This example leverages the Dapr client SDK. If you are looking for the example using only HTTP [click here](../http).
This quickstart includes one service:

- Dotnet client service `order-processor`

### Run Dotnet service with Dapr

1. Open a new terminal window and navigate to `order-processor` directory:

```bash
cd order-processor
```

2. Install dependencies:

<!-- STEP
name: Install Dotnet dependencies
working_dir: ./order-processor
-->

```bash
dotnet restore
dotnet build
```

3. Run the Dotnet service app with Dapr:

```bash
dapr run --app-id order-processor --components-path ../../../components/ -- dotnet run
```

<!-- END_STEP -->
35 changes: 35 additions & 0 deletions state_management/csharp/sdk/order-processor/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
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;
using System.Text;
using System.Text.Json.Serialization;

string DAPR_STORE_NAME = "statestore";
var client = new DaprClientBuilder().Build();
while(true) {
Random random = new Random();
var orderId = random.Next(1,1000);
var order = new Order(orderId);

// Save state into the state store
await client.SaveStateAsync(DAPR_STORE_NAME, orderId.ToString(), order.ToString());
Console.WriteLine("Saving Order: " + order);

// Get state from the state store
var result = await client.GetStateAsync<string>(DAPR_STORE_NAME, orderId.ToString());
Console.WriteLine("Getting Order: " + result);

// Delete state from the state store
await client.DeleteStateAsync(DAPR_STORE_NAME, orderId.ToString());
Console.WriteLine("Deleting Order: " + order);

await Task.Delay(TimeSpan.FromSeconds(5));
}

public record Order([property: JsonPropertyName("orderId")] int orderId);
12 changes: 12 additions & 0 deletions state_management/csharp/sdk/order-processor/Program.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Dapr.AspNetCore" Version="1.5.0" />
</ItemGroup>

</Project>
38 changes: 38 additions & 0 deletions state_management/go/http/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Dapr state management (HTTP Client)

In this quickstart, you'll create a microservice to demonstrate Dapr's state management API. The service generates messages to store data in a state store. See [Why state management](#why-state-management) to understand when this pattern might be a good choice for your software architecture.

Visit [this](https://docs.dapr.io/developing-applications/building-blocks/state-management/) link for more information about Dapr and State Management.

> **Note:** This example leverages HTTP `requests` only. If you are looking for the example using the Dapr Client SDK (recommended) [click here](../sdk/).
This quickstart includes one service:

- Go client service `order-processor`

### Run Go service with Dapr

1. Open a new terminal window and navigate to `order-processor` directory:

```bash
cd order-processor
```

2. Install dependencies:

<!-- STEP
name: Build Go file
working_dir: ./order-processor
-->

```bash
go build app.go
```

3. Run the Go service app with Dapr:

```bash
dapr run --app-id order-processor --components-path ../../../components/ -- go run app.go
```

<!-- END_STEP -->
Binary file added state_management/go/http/order-processor/app
Binary file not shown.
56 changes: 56 additions & 0 deletions state_management/go/http/order-processor/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package main

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"time"
)

func main() {
var DAPR_HOST, DAPR_HTTP_PORT string
var okHost, okPort bool
if DAPR_HOST, okHost = os.LookupEnv("DAPR_HOST"); !okHost {
DAPR_HOST = "http://localhost"
}
if DAPR_HTTP_PORT, okPort = os.LookupEnv("DAPR_HTTP_PORT"); !okPort {
DAPR_HTTP_PORT = "3500"
}

DAPR_STATE_STORE := "statestore"
for {
orderId := rand.Intn(1000-1) + 1
order := "{\"orderId\":" + strconv.Itoa(orderId) + "}"
state, _ := json.Marshal([]map[string]string{
{"key": strconv.Itoa(orderId), "value": order},
})
responseBody := bytes.NewBuffer(state)

// Save state into a state store
_, _ = http.Post(DAPR_HOST+":"+DAPR_HTTP_PORT+"/v1.0/state/"+DAPR_STATE_STORE, "application/json", responseBody)
log.Println("Saving Order: " + order)

// Get state from a state store
getResponse, err := http.Get(DAPR_HOST + ":" + DAPR_HTTP_PORT + "/v1.0/state/" + DAPR_STATE_STORE + "/" + strconv.Itoa(orderId))
if err != nil {
fmt.Print(err.Error())
os.Exit(1)
}
result, _ := ioutil.ReadAll(getResponse.Body)
log.Println("Getting Order: ", string(result))

// Delete state from the state store
req, _ := http.NewRequest(http.MethodDelete, DAPR_HOST+":"+DAPR_HTTP_PORT+"/v1.0/state/"+DAPR_STATE_STORE+"/"+strconv.Itoa(orderId), nil)
client := &http.Client{}
_, _ = client.Do(req)
log.Println("Deleting Order: " + order)

time.Sleep(5000)
}
}
16 changes: 16 additions & 0 deletions state_management/go/http/order-processor/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module dapr_example

go 1.17

require (
github.com/dapr/go-sdk v1.2.0 // indirect
github.com/golang/protobuf v1.4.3 // indirect
github.com/gorilla/mux v1.8.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb // indirect
golang.org/x/sys v0.0.0-20201202213521-69691e467435 // indirect
golang.org/x/text v0.3.4 // indirect
google.golang.org/genproto v0.0.0-20201204160425-06b3db808446 // indirect
google.golang.org/grpc v1.34.0 // indirect
google.golang.org/protobuf v1.25.0 // indirect
)
Loading

0 comments on commit d799eb0

Please sign in to comment.