Modified based on the review comments - 2

Signed-off-by: Amulya Varote <amulyavarote@MININT-8V4CL0S.redmond.corp.microsoft.com>
This commit is contained in:
Amulya Varote 2021-12-05 05:26:01 -08:00 committed by Amulya Varote
parent 928428298f
commit 7b673702be
5 changed files with 88 additions and 39 deletions

View File

@ -13,13 +13,13 @@ For a complete sample showing output bindings, visit this [link](https://github.
The below code example loosely describes an application that processes orders. In the example, there is an order processing service which has a Dapr sidecar. The order processing service uses Dapr to invoke external resources via an output binding. The below code example loosely describes an application that processes orders. In the example, there is an order processing service which has a Dapr sidecar. The order processing service uses Dapr to invoke external resources via an output binding.
<img src="/images/building-block-bindings-example.png" width=1000 alt="Diagram showing bindings of example service"> <img src="/images/building-block-output-binding-example.png" width=1000 alt="Diagram showing bindings of example service">
## 1. Create a binding ## 1. Create a binding
An output binding represents a resource that Dapr uses to invoke and send messages to. An output binding represents a resource that Dapr uses to invoke and send messages to.
For the purpose of this guide, you'll use a Kafka binding. You can find a list of the different binding specs [here]({{< ref setup-bindings >}}). For the purpose of this guide, you'll use a Kafka binding. You can find a list of all supported binding components [here]({{< ref setup-bindings >}}).
Create a new binding component with the name of `checkout`. Create a new binding component with the name of `checkout`.
@ -101,7 +101,14 @@ Below are code examples that leverage Dapr SDKs for output binding.
```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;
//code //code
namespace EventService namespace EventService
@ -110,13 +117,17 @@ namespace EventService
{ {
static async Task Main(string[] args) static async Task Main(string[] args)
{ {
string BINDING_NAME = "checkout"; string BINDING_NAME = "checkout";
string BINDING_OPERATION = "create"; string BINDING_OPERATION = "create";
int orderId = 100; while(true) {
using var client = new DaprClientBuilder().Build(); System.Threading.Thread.Sleep(5000);
//Using Dapr SDK to invoke output binding Random random = new Random();
await client.InvokeBindingAsync(BINDING_NAME, BINDING_OPERATION, orderId); int orderId = random.Next(1,1000);
Console.WriteLine("Sending message: " + orderId); using var client = new DaprClientBuilder().Build();
//Using Dapr SDK to invoke output binding
await client.InvokeBindingAsync(BINDING_NAME, BINDING_OPERATION, orderId);
Console.WriteLine("Sending message: " + orderId);
}
} }
} }
} }
@ -138,19 +149,30 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
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 @SpringBootApplication
public class OrderProcessingServiceApplication { public class OrderProcessingServiceApplication {
private static final Logger log = LoggerFactory.getLogger(OrderProcessingServiceApplication.class);
public static void main(String[] args) throws InterruptedException{ public static void main(String[] args) throws InterruptedException{
String BINDING_NAME = "checkout"; String BINDING_NAME = "checkout";
String BINDING_OPERATION = "create"; String BINDING_OPERATION = "create";
int orderId = 100; while(true) {
DaprClient client = new DaprClientBuilder().build(); TimeUnit.MILLISECONDS.sleep(5000);
//Using Dapr SDK to invoke output binding Random random = new Random();
client.invokeBinding(BINDING_NAME, BINDING_OPERATION, orderId).block(); int orderId = random.nextInt(1000-1) + 1;
log.info("Sending message: " + orderId); DaprClient client = new DaprClientBuilder().build();
//Using Dapr SDK to invoke output binding
client.invokeBinding(BINDING_NAME, BINDING_OPERATION, orderId).block();
log.info("Sending message: " + orderId);
}
} }
} }
@ -168,18 +190,25 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
```python ```python
#dependencies #dependencies
import random
from time import sleep
import requests
import logging
import json
from dapr.clients import DaprClient from dapr.clients import DaprClient
#code #code
logging.basicConfig(level = logging.INFO)
BINDING_NAME = 'checkout' BINDING_NAME = 'checkout'
BINDING_OPERATION = 'create' BINDING_OPERATION = 'create'
while True:
orderId = 100 sleep(random.randrange(50, 5000) / 1000)
with DaprClient() as client: orderId = random.randint(1, 1000)
#Using Dapr SDK to invoke output binding with DaprClient() as client:
resp = client.invoke_binding(BINDING_NAME, BINDING_OPERATION, json.dumps(orderId)) #Using Dapr SDK to invoke output binding
logging.basicConfig(level = logging.INFO) resp = client.invoke_binding(BINDING_NAME, BINDING_OPERATION, json.dumps(orderId))
logging.info('Sending message: ' + str(orderId)) logging.basicConfig(level = logging.INFO)
logging.info('Sending message: ' + str(orderId))
``` ```
@ -197,6 +226,9 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --app-pr
//dependencies //dependencies
import ( import (
"context" "context"
"log"
"math/rand"
"time"
"strconv" "strconv"
dapr "github.com/dapr/go-sdk/client" dapr "github.com/dapr/go-sdk/client"
@ -206,17 +238,20 @@ import (
func main() { func main() {
BINDING_NAME := "checkout"; BINDING_NAME := "checkout";
BINDING_OPERATION := "create"; BINDING_OPERATION := "create";
orderId := 100 for i := 0; i < 10; i++ {
client, err := dapr.NewClient() time.Sleep(5000)
if err != nil { orderId := rand.Intn(1000-1) + 1
panic(err) client, err := dapr.NewClient()
} if err != nil {
defer client.Close() panic(err)
ctx := context.Background() }
//Using Dapr SDK to invoke output binding defer client.Close()
in := &dapr.InvokeBindingRequest{ Name: BINDING_NAME, Operation: BINDING_OPERATION , Data: []byte(strconv.Itoa(orderId))} ctx := context.Background()
err = client.InvokeOutputBinding(ctx, in) //Using Dapr SDK to invoke output binding
log.Println("Sending message: " + strconv.Itoa(orderId)) in := &dapr.InvokeBindingRequest{ Name: BINDING_NAME, Operation: BINDING_OPERATION , Data: []byte(strconv.Itoa(orderId))}
err = client.InvokeOutputBinding(ctx, in)
log.Println("Sending message: " + strconv.Itoa(orderId))
}
} }
``` ```
@ -233,17 +268,21 @@ dapr run --app-id orderprocessing --app-port 6001 --dapr-http-port 3601 --dapr-g
```javascript ```javascript
//dependencies //dependencies
import { DaprServer, DaprClient, CommunicationProtocolEnum } from 'dapr-client'; import { DaprServer, DaprClient, CommunicationProtocolEnum } from 'dapr-client';
//code //code
const daprHost = "127.0.0.1"; const daprHost = "127.0.0.1";
var main = function() { var main = function() {
var orderId = 100; for(var i=0;i<10;i++) {
start(orderId).catch((e) => { sleep(5000);
console.error(e); var orderId = Math.floor(Math.random() * (1000 - 1) + 1);
process.exit(1); start(orderId).catch((e) => {
}); console.error(e);
process.exit(1);
});
}
} }
async function start(orderId) { async function start(orderId) {
@ -255,6 +294,10 @@ async function start(orderId) {
console.log("Sending message: " + orderId); console.log("Sending message: " + orderId);
} }
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
main(); main();
``` ```

View File

@ -22,7 +22,7 @@ For more info on bindings, read [this overview]({{<ref bindings-overview.md>}}).
The below code example loosely describes an application that processes orders. In the example, there is an order processing service which has a Dapr sidecar. The checkout service uses Dapr to trigger the application via an input binding. The below code example loosely describes an application that processes orders. In the example, there is an order processing service which has a Dapr sidecar. The checkout service uses Dapr to trigger the application via an input binding.
<img src="/images/building-block-bindings-example.png" width=1000 alt="Diagram showing bindings of example service"> <img src="/images/building-block-input-binding-example.png" width=1000 alt="Diagram showing bindings of example service">
## 1. Create a binding ## 1. Create a binding
@ -146,12 +146,16 @@ dapr run --app-id checkout --app-port 6002 --dapr-http-port 3602 --dapr-grpc-por
```java ```java
//dependencies //dependencies
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
//code //code
@RestController @RestController
@RequestMapping("/") @RequestMapping("/")
public class CheckoutServiceController { public class CheckoutServiceController {
private static final Logger log = LoggerFactory.getLogger(CheckoutServiceController.class);
@PostMapping(path = "/checkout") @PostMapping(path = "/checkout")
public Mono<String> getCheckout(@RequestBody(required = false) byte[] body) { public Mono<String> getCheckout(@RequestBody(required = false) byte[] body) {
return Mono.fromRunnable(() -> return Mono.fromRunnable(() ->
@ -173,6 +177,7 @@ dapr run --app-id checkout --app-port 6002 --dapr-http-port 3602 --dapr-grpc-por
```python ```python
#dependencies #dependencies
import logging
from dapr.ext.grpc import App, BindingRequest from dapr.ext.grpc import App, BindingRequest
#code #code
@ -201,6 +206,7 @@ dapr run --app-id checkout --app-port 6002 --dapr-http-port 3602 --app-protocol
//dependencies //dependencies
import ( import (
"encoding/json" "encoding/json"
"log"
"net/http" "net/http"
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
@ -237,7 +243,7 @@ dapr run --app-id checkout --app-port 6002 --dapr-http-port 3602 --dapr-grpc-por
{{% codetab %}} {{% codetab %}}
```javascript ```javascript
//dependencies //dependencies
import { DaprServer, CommunicationProtocolEnum } from 'dapr-client'; import { DaprServer, CommunicationProtocolEnum } from 'dapr-client';
//code //code

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB