Quickstart: Input & Output Bindings

Get started with Dapr’s Binding building block

Let’s take a look at Dapr’s Bindings building block. Using bindings, you can:

  • Trigger your app with events coming in from external systems.
  • Interface with external systems.

In this Quickstart, you schedule a batch script to run every 10 seconds using an input Cron binding. The script processes a JSON file and outputs data to a SQL database using the PostgreSQL Dapr binding.

Bindings - 图1

Select your preferred language-specific Dapr SDK before proceeding with the Quickstart.

Pre-requisites

For this example, you will need:

Step 1: Set up the environment

Clone the sample provided in the Quickstarts repo.

  1. git clone https://github.com/dapr/quickstarts.git

Step 2: Run PostgreSQL Docker container locally

Run the PostgreSQL instance locally in a Docker container on your machine. The Quickstart sample includes a Docker Compose file to locally customize, build, run, and initialize the postgres container with a default orders table.

In a terminal window, from the root of the Quickstarts clone directory, navigate to the bindings/db directory.

  1. cd bindings/db

Run the following command to set up the container:

  1. docker compose up

Verify that the container is running locally.

  1. docker ps

The output should include:

  1. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  2. 55305d1d378b postgres "docker-entrypoint.s…" 3 seconds ago Up 2 seconds 0.0.0.0:5432->5432/tcp sql_db

Step 3: Schedule a Cron job and write to the database

In a new terminal window, navigate to the SDK directory.

  1. cd bindings/python/sdk/batch

Install the dependencies:

  1. pip3 install -r requirements.txt

Run the batch-sdk service alongside a Dapr sidecar.

  1. dapr run --app-id batch-sdk --app-port 50051 --resources-path ../../../components -- python3 app.py

Note: Since Python3.exe is not defined in Windows, you may need to use python app.py instead of python3 app.py.

The code inside the process_batch function is executed every 10 seconds (defined in binding-cron.yaml in the components directory). The binding trigger looks for a route called via HTTP POST in your application by the Dapr sidecar.

  1. # Triggered by Dapr input binding
  2. @app.route('/' + cron_binding_name, methods=['POST'])
  3. def process_batch():

The batch-sdk service uses the PostgreSQL output binding defined in the binding-postgresql.yaml component to insert the OrderId, Customer, and Price records into the orders table.

  1. with DaprClient() as d:
  2. sqlCmd = ('insert into orders (orderid, customer, price) values ' +
  3. '(%s, \'%s\', %s)' % (order_line['orderid'],
  4. order_line['customer'],
  5. order_line['price']))
  6. payload = {'sql': sqlCmd}
  7. print(sqlCmd, flush=True)
  8. try:
  9. # Insert order using Dapr output binding via HTTP Post
  10. resp = d.invoke_binding(binding_name=sql_binding, operation='exec',
  11. binding_metadata=payload, data='')
  12. return resp
  13. except Exception as e:
  14. print(e, flush=True)
  15. raise SystemExit(e)

Step 4: View the output of the job

Notice, as specified above, the code invokes the output binding with the OrderId, Customer, and Price as a payload.

Your output binding’s print statement output:

  1. == APP == Processing batch..
  2. == APP == insert into orders (orderid, customer, price) values (1, 'John Smith', 100.32)
  3. == APP == insert into orders (orderid, customer, price) values (2, 'Jane Bond', 15.4)
  4. == APP == insert into orders (orderid, customer, price) values (3, 'Tony James', 35.56)
  5. == APP == Finished processing batch

In a new terminal, verify the same data has been inserted into the database. Navigate to the bindings/db directory.

  1. cd bindings/db

Run the following to start the interactive psql CLI:

  1. docker exec -i -t postgres psql --username postgres -p 5432 -h localhost --no-password

At the admin=# prompt, change to the orders table:

  1. \c orders;

At the orders=# prompt, select all rows:

  1. select * from orders;

The output should look like this:

  1. orderid | customer | price
  2. ---------+------------+--------
  3. 1 | John Smith | 100.32
  4. 2 | Jane Bond | 15.4
  5. 3 | Tony James | 35.56

components\binding-cron.yaml component file

When you execute the dapr run command and specify the component path, the Dapr sidecar:

The Cron binding-cron.yaml file included for this Quickstart contains the following:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: cron
  5. namespace: quickstarts
  6. spec:
  7. type: bindings.cron
  8. version: v1
  9. metadata:
  10. - name: schedule
  11. value: "@every 10s" # valid cron schedule
  12. - name: direction
  13. value: "input" # direction of the cron binding

Note: The metadata section of binding-cron.yaml contains a Cron expression that specifies how often the binding is invoked.

component\binding-postgresql.yaml component file

When you execute the dapr run command and specify the component path, the Dapr sidecar:

  • Initiates the PostgreSQL binding building block
  • Connects to PostgreSQL using the settings specified in the binding-postgresql.yaml file

With the binding-postgresql.yaml component, you can easily swap out the backend database binding without making code changes.

The PostgreSQL binding-postgresql.yaml file included for this Quickstart contains the following:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: sqldb
  5. namespace: quickstarts
  6. spec:
  7. type: bindings.postgresql
  8. version: v1
  9. metadata:
  10. - name: url # Required
  11. value: "user=postgres password=docker host=localhost port=5432 dbname=orders pool_min_conns=1 pool_max_conns=10"
  12. - name: direction
  13. value: "output" # direction of the postgresql binding

In the YAML file:

  • spec/type specifies that PostgreSQL is used for this binding.
  • spec/metadata defines the connection to the PostgreSQL instance used by the component.

Pre-requisites

For this example, you will need:

Step 1: Set up the environment

Clone the sample provided in the Quickstarts repo.

  1. git clone https://github.com/dapr/quickstarts.git

Step 2: Run PostgreSQL Docker container locally

Run the PostgreSQL instance locally in a Docker container on your machine. The Quickstart sample includes a Docker Compose file to locally customize, build, run, and initialize the postgres container with a default orders table.

In a terminal window, from the root of the Quickstarts clone directory, navigate to the bindings/db directory.

  1. cd bindings/db

Run the following command to set up the container:

  1. docker compose up

Verify that the container is running locally.

  1. docker ps

The output should include:

  1. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  2. 55305d1d378b postgres "docker-entrypoint.s…" 3 seconds ago Up 2 seconds 0.0.0.0:5432->5432/tcp sql_db

Step 3: Schedule a Cron job and write to the database

In a new terminal window, navigate to the SDK directory.

  1. cd bindings/javascript/sdk/batch

Install the dependencies:

  1. npm install

Run the batch-sdk service alongside a Dapr sidecar.

  1. dapr run --app-id batch-sdk --app-port 5002 --dapr-http-port 3500 --resources-path ../../../components -- node index.js

The code inside the process_batch function is executed every 10 seconds (defined in binding-cron.yaml in the components directory). The binding trigger looks for a route called via HTTP POST in your application by the Dapr sidecar.

  1. async function start() {
  2. await server.binding.receive(cronBindingName,processBatch);
  3. await server.start();
  4. }

The batch-sdk service uses the PostgreSQL output binding defined in the binding-postgresql.yaml component to insert the OrderId, Customer, and Price records into the orders table.

  1. async function processBatch(){
  2. const loc = '../../orders.json';
  3. fs.readFile(loc, 'utf8', (err, data) => {
  4. const orders = JSON.parse(data).orders;
  5. orders.forEach(order => {
  6. let sqlCmd = `insert into orders (orderid, customer, price) values (${order.orderid}, '${order.customer}', ${order.price});`;
  7. let payload = `{ "sql": "${sqlCmd}" } `;
  8. console.log(payload);
  9. client.binding.send(postgresBindingName, "exec", "", JSON.parse(payload));
  10. });
  11. console.log('Finished processing batch');
  12. });
  13. return 0;
  14. }

Step 4: View the output of the job

Notice, as specified above, the code invokes the output binding with the OrderId, Customer, and Price as a payload.

Your output binding’s print statement output:

  1. == APP == Processing batch..
  2. == APP == insert into orders (orderid, customer, price) values(1, 'John Smith', 100.32)
  3. == APP == insert into orders (orderid, customer, price) values(2, 'Jane Bond', 15.4)
  4. == APP == insert into orders (orderid, customer, price) values(3, 'Tony James', 35.56)

In a new terminal, verify the same data has been inserted into the database. Navigate to the bindings/db directory.

  1. cd bindings/db

Run the following to start the interactive Postgres CLI:

  1. docker exec -i -t postgres psql --username postgres -p 5432 -h localhost --no-password

At the admin=# prompt, change to the orders table:

  1. \c orders;

At the orders=# prompt, select all rows:

  1. select * from orders;

The output should look like this:

  1. orderid | customer | price
  2. ---------+------------+--------
  3. 1 | John Smith | 100.32
  4. 2 | Jane Bond | 15.4
  5. 3 | Tony James | 35.56

components\binding-cron.yaml component file

When you execute the dapr run command and specify the component path, the Dapr sidecar:

The Cron binding-cron.yaml file included for this Quickstart contains the following:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: cron
  5. namespace: quickstarts
  6. spec:
  7. type: bindings.cron
  8. version: v1
  9. metadata:
  10. - name: schedule
  11. value: "@every 10s" # valid cron schedule
  12. - name: direction
  13. value: "input" # direction of the cron binding

Note: The metadata section of binding-cron.yaml contains a Cron expression that specifies how often the binding is invoked.

component\binding-postgresql.yaml component file

When you execute the dapr run command and specify the component path, the Dapr sidecar:

  • Initiates the PostgreSQL binding building block
  • Connects to PostgreSQL using the settings specified in the binding-postgresql.yaml file

With the binding-postgresql.yaml component, you can easily swap out the backend database binding without making code changes.

The PostgreSQL binding-postgresql.yaml file included for this Quickstart contains the following:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: sqldb
  5. namespace: quickstarts
  6. spec:
  7. type: bindings.postgresql
  8. version: v1
  9. metadata:
  10. - name: url # Required
  11. value: "user=postgres password=docker host=localhost port=5432 dbname=orders pool_min_conns=1 pool_max_conns=10"
  12. - name: direction
  13. value: "output" # direction of the postgresql binding

In the YAML file:

  • spec/type specifies that PostgreSQL is used for this binding.
  • spec/metadata defines the connection to the PostgreSQL instance used by the component.

Pre-requisites

For this example, you will need:

Step 1: Set up the environment

Clone the sample provided in the Quickstarts repo.

  1. git clone https://github.com/dapr/quickstarts.git

Step 2: Run PostgreSQL Docker container locally

Run the PostgreSQL instance locally in a Docker container on your machine. The Quickstart sample includes a Docker Compose file to locally customize, build, run, and initialize the postgres container with a default orders table.

In a terminal window, from the root of the Quickstarts clone directory, navigate to the bindings/db directory.

  1. cd bindings/db

Run the following command to set up the container:

  1. docker compose up

Verify that the container is running locally.

  1. docker ps

The output should include:

  1. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  2. 55305d1d378b postgres "docker-entrypoint.s…" 3 seconds ago Up 2 seconds 0.0.0.0:5432->5432/tcp sql_db

Step 3: Schedule a Cron job and write to the database

In a new terminal window, navigate to the SDK directory.

  1. cd bindings/csharp/sdk/batch

Install the dependencies:

  1. dotnet restore
  2. dotnet build batch.csproj

Run the batch-sdk service alongside a Dapr sidecar.

  1. dapr run --app-id batch-sdk --app-port 7002 --resources-path ../../../components -- dotnet run

The code inside the process_batch function is executed every 10 seconds (defined in binding-cron.yaml in the components directory). The binding trigger looks for a route called via HTTP POST in your application by the Dapr sidecar.

  1. app.MapPost("/" + cronBindingName, async () => {
  2. // ...
  3. });

The batch-sdk service uses the PostgreSQL output binding defined in the binding-postgresql.yaml component to insert the OrderId, Customer, and Price records into the orders table.

  1. // ...
  2. string jsonFile = File.ReadAllText("../../../orders.json");
  3. var ordersArray = JsonSerializer.Deserialize<Orders>(jsonFile);
  4. using var client = new DaprClientBuilder().Build();
  5. foreach(Order ord in ordersArray?.orders ?? new Order[] {}){
  6. var sqlText = $"insert into orders (orderid, customer, price) values ({ord.OrderId}, '{ord.Customer}', {ord.Price});";
  7. var command = new Dictionary<string,string>(){
  8. {"sql",
  9. sqlText}
  10. };
  11. // ...
  12. }
  13. // Insert order using Dapr output binding via Dapr Client SDK
  14. await client.InvokeBindingAsync(bindingName: sqlBindingName, operation: "exec", data: "", metadata: command);

Step 4: View the output of the job

Notice, as specified above, the code invokes the output binding with the OrderId, Customer, and Price as a payload.

Your output binding’s print statement output:

  1. == APP == Processing batch..
  2. == APP == insert into orders (orderid, customer, price) values (1, 'John Smith', 100.32);
  3. == APP == insert into orders (orderid, customer, price) values (2, 'Jane Bond', 15.4);
  4. == APP == insert into orders (orderid, customer, price) values (3, 'Tony James', 35.56);
  5. == APP == Finished processing batch

