Quarkus - Dapr

A Quarkus extension that lets you build applications on top of the Dapr distributed application runtime.

Installation

If you want to use this extension, you need to add the io.quarkiverse.dapr:quarkus-dapr extension first to your build file.

For instance, with Maven, add the following dependency to your POM file:

<dependency>
    <groupId>io.quarkiverse.dapr</groupId>
    <artifactId>quarkus-dapr</artifactId>
    <version>2.7.0</version>
</dependency>

Introduction

What is Dapr?

Dapr is a portable, event-driven runtime that makes it easy for any developer to build resilient, stateless and stateful applications that run on the cloud and edge and embraces the diversity of languages and developer frameworks.

Leveraging the benefits of a sidecar architecture, Dapr helps you tackle the challenges that come with building microservices and keeps your code platform agnostic.

For more information about Dapr, please go https://dapr.io/.

What is Quarkus-Dapr?

Quarkus Dapr is a Quarkus extension to integrate with Dapr.

Quarkus Dapr Extension enables Java developers to create ultra lightweight Java native applications for Function Computing and FaaS scenes, which is also particularly suitable for running as serverless.

With the help of Dapr, these ultra lightweight Java native applications can easily interact with external application and resources. Dapr provides many useful building blocks to build modern distributed application: service invocation, state management, input/output bindings, publish & subscribe, secret management…​…​

Because of the advantages of sidecar model, the native applications can benefit from Dapr’s distributed capabilities while remain lightweight without introducing too many dependencies. This is not only helping to keep the size of java native applications, but also making the native applications easy to build as native images.

Examples

With Quarkus Dapr Extension, it’s pretty easy for java developers.

publish & subscribe

To publish events to your message broker, just inject a dapr client to your bean and call it’s publishEvent() method:

@Inject
SyncDaprClient dapr;

dapr.publishEvent("messagebus", "topic1", "Hello from Quarkus!");

To subscribe events for your message broker, adding some annotations on your method is enough. Dapr delivers each event wrapped in a CloudEvent envelope. Declare the method parameter as io.dapr.client.domain.CloudEvent<T>, where T is the type of the event payload, to get access to the envelope:

@POST
@Path("/topic1")
@Topic(name = "topic1", pubsubName = "messagebus")
public void eventOnTopic1(CloudEvent<String> event) {
    String content = event.getData();
    // ...
}

This extension supports CloudEvent as the event type, with any payload type:

@POST
@Path("/topic2")
@Topic(name = "topic2", pubsubName = "messagebus")
public void eventOnTopic2(CloudEvent<MyData> event) {
    MyData data = event.getData();
    // ...
}

The parameter can also be a custom type, which is deserialized from the event data:

@POST
@Path("/topic3")
@Topic(name = "topic3", pubsubName = "messagebus")
public void eventOnTopic3(MyData data) {
    // ...
}

In the attributes name, pubsubName, and match of the @Topic annotation, it is possible to set a config property to be loaded at runtime.

@POST
@Path("/topic6")
@Topic(name = "${topic6}", pubsubName = "${pubsub.topic6}", rule = @Rule(match = "${match.rule6}", priority = 1))
public void eventOnTopic6(CloudEvent<String> event) {
    // ...
}

For more details and hands-on experiences, please reference to our Demo.

Connecting to the Dapr sidecar

The DaprClient, SyncDaprClient, DaprWorkflowClient, the workflow runtime and the actor runtime all connect to the Dapr sidecar using the quarkus.dapr.* runtime properties, so they can be set in application.properties, per profile, or from any other Quarkus config source:

quarkus.dapr.sidecar-ip=127.0.0.1
quarkus.dapr.http-port=3501
quarkus.dapr.grpc-port=50002
%prod.quarkus.dapr.api-token=${DAPR_TOKEN_FROM_SECRET}

Properties that are not set fall back to the Dapr SDK defaults, so the DAPR_* environment variables (e.g. DAPR_HTTP_PORT, DAPR_API_TOKEN) and dapr. system properties keep working. Note that the plain SDK names (e.g. dapr.http.port) are not read from application.properties; use the quarkus.dapr. names instead.

The configured values are also available as an io.dapr.config.Properties bean, which can be used to create additional Dapr SDK clients (e.g. new ActorClient(properties)).

Quarkus Dapr – Dev Services

The Quarkus Dapr Extension provides Dev Services to simplify local development when using Quarkus with Dapr. It automatically provisions the required infrastructure and configures the Dapr sidecar so you can focus on application development.

Setting the Dapr Image

Dev Services for Dapr uses container images that are compatible with the version defined by the dapr/java-sdk dependency.

By default, the image version is aligned with the constant declared in the dapr/java-sdk library. This guarantees runtime compatibility between the Java SDK and the Dapr sidecar.

If necessary, you can override the default image by configuring:

quarkus.dapr.devservices.image-name=your-custom-image

Dapr Dev Services – Provisioned Containers

By default, Quarkus Dapr Dev Services starts the following containers:

docker.io/library/postgres
ghcr.io/diagridio/diagrid-dashboard
docker.io/daprio/placement
docker.io/daprio/scheduler
docker.io/daprio/daprd

The first two containers (postgres and diagrid-dashboard) are required to enable Dapr Dashboard integration in the Dev UI.

In addition, Quarkus Dapr automatically provisions a State Store component named kvstore, configured to use the PostgreSQL instance.

You can disable the Dapr Dashboard with:

quarkus.dapr.devservices.dashboard.enabled=false

If the Dapr Dashboard is disabled, Quarkus Dapr automatically provisions an in-memory State Store component named kvstore instead of using PostgreSQL.

Provided Dapr Components

As described above, Quarkus Dapr automatically configures the Dapr sidecar with a State Store component.

It also registers a Pub/Sub component. When running with Dev Services, this Pub/Sub component uses an in-memory implementation suitable for development and testing.

The component name for Pub/Sub (in-memory) is pubsub.

The component name for the State Store (in-memory or PostgreSQL) is kvstore.

Using Dev Services

The following example demonstrates how to use the automatically provisioned Pub/Sub and State Store components.

DaprResource.java
package io.dapr.docs;

import io.dapr.Topic;
import io.dapr.client.domain.CloudEvent;
import io.dapr.client.domain.State;
import io.quarkiverse.dapr.core.SyncDaprClient;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
import java.util.Map;
import java.util.UUID;

@Path("/dapr")
public class DaprResource {

    @Inject
    SyncDaprClient client;

    @POST
    @Path("/state")
    public Response saveState() {
        client.saveState("kvstore", "identity", UUID.randomUUID().toString()); (1)
        return Response.ok().build();
    }

    @GET
    @Path("/state")
    public Response getState() {
        State<String> state = client.getState("kvstore", "identity", String.class);
        return Response.ok(Map.of("identity", state.getValue())).build();
    }

    @POST
    @Path("/pub")
    public void pub() {
        client.publishEvent("pubsub", "topicName", "Hello from Quarkus!"); (2)
    }

    @POST
    @Topic(name = "topicName") (3)
    @Path("/sub") (4)
    public void sub(CloudEvent<String> event) {
        System.out.println("Received event: " + event.getData());
    }
}
1 kvstore is the name of the State Store component created by Dev Services. identity is the key used to store the value.
2 pubsub is the name of the Pub/Sub component created by Dev Services. topicName is the topic used to publish the message.
3 topicName must match the topic used in publishEvent. The @io.dapr.Topic annotation maps the endpoint to the topic.
4 The value sub can be any path. It is used internally to expose the subscription endpoint.

The default value of quarkus.dapr.default-pub-sub is redis. If you want to use the in-memory Pub/Sub component provided by Dev Services, set it to:

quarkus.dapr.default-pub-sub=pubsub

Adding Custom Dapr Components

To use non in-memory Dapr components, add them to the following directory:

src/main/resources/components

Example: Pub/Sub with Redis

src/main/resources/components/redis-pubsub.yaml
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: pubsub
spec:
  type: pubsub.redis
  version: v1
  metadata:
    - name: redisHost
      value: localhost:6379
    - name: redisPassword
      value: ""

Example: State Store with Redis

src/main/resources/components/redis-statestore.yaml
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
  name: statestore
spec:
  type: state.redis
  version: v1
  metadata:
    - name: keyPrefix
      value: name
    - name: redisHost
      value: localhost:6379
    - name: redisPassword
      value: ""

Quarkus Dapr automatically detects these files and configures the Dapr sidecar with the provided components during application startup.

If you declare a state.postgresql component and the Dapr Dashboard is enabled, Dev Services will not start its own PostgreSQL container: the Dapr sidecar and the Dashboard use your component instead.

Extension Configuration Reference

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Type

Default

Whether this Dev Service should start with the application in dev mode or tests.

Dapr Dev Services are enabled by default.

Environment variable: QUARKUS_DAPR_DEVSERVICES_ENABLED

boolean

true

The Dapr container image to use.

Environment variable: QUARKUS_DAPR_DEVSERVICES_DAPRD_IMAGE

string

daprio/daprd:1.19.1

Whether this Dev Service should start the Dapr Workflow Dashboard.

Environment variable: QUARKUS_DAPR_DEVSERVICES_DASHBOARD_ENABLED

boolean

true

default pub sub config

Environment variable: QUARKUS_DAPR_DEFAULT_PUB_SUB

string

redis

Indicates whether Dapr Workflow should be enabled.

Environment variable: QUARKUS_DAPR_WORKFLOW_ENABLED

boolean

true

Dapr sidecar host. Maps to the Dapr SDK property dapr.sidecar.ip.

Environment variable: QUARKUS_DAPR_SIDECAR_IP

string

Dapr sidecar HTTP port. Maps to the Dapr SDK property dapr.http.port.

Environment variable: QUARKUS_DAPR_HTTP_PORT

int

Dapr sidecar HTTP endpoint, it takes precedence over the sidecar host and HTTP port. Maps to the Dapr SDK property dapr.http.endpoint.

Environment variable: QUARKUS_DAPR_HTTP_ENDPOINT

string

Dapr sidecar gRPC port. Maps to the Dapr SDK property dapr.grpc.port.

Environment variable: QUARKUS_DAPR_GRPC_PORT

int

Dapr sidecar gRPC endpoint, it takes precedence over the sidecar host and gRPC port. Maps to the Dapr SDK property dapr.grpc.endpoint.

Environment variable: QUARKUS_DAPR_GRPC_ENDPOINT

string

API token sent to the Dapr sidecar in the dapr-api-token header. Maps to the Dapr SDK property dapr.api.token.

Environment variable: QUARKUS_DAPR_API_TOKEN

string

pub sub type

Environment variable: QUARKUS_DAPR_PUB_SUB__PUB_SUB__TYPE

string

redis

publish pub sub default metadata

Environment variable: QUARKUS_DAPR_PUB_SUB__PUB_SUB__PUBLISH_METADATA__PUBLISH_METADATA_

Map<String,String>

consume pub sub default metadata

Environment variable: QUARKUS_DAPR_PUB_SUB__PUB_SUB__CONSUME_METADATA__CONSUME_METADATA_

Map<String,String>