Java

Pre-requisites

Importing Dapr’s Java SDK

For a Maven project, add the following to your pom.xml file:

  1. <project>
  2. ...
  3. <dependencies>
  4. ...
  5. <!-- Dapr's core SDK with all features, except Actors. -->
  6. <dependency>
  7. <groupId>io.dapr</groupId>
  8. <artifactId>dapr-sdk</artifactId>
  9. <version>1.6.0</version>
  10. </dependency>
  11. <!-- Dapr's SDK for Actors (optional). -->
  12. <dependency>
  13. <groupId>io.dapr</groupId>
  14. <artifactId>dapr-sdk-actors</artifactId>
  15. <version>1.6.0</version>
  16. </dependency>
  17. <!-- Dapr's SDK integration with SpringBoot (optional). -->
  18. <dependency>
  19. <groupId>io.dapr</groupId>
  20. <artifactId>dapr-sdk-springboot</artifactId>
  21. <version>1.6.0</version>
  22. </dependency>
  23. ...
  24. </dependencies>
  25. ...
  26. </project>

For a Gradle project, add the following to your build.gradle file:

  1. dependencies {
  2. ...
  3. // Dapr's core SDK with all features, except Actors.
  4. compile('io.dapr:dapr-sdk:1.6.0')
  5. // Dapr's SDK for Actors (optional).
  6. compile('io.dapr:dapr-sdk-actors:1.6.0')
  7. // Dapr's SDK integration with SpringBoot (optional).
  8. compile('io.dapr:dapr-sdk-springboot:1.6.0')
  9. }

If you are also using Spring Boot, you may run into a common issue where the OkHttp version that the Dapr SDK uses conflicts with the one specified in the Spring Boot Bill of Materials. You can fix this by specifying a compatible OkHttp version in your project to match the version that the Dapr SDK uses:

  1. <dependency>
  2. <groupId>com.squareup.okhttp3</groupId>
  3. <artifactId>okhttp</artifactId>
  4. <version>4.9.0</version>
  5. </dependency>

Building blocks

The Java SDK allows you to interface with all of the Dapr building blocks.

Invoke a service

  1. import io.dapr.client.DaprClient;
  2. import io.dapr.client.DaprClientBuilder;
  3. try (DaprClient client = (new DaprClientBuilder()).build()) {
  4. // invoke a 'GET' method (HTTP) skipping serialization: \say with a Mono<byte[]> return type
  5. // for gRPC set HttpExtension.NONE parameters below
  6. response = client.invokeMethod(SERVICE_TO_INVOKE, METHOD_TO_INVOKE, "{\"name\":\"World!\"}", HttpExtension.GET, byte[].class).block();
  7. // invoke a 'POST' method (HTTP) skipping serialization: to \say with a Mono<byte[]> return type
  8. response = client.invokeMethod(SERVICE_TO_INVOKE, METHOD_TO_INVOKE, "{\"id\":\"100\", \"FirstName\":\"Value\", \"LastName\":\"Value\"}", HttpExtension.POST, byte[].class).block();
  9. System.out.println(new String(response));
  10. // invoke a 'POST' method (HTTP) with serialization: \employees with a Mono<Employee> return type
  11. Employee newEmployee = new Employee("Nigel", "Guitarist");
  12. Employee employeeResponse = client.invokeMethod(SERVICE_TO_INVOKE, "employees", newEmployee, HttpExtension.POST, Employee.class).block();
  13. }

Save & get application state

  1. import io.dapr.client.DaprClient;
  2. import io.dapr.client.DaprClientBuilder;
  3. import io.dapr.client.domain.State;
  4. import reactor.core.publisher.Mono;
  5. try (DaprClient client = (new DaprClientBuilder()).build()) {
  6. // Save state
  7. client.saveState(STATE_STORE_NAME, FIRST_KEY_NAME, myClass).block();
  8. // Get state
  9. State<MyClass> retrievedMessage = client.getState(STATE_STORE_NAME, FIRST_KEY_NAME, MyClass.class).block();
  10. // Delete state
  11. client.deleteState(STATE_STORE_NAME, FIRST_KEY_NAME).block();
  12. }

Publish & subscribe to messages