In a new terminal, verify the same data has been inserted into the database. Navigate to the bindings/db directory.

  1. cd bindings/db

Run the following to start the interactive Postgres CLI:

  1. docker exec -i -t postgres psql --username postgres -p 5432 -h localhost --no-password

At the admin=# prompt, change to the orders table:

  1. \c orders;

At the orders=# prompt, select all rows:

  1. select * from orders;

The output should look like this:

  1. orderid | customer | price
  2. ---------+------------+--------
  3. 1 | John Smith | 100.32
  4. 2 | Jane Bond | 15.4
  5. 3 | Tony James | 35.56

components\binding-cron.yaml component file

When you execute the dapr run command and specify the component path, the Dapr sidecar:

The Cron binding-cron.yaml file included for this Quickstart contains the following:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: cron
  5. namespace: quickstarts
  6. spec:
  7. type: bindings.cron
  8. version: v1
  9. metadata:
  10. - name: schedule
  11. value: "@every 10s" # valid cron schedule
  12. - name: direction
  13. value: "input" # direction of the cron binding

Note: The metadata section of binding-cron.yaml contains a Cron expression that specifies how often the binding is invoked.

component\binding-postgresql.yaml component file

When you execute the dapr run command and specify the component path, the Dapr sidecar:

  • Initiates the PostgreSQL binding building block
  • Connects to PostgreSQL using the settings specified in the binding-postgresql.yaml file

With the binding-postgresql.yaml component, you can easily swap out the backend database binding without making code changes.

The PostgreSQL binding-postgresql.yaml file included for this Quickstart contains the following:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: sqldb
  5. namespace: quickstarts
  6. spec:
  7. type: bindings.postgresql
  8. version: v1
  9. metadata:
  10. - name: url # Required
  11. value: "user=postgres password=docker host=localhost port=5432 dbname=orders pool_min_conns=1 pool_max_conns=10"
  12. - name: direction
  13. value: "output" # direction of the postgresql binding

In the YAML file:

  • spec/type specifies that PostgreSQL is used for this binding.
  • spec/metadata defines the connection to the PostgreSQL instance used by the component.

Pre-requisites

For this example, you will need:

Step 1: Set up the environment

Clone the sample provided in the Quickstarts repo.

  1. git clone https://github.com/dapr/quickstarts.git

Step 2: Run PostgreSQL Docker container locally

Run the PostgreSQL instance locally in a Docker container on your machine. The Quickstart sample includes a Docker Compose file to locally customize, build, run, and initialize the postgres container with a default orders table.

In a terminal window, from the root of the Quickstarts clone directory, navigate to the bindings/db directory.

  1. cd bindings/db

Run the following command to set up the container:

  1. docker compose up

Verify that the container is running locally.

  1. docker ps

The output should include:

  1. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  2. 55305d1d378b postgres "docker-entrypoint.s…" 3 seconds ago Up 2 seconds 0.0.0.0:5432->5432/tcp sql_db

Step 3: Schedule a Cron job and write to the database

In a new terminal window, navigate to the SDK directory.

  1. cd bindings/java/sdk/batch

Install the dependencies:

  1. mvn clean install

Run the batch-sdk service alongside a Dapr sidecar.

  1. dapr run --app-id batch-sdk --app-port 8080 --resources-path ../../../components -- java -jar target/BatchProcessingService-0.0.1-SNAPSHOT.jar

The code inside the process_batch function is executed every 10 seconds (defined in binding-cron.yaml in the components directory). The binding trigger looks for a route called via HTTP POST in your application by the Dapr sidecar.

  1. @PostMapping(path = cronBindingPath, consumes = MediaType.ALL_VALUE)
  2. public ResponseEntity<String> processBatch() throws IOException, Exception

The batch-sdk service uses the PostgreSQL output binding defined in the binding-postgresql.yaml component to insert the OrderId, Customer, and Price records into the orders table.

  1. try (DaprClient client = new DaprClientBuilder().build()) {
  2. for (Order order : ordList.orders) {
  3. String sqlText = String.format(
  4. "insert into orders (orderid, customer, price) " +
  5. "values (%s, '%s', %s);",
  6. order.orderid, order.customer, order.price);
  7. logger.info(sqlText);
  8. Map<String, String> metadata = new HashMap<String, String>();
  9. metadata.put("sql", sqlText);
  10. // Invoke sql output binding using Dapr SDK
  11. client.invokeBinding(sqlBindingName, "exec", null, metadata).block();
  12. }
  13. logger.info("Finished processing batch");
  14. return ResponseEntity.ok("Finished processing batch");
  15. }

Step 4: View the output of the job

Notice, as specified above, the code invokes the output binding with the OrderId, Customer, and Price as a payload.

Your output binding’s print statement output:

  1. == APP == 2022-06-22 16:39:17.012 INFO 35772 --- [nio-8080-exec-4] c.s.c.BatchProcessingServiceController : Processing batch..
  2. == APP == 2022-06-22 16:39:17.268 INFO 35772 --- [nio-8080-exec-4] c.s.c.BatchProcessingServiceController : insert into orders (orderid, customer, price) values (1, 'John Smith', 100.32);
  3. == APP == 2022-06-22 16:39:17.838 INFO 35772 --- [nio-8080-exec-4] c.s.c.BatchProcessingServiceController : insert into orders (orderid, customer, price) values (2, 'Jane Bond', 15.4);
  4. == APP == 2022-06-22 16:39:17.844 INFO 35772 --- [nio-8080-exec-4] c.s.c.BatchProcessingServiceController : insert into orders (orderid, customer, price) values (3, 'Tony James', 35.56);
  5. == APP == 2022-06-22 16:39:17.848 INFO 35772 --- [nio-8080-exec-4] c.s.c.BatchProcessingServiceController : Finished processing batch

In a new terminal, verify the same data has been inserted into the database. Navigate to the bindings/db directory.

  1. cd bindings/db

Run the following to start the interactive Postgres CLI:

  1. docker exec -i -t postgres psql --username postgres -p 5432 -h localhost --no-password

At the admin=# prompt, change to the orders table:

  1. \c orders;

At the orders=# prompt, select all rows:

  1. select * from orders;

The output should look like this:

  1. orderid | customer | price
  2. ---------+------------+--------
  3. 1 | John Smith | 100.32
  4. 2 | Jane Bond | 15.4
  5. 3 | Tony James | 35.56

components\binding-cron.yaml component file

When you execute the dapr run command and specify the component path, the Dapr sidecar:

The Cron binding-cron.yaml file included for this Quickstart contains the following:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: cron
  5. namespace: quickstarts
  6. spec:
  7. type: bindings.cron
  8. version: v1
  9. metadata:
  10. - name: schedule
  11. value: "@every 10s" # valid cron schedule
  12. - name: direction
  13. value: "input" # direction of the cron binding

Note: The metadata section of binding-cron.yaml contains a Cron expression that specifies how often the binding is invoked.

component\binding-postgresql.yaml component file

When you execute the dapr run command and specify the component path, the Dapr sidecar:

  • Initiates the PostgreSQL binding building block
  • Connects to PostgreSQL using the settings specified in the binding-postgresql.yaml file

With the binding-postgresql.yaml component, you can easily swap out the backend database binding without making code changes.

The PostgreSQL binding-postgresql.yaml file included for this Quickstart contains the following:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: sqldb
  5. namespace: quickstarts
  6. spec:
  7. type: bindings.postgresql
  8. version: v1
  9. metadata:
  10. - name: url # Required
  11. value: "user=postgres password=docker host=localhost port=5432 dbname=orders pool_min_conns=1 pool_max_conns=10"
  12. - name: direction
  13. value: "output" # direction of the postgresql binding

In the YAML file:

  • spec/type specifies that PostgreSQL is used for this binding.
  • spec/metadata defines the connection to the PostgreSQL instance used by the component.

Pre-requisites

For this example, you will need:

Step 1: Set up the environment

Clone the sample provided in the Quickstarts repo.

  1. git clone https://github.com/dapr/quickstarts.git

Step 2: Run PostgreSQL Docker container locally

Run the PostgreSQL instance locally in a Docker container on your machine. The Quickstart sample includes a Docker Compose file to locally customize, build, run, and initialize the postgres container with a default orders table.

In a terminal window, from the root of the Quickstarts clone directory, navigate to the bindings/db directory.

  1. cd bindings/db

Run the following command to set up the container:

  1. docker compose up

Verify that the container is running locally.

  1. docker ps

The output should include:

  1. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  2. 55305d1d378b postgres "docker-entrypoint.s…" 3 seconds ago Up 2 seconds 0.0.0.0:5432->5432/tcp sql_db

Step 3: Schedule a Cron job and write to the database

In a new terminal window, navigate to the SDK directory.

  1. cd bindings/go/sdk/batch

Install the dependencies:

  1. go build .

Run the batch-sdk service alongside a Dapr sidecar.

  1. dapr run --app-id batch-sdk --app-port 6002 --dapr-http-port 3502 --dapr-grpc-port 60002 --resources-path ../../../components -- go run .

The code inside the process_batch function is executed every 10 seconds (defined in binding-cron.yaml in the components directory). The binding trigger looks for a route called via HTTP POST in your application by the Dapr sidecar.

  1. // Triggered by Dapr input binding
  2. r.HandleFunc("/"+cronBindingName, processBatch).Methods("POST")

The batch-sdk service uses the PostgreSQL output binding defined in the binding-postgresql.yaml component to insert the OrderId, Customer, and Price records into the orders table.

  1. func sqlOutput(order Order) (err error) {
  2. client, err := dapr.NewClient()
  3. if err != nil {
  4. return err
  5. }
  6. ctx := context.Background()
  7. sqlCmd := fmt.Sprintf("insert into orders (orderid, customer, price) values (%d, '%s', %s);", order.OrderId, order.Customer, strconv.FormatFloat(order.Price, 'f', 2, 64))
  8. fmt.Println(sqlCmd)
  9. // Insert order using Dapr output binding via Dapr SDK
  10. in := &dapr.InvokeBindingRequest{
  11. Name: sqlBindingName,
  12. Operation: "exec",
  13. Data: []byte(""),
  14. Metadata: map[string]string{"sql": sqlCmd},
  15. }
  16. err = client.InvokeOutputBinding(ctx, in)
  17. if err != nil {
  18. return err
  19. }
  20. return nil
  21. }

Step 4: View the output of the job

Notice, as specified above, the code invokes the output binding with the OrderId, Customer, and Price as a payload.

Your output binding’s print statement output:

  1. == APP == Processing batch..
  2. == APP == insert into orders (orderid, customer, price) values(1, 'John Smith', 100.32)
  3. == APP == insert into orders (orderid, customer, price) values(2, 'Jane Bond', 15.4)
  4. == APP == insert into orders (orderid, customer, price) values(3, 'Tony James', 35.56)

In a new terminal, verify the same data has been inserted into the database. Navigate to the bindings/db directory.

  1. cd bindings/db

Run the following to start the interactive Postgres CLI:

  1. docker exec -i -t postgres psql --username postgres -p 5432 -h localhost --no-password

At the admin=# prompt, change to the orders table:

  1. \c orders;

At the orders=# prompt, select all rows:

  1. select * from orders;

The output should look like this:

  1. orderid | customer | price
  2. ---------+------------+--------
  3. 1 | John Smith | 100.32
  4. 2 | Jane Bond | 15.4
  5. 3 | Tony James | 35.56

components\binding-cron.yaml component file

When you execute the dapr run command and specify the component path, the Dapr sidecar:

The Cron binding-cron.yaml file included for this Quickstart contains the following:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: cron
  5. namespace: quickstarts
  6. spec:
  7. type: bindings.cron
  8. version: v1
  9. metadata:
  10. - name: schedule
  11. value: "@every 10s" # valid cron schedule
  12. - name: direction
  13. value: "input" # direction of the cron binding

Note: The metadata section of binding-cron.yaml contains a Cron expression that specifies how often the binding is invoked.

component\binding-postgresql.yaml component file

When you execute the dapr run command and specify the component path, the Dapr sidecar:

  • Initiates the PostgreSQL binding building block
  • Connects to PostgreSQL using the settings specified in the binding-postgresql.yaml file

With the binding-postgresql.yaml component, you can easily swap out the backend database binding without making code changes.

The PostgreSQL binding-postgresql.yaml file included for this Quickstart contains the following:

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: sqldb
  5. namespace: quickstarts
  6. spec:
  7. type: bindings.postgresql
  8. version: v1
  9. metadata:
  10. - name: url # Required
  11. value: "user=postgres password=docker host=localhost port=5432 dbname=orders pool_min_conns=1 pool_max_conns=10"
  12. - name: direction
  13. value: "output" # direction of the postgresql binding

In the YAML file:

  • spec/type specifies that PostgreSQL is used for this binding.
  • spec/metadata defines the connection to the PostgreSQL instance used by the component.

Tell us what you think!

We’re continuously working to improve our Quickstart examples and value your feedback. Did you find this quickstart helpful? Do you have suggestions for improvement?

Join the discussion in our discord channel.

Next steps

Explore Dapr tutorials >>

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