Publish messages
  1. import io.dapr.client.DaprClient;
  2. import io.dapr.client.DaprClientBuilder;
  3. import io.dapr.client.domain.Metadata;
  4. import static java.util.Collections.singletonMap;
  5. try (DaprClient client = (new DaprClientBuilder()).build()) {
  6. client.publishEvent(PUBSUB_NAME, TOPIC_NAME, message, singletonMap(Metadata.TTL_IN_SECONDS, MESSAGE_TTL_IN_SECONDS)).block();
  7. }
Subscribe to messages
  1. import com.fasterxml.jackson.databind.ObjectMapper;
  2. import io.dapr.Topic;
  3. import io.dapr.client.domain.CloudEvent;
  4. import org.springframework.web.bind.annotation.PostMapping;
  5. import org.springframework.web.bind.annotation.RequestBody;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import reactor.core.publisher.Mono;
  8. @RestController
  9. public class SubscriberController {
  10. private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
  11. @Topic(name = "testingtopic", pubsubName = "${myAppProperty:messagebus}")
  12. @PostMapping(path = "/testingtopic")
  13. public Mono<Void> handleMessage(@RequestBody(required = false) CloudEvent<?> cloudEvent) {
  14. return Mono.fromRunnable(() -> {
  15. try {
  16. System.out.println("Subscriber got: " + cloudEvent.getData());
  17. System.out.println("Subscriber got: " + OBJECT_MAPPER.writeValueAsString(cloudEvent));
  18. } catch (Exception e) {
  19. throw new RuntimeException(e);
  20. }
  21. });
  22. }
  23. @Topic(name = "testingtopic", pubsubName = "${myAppProperty:messagebus}",
  24. rule = @Rule(match = "event.type == 'myevent.v2'", priority = 1))
  25. @PostMapping(path = "/testingtopicV2")
  26. public Mono<Void> handleMessageV2(@RequestBody(required = false) CloudEvent envelope) {
  27. return Mono.fromRunnable(() -> {
  28. try {
  29. System.out.println("Subscriber got: " + cloudEvent.getData());
  30. System.out.println("Subscriber got: " + OBJECT_MAPPER.writeValueAsString(cloudEvent));
  31. } catch (Exception e) {
  32. throw new RuntimeException(e);
  33. }
  34. });
  35. }
  36. }

Interact with output bindings

  1. import io.dapr.client.DaprClient;
  2. import io.dapr.client.DaprClientBuilder;
  3. try (DaprClient client = (new DaprClientBuilder()).build()) {
  4. // sending a class with message; BINDING_OPERATION="create"
  5. client.invokeBinding(BINDING_NAME, BINDING_OPERATION, myClass).block();
  6. // sending a plain string
  7. client.invokeBinding(BINDING_NAME, BINDING_OPERATION, message).block();
  8. }

Interact with input bindings

  1. import org.springframework.web.bind.annotation.*;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. @RestController
  5. @RequestMapping("/")
  6. public class myClass {
  7. private static final Logger log = LoggerFactory.getLogger(myClass);
  8. @PostMapping(path = "/checkout")
  9. public Mono<String> getCheckout(@RequestBody(required = false) byte[] body) {
  10. return Mono.fromRunnable(() ->
  11. log.info("Received Message: " + new String(body)));
  12. }
  13. }

Retrieve secrets

  1. import com.fasterxml.jackson.databind.ObjectMapper;
  2. import io.dapr.client.DaprClient;
  3. import io.dapr.client.DaprClientBuilder;
  4. import java.util.Map;
  5. try (DaprClient client = (new DaprClientBuilder()).build()) {
  6. Map<String, String> secret = client.getSecret(SECRET_STORE_NAME, secretKey).block();
  7. System.out.println(JSON_SERIALIZER.writeValueAsString(secret));
  8. }

Actors

An actor is an isolated, independent unit of compute and state with single-threaded execution. Dapr provides an actor implementation based on the Virtual Actor pattern, which provides a single-threaded programming model and where actors are garbage collected when not in use. With Dapr’s implementaiton, you write your Dapr actors according to the Actor model, and Dapr leverages the scalability and reliability that the underlying platform provides.

  1. import io.dapr.actors.ActorMethod;
  2. import io.dapr.actors.ActorType;
  3. import reactor.core.publisher.Mono;
  4. @ActorType(name = "DemoActor")
  5. public interface DemoActor {
  6. void registerReminder();
  7. @ActorMethod(name = "echo_message")
  8. String say(String something);
  9. void clock(String message);
  10. @ActorMethod(returns = Integer.class)
  11. Mono<Integer> incrementAndGet(int delta);
  12. }

Get & Subscribe to application configurations

Note this is a preview API and thus will only be accessible via the DaprPreviewClient interface and not the normal DaprClient interface

  1. import io.dapr.client.DaprClientBuilder;
  2. import io.dapr.client.DaprPreviewClient;
  3. import io.dapr.client.domain.ConfigurationItem;
  4. import io.dapr.client.domain.GetConfigurationRequest;
  5. import io.dapr.client.domain.SubscribeConfigurationRequest;
  6. import reactor.core.publisher.Flux;
  7. import reactor.core.publisher.Mono;
  8. try (DaprPreviewClient client = (new DaprClientBuilder()).buildPreviewClient()) {
  9. // Get configuration for a single key
  10. Mono<ConfigurationItem> item = client.getConfiguration(CONFIG_STORE_NAME, CONFIG_KEY).block();
  11. // Get Configurations for multiple keys
  12. Mono<List<ConfigurationItem>> items =
  13. client.getConfiguration(CONFIG_STORE_NAME, CONFIG_KEY_1, CONFIG_KEY_2);
  14. // Susbcribe to Confifuration changes
  15. Flux<List<ConfigurationItem>> outFlux = client.subscribeToConfiguration(CONFIG_STORE_NAME, CONFIG_KEY_1, CONFIG_KEY_2);
  16. outFlux.subscribe(configItems -> configItems.forEach(...));
  17. }

Query saved state

Note this is a preview API and thus will only be accessible via the DaprPreviewClient interface and not the normal DaprClient interface

  1. import io.dapr.client.DaprClient;
  2. import io.dapr.client.DaprClientBuilder;
  3. import io.dapr.client.DaprPreviewClient;
  4. import io.dapr.client.domain.QueryStateItem;
  5. import io.dapr.client.domain.QueryStateRequest;
  6. import io.dapr.client.domain.QueryStateResponse;
  7. import io.dapr.client.domain.query.Query;
  8. import io.dapr.client.domain.query.Sorting;
  9. import io.dapr.client.domain.query.filters.EqFilter;
  10. try (DaprClient client = builder.build(); DaprPreviewClient previewClient = builder.buildPreviewClient()) {
  11. String searchVal = args.length == 0 ? "searchValue" : args[0];
  12. // Create JSON data
  13. Listing first = new Listing();
  14. first.setPropertyType("apartment");
  15. first.setId("1000");
  16. ...
  17. Listing second = new Listing();
  18. second.setPropertyType("row-house");
  19. second.setId("1002");
  20. ...
  21. Listing third = new Listing();
  22. third.setPropertyType("apartment");
  23. third.setId("1003");
  24. ...
  25. Listing fourth = new Listing();
  26. fourth.setPropertyType("apartment");
  27. fourth.setId("1001");
  28. ...
  29. Map<String, String> meta = new HashMap<>();
  30. meta.put("contentType", "application/json");
  31. // Save state
  32. SaveStateRequest request = new SaveStateRequest(STATE_STORE_NAME).setStates(
  33. new State<>("1", first, null, meta, null),
  34. new State<>("2", second, null, meta, null),
  35. new State<>("3", third, null, meta, null),
  36. new State<>("4", fourth, null, meta, null)
  37. );
  38. client.saveBulkState(request).block();
  39. // Create query and query state request
  40. Query query = new Query()
  41. .setFilter(new EqFilter<>("propertyType", "apartment"))
  42. .setSort(Arrays.asList(new Sorting("id", Sorting.Order.DESC)));
  43. QueryStateRequest request = new QueryStateRequest(STATE_STORE_NAME)
  44. .setQuery(query);
  45. // Use preview client to call query state API
  46. QueryStateResponse<MyData> result = previewClient.queryState(request, MyData.class).block();
  47. // View Query state response
  48. System.out.println("Found " + result.getResults().size() + " items.");
  49. for (QueryStateItem<Listing> item : result.getResults()) {
  50. System.out.println("Key: " + item.getKey());
  51. System.out.println("Data: " + item.getValue());
  52. }
  53. }