mirror of https://github.com/dapr/java-sdk.git
Docs update examples (#908)
* fixing typos and broken links in examples Signed-off-by: Cassandra Coyle <cassie@diagrid.io> * rm dup init cmd Signed-off-by: Cassandra Coyle <cassie@diagrid.io> --------- Signed-off-by: Cassandra Coyle <cassie@diagrid.io>
This commit is contained in:
parent
4dbcbde14d
commit
64423bdac6
|
@ -1,6 +1,6 @@
|
|||
# Dapr Actors Sample
|
||||
|
||||
In this example, we'll use Dapr to test the actor pattern capabilities such as concurrency, state, life-cycle management for actor activation/deactivation and timers and reminders to wake-up actors.
|
||||
In this example, we'll use Dapr to test the actor pattern capabilities such as concurrency, state, life-cycle management for actor activation/deactivation, timers, and reminders to wake-up actors.
|
||||
|
||||
Visit [this](https://docs.dapr.io/developing-applications/building-blocks/actors/) link for more information about the Actor pattern.
|
||||
|
||||
|
@ -41,9 +41,13 @@ Get into the examples directory.
|
|||
cd examples
|
||||
```
|
||||
|
||||
### Initialize Dapr
|
||||
|
||||
Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initialized.
|
||||
|
||||
### Running the Demo actor service
|
||||
|
||||
The first Java class is `DemoActorService`. Its job is to register an implementation of `DemoActor` in the Dapr's Actor runtime. In `DemoActorService.java` file, you will find the `DemoActorService` class and the `main` method. See the code snippet below:
|
||||
The first Java class is `DemoActorService`. It's job is to register an implementation of `DemoActor` in the Dapr's Actor runtime. In the `DemoActorService.java` file, you will find the `DemoActorService` class and the `main` method. See the code snippet below:
|
||||
|
||||
```java
|
||||
public class DemoActorService {
|
||||
|
@ -62,7 +66,7 @@ public class DemoActorService {
|
|||
This application uses `ActorRuntime.getInstance().registerActor()` in order to register `DemoActorImpl` as an actor in the Dapr Actor runtime. Internally, it is using `DefaultObjectSerializer` for two properties: `objectSerializer` is for Dapr's sent and received objects, and `stateSerializer` is for objects to be persisted.
|
||||
|
||||
|
||||
`DaprApplication.start()` method will run the Spring Boot [DaprApplication](../../../springboot/DaprApplication.java), which registers the Dapr Spring Boot controller [DaprController](https://github.com/dapr/java-sdk/blob/master/sdk-springboot/src/main/java/io/dapr/springboot/DaprController.java). This controller contains all Actor methods implemented as endpoints. The Dapr's sidecar will call into the controller.
|
||||
`DaprApplication.start()` method will run the Spring Boot [DaprApplication](https://github.com/dapr/java-sdk/blob/master/sdk-tests/src/test/java/io/dapr/it/actors/services/springboot/DaprApplication.java), which registers the Dapr Spring Boot controller [DaprController](https://github.com/dapr/java-sdk/blob/master/sdk-springboot/src/main/java/io/dapr/springboot/DaprController.java). This controller contains all Actor methods implemented as endpoints. The Dapr's sidecar will call into the controller.
|
||||
|
||||
See [DemoActorImpl](DemoActorImpl.java) for details on the implementation of an actor:
|
||||
```java
|
||||
|
@ -110,7 +114,7 @@ public class DemoActorImpl extends AbstractActor implements DemoActor, Remindabl
|
|||
}
|
||||
}
|
||||
```
|
||||
An actor inherits from `AbstractActor` and implements the constructor to pass through `ActorRuntimeContext` and `ActorId`. By default, the actor's name will be the same as the class' name. Optionally, it can be annotated with `ActorType` and override the actor's name. The actor's methods can be synchronously or use [Project Reactor's Mono](https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html) return type. Finally, state management is done via methods in `super.getActorStateManager()`. The `DemoActor` interface is used by the Actor runtime and also client. See how `DemoActor` interface can be annotated as Dapr Actor.
|
||||
An actor inherits from `AbstractActor` and implements the constructor to pass through `ActorRuntimeContext` and `ActorId`. By default, the actor's name will be the same as the class' name. Optionally, it can be annotated with `ActorType` and override the actor's name. The actor's methods can be synchronously or use [Project Reactor's Mono](https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html) return type. Finally, state management is done via methods in `super.getActorStateManager()`. The `DemoActor` interface is used by the Actor runtime and also client. See how the `DemoActor` interface can be annotated as a Dapr Actor.
|
||||
|
||||
```java
|
||||
import io.dapr.actors.ActorMethod;
|
||||
|
@ -229,9 +233,9 @@ public class DemoActorClient {
|
|||
|
||||
First, the client defines how many actors it is going to create. The main method declares a `ActorClient` and `ActorProxyBuilder` to create instances of the `DemoActor` interface, which are implemented automatically by the SDK and make remote calls to the equivalent methods in Actor runtime. `ActorClient` is reusable for different actor types and should be instantiated only once in your code. `ActorClient` also implements `AutoCloseable`, which means it holds resources that need to be closed. In this example, we use the "try-resource" feature in Java.
|
||||
|
||||
Then, the code executes the `callActorForever` private method once per actor. Initially, it will invoke `registerReminder()`, which sets the due time and period for the reminder. Then, `incrementAndGet()` increments a counter, persists it and sends it back as response. Finally `say` method which will print a message containing the received string along with the formatted server time.
|
||||
Then, the code executes the `callActorForever` private method once per actor. Initially, it will invoke `registerReminder()`, which sets the due time and period for the reminder. Then, `incrementAndGet()` increments a counter, persists it and sends it back as response. Finally, `say` method will print a message containing the received string along with the formatted server time.
|
||||
|
||||
Use the follow command to execute the DemoActorClient:
|
||||
Use the following command to execute the DemoActorClient:
|
||||
|
||||
<!-- STEP
|
||||
name: Run Demo Actor Client
|
||||
|
@ -301,10 +305,10 @@ Finally, the console for `demoactorclient` got the service responses:
|
|||
== APP == Reply 2023-05-23 11:04:49.863 received from actor at index 2 with ID 4720f646-baaa-4fae-86dd-aec2fc2ead6e
|
||||
```
|
||||
|
||||
For more details on Dapr SpringBoot integration, please refer to [Dapr Spring Boot](../../../springboot/DaprApplication.java) Application implementation.
|
||||
For more details on Dapr SpringBoot integration, please refer to [Dapr Spring Boot](https://github.com/dapr/java-sdk/blob/master/sdk-tests/src/test/java/io/dapr/it/actors/services/springboot/DaprApplication.java) Application implementation.
|
||||
|
||||
### Limitations
|
||||
|
||||
Currently, these are the limitations in the Java SDK for Dapr:
|
||||
* Actor interface cannot have overloaded methods (methods with same name but different signature).
|
||||
* Actor interface cannot have overloaded methods (methods with same name, but different signature).
|
||||
* Actor methods can only have zero or one parameter.
|
||||
|
|
|
@ -10,7 +10,7 @@ Visit [this](https://docs.dapr.io/developing-applications/building-blocks/bindin
|
|||
|
||||
## Binding sample using the Java-SDK
|
||||
|
||||
In this example, the component used is Kafka but others are also available.
|
||||
In this example, the component used is Kafka, but others are also available.
|
||||
|
||||
Visit [this](https://github.com/dapr/components-contrib/tree/master/bindings) link for more information about binding implementations.
|
||||
|
||||
|
@ -46,11 +46,15 @@ Then, go into the examples directory:
|
|||
cd examples
|
||||
```
|
||||
|
||||
### Initialize Dapr
|
||||
|
||||
Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initialized.
|
||||
|
||||
### Setting Kafka locally
|
||||
|
||||
Before getting into the application code, follow these steps in order to set up a local instance of Kafka. This is needed for the local instances. Steps are:
|
||||
Before getting into the application code, follow these steps in order to set up a local instance of Kafka. This is needed for the local instances.
|
||||
|
||||
1. To run container locally run:
|
||||
1. Run the container locally:
|
||||
|
||||
<!-- STEP
|
||||
name: Setup kafka container
|
||||
|
@ -109,7 +113,7 @@ public class InputBindingController {
|
|||
}
|
||||
```
|
||||
|
||||
Execute the follow script in order to run the Input Binding example:
|
||||
Execute the following command to run the Input Binding example:
|
||||
|
||||
<!-- STEP
|
||||
name: Run input binding
|
||||
|
@ -130,9 +134,9 @@ dapr run --components-path ./components/bindings --app-id inputbinding --app-por
|
|||
|
||||
### Running the Output binding sample
|
||||
|
||||
The output binding application is a simple java class with a main method that uses the Dapr Client to invoke binding.
|
||||
The output binding application is a simple Java class with a main method that uses the Dapr Client to invoke binding.
|
||||
|
||||
In the `OutputBindingExample.java` file, you will find the `OutputBindingExample` class, containing the main method. The main method declares a Dapr Client using the `DaprClientBuilder` class. Notice that this builder gets two serializer implementations in the constructor: One is for Dapr's sent and recieved objects, and second is for objects to be persisted. The client publishes events using `invokeBinding` method. The Dapr client is also within a try-with-resource block to properly close the client at the end. See the code snippet below:
|
||||
In the `OutputBindingExample.java` file, you will find the `OutputBindingExample` class, containing the main method. The main method declares a Dapr Client using the `DaprClientBuilder` class. Notice that this builder gets two serializer implementations in the constructor: one is for Dapr's sent and recieved objects, and the second is for objects to be persisted. The client publishes events using the `invokeBinding` method. The Dapr client is also within a try-with-resource block to properly close the client at the end. See the code snippet below:
|
||||
```java
|
||||
public class OutputBindingExample{
|
||||
///...
|
||||
|
@ -179,7 +183,7 @@ public class OutputBindingExample{
|
|||
|
||||
This example binds two events: A user-defined data object (using the `myClass` object as parameter) and a simple string using the same `invokeBinding` method.
|
||||
|
||||
Use the follow command to execute the Output Binding example:
|
||||
Execute the following command to run the Output Binding example:
|
||||
|
||||
<!-- STEP
|
||||
name: Run output binding
|
||||
|
@ -251,4 +255,4 @@ docker-compose -f ./src/main/java/io/dapr/examples/bindings/http/docker-compose-
|
|||
|
||||
<!-- END_STEP -->
|
||||
|
||||
For more details on Dapr Spring Boot integration, please refer to [Dapr Spring Boot](../../DaprApplication.java) Application implementation.
|
||||
For more details on the Dapr Spring Boot integration, please refer to the [Dapr Spring Boot](../../DaprApplication.java) Application implementation.
|
||||
|
|
|
@ -4,8 +4,8 @@ This example provides the different capabilities provided by Dapr Java SDK for C
|
|||
|
||||
### Using the ConfigurationAPI
|
||||
|
||||
The java SDK exposes several methods for this -
|
||||
* `client.getConfiguration(...)` for getting a configuration for a single/multiple keys.
|
||||
The Java SDK exposes several methods for this -
|
||||
* `client.getConfiguration(...)` for getting configuration for a single/multiple key(s).
|
||||
* `client.subscribeConfiguration(...)` for subscribing to a list of keys for any change.
|
||||
* `client.unsubscribeConfiguration(...)` for unsubscribing to changes from subscribed items.
|
||||
|
||||
|
@ -33,7 +33,18 @@ Then build the Maven project:
|
|||
# make sure you are in the `java-sdk` directory.
|
||||
mvn install
|
||||
```
|
||||
## Store few dummy configurations in configurationstore
|
||||
|
||||
Then get into the examples directory:
|
||||
|
||||
```sh
|
||||
cd examples
|
||||
```
|
||||
|
||||
### Initialize Dapr
|
||||
|
||||
Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initialized.
|
||||
|
||||
## Store dummy configurations in configuration store
|
||||
<!-- STEP
|
||||
name: Set configuration value
|
||||
expected_stdout_lines:
|
||||
|
@ -48,9 +59,9 @@ docker exec dapr_redis redis-cli MSET myconfig1 "val1||1" myconfig2 "val2||1" my
|
|||
|
||||
### Running the example
|
||||
|
||||
This example uses the Java SDK Dapr client in order to **Get, Subscribe and Unsubscribe** from configuration items and utilizes `Redis` as configuration store.
|
||||
This example uses the Java SDK Dapr client in order to **Get, Subscribe and Unsubscribe** from configuration items, and utilizes `Redis` as configuration store.
|
||||
`ConfigurationClient.java` is the example class demonstrating all 3 features.
|
||||
Kindly check [DaprPreviewClient.java](https://github.com/dapr/java-sdk/blob/master/sdk/src/main/java/io/dapr/client/DaprPreviewClient.java) for detailed description of the supported APIs.
|
||||
Kindly check [DaprPreviewClient.java](https://github.com/dapr/java-sdk/blob/master/sdk/src/main/java/io/dapr/client/DaprPreviewClient.java) for a detailed description of the supported APIs.
|
||||
|
||||
```java
|
||||
public class ConfigurationClient {
|
||||
|
|
|
@ -34,6 +34,17 @@ Then build the Maven project:
|
|||
# make sure you are in the `java-sdk` directory.
|
||||
mvn install
|
||||
```
|
||||
|
||||
Then get into the examples directory:
|
||||
|
||||
```sh
|
||||
cd examples
|
||||
```
|
||||
|
||||
### Initialize Dapr
|
||||
|
||||
Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initialized.
|
||||
|
||||
## Store few dummy configurations in configurationstore
|
||||
<!-- STEP
|
||||
name: Set configuration value
|
||||
|
|
|
@ -33,7 +33,7 @@ cd examples
|
|||
```
|
||||
|
||||
### Running the StateClient
|
||||
This example uses the Java SDK Dapr client in order perform an invalid operartion, causing Dapr runtime to return an error. See the code snippet bellow:
|
||||
This example uses the Java SDK Dapr client in order to perform an invalid operation, causing Dapr runtime to return an error. See the code snippet below:
|
||||
|
||||
```java
|
||||
public class Client {
|
||||
|
@ -56,7 +56,7 @@ public class Client {
|
|||
|
||||
}
|
||||
```
|
||||
The code uses the `DaprClient` created by the `DaprClientBuilder`. It tries to get a state from state store but provides an unknown state store. It causes Dapr sidecar to return error, which is converted to a `DaprException` to the application. To be compatible with Project Reactor, `DaprException` extends from `RuntimeException` - making it an unchecked exception. Applications might also get `IllegalArgumentException` when invoking methods with invalid input parameters that are validated at the client side.
|
||||
The code uses the `DaprClient` created by the `DaprClientBuilder`. It tries to get a state from state store, but provides an unknown state store. It causes the Dapr sidecar to return an error, which is converted to a `DaprException` to the application. To be compatible with Project Reactor, `DaprException` extends from `RuntimeException` - making it an unchecked exception. Applications might also get an `IllegalArgumentException` when invoking methods with invalid input parameters that are validated at the client side.
|
||||
|
||||
The Dapr client is also within a try-with-resource block to properly close the client at the end.
|
||||
|
||||
|
|
|
@ -50,7 +50,7 @@ The first component is the service. It has a simple API with the `Say` method. T
|
|||
}
|
||||
```
|
||||
|
||||
In the `HelloWorldService.java` file, you will find the `HelloWorldService` class, containing the main method. The service implementation happens in the `GrpcHelloWorldDaprService` class. You can see that it extends `DaprClientImplBase` instead of `HelloWorldImplBase`. This is because this service will be called by Dapr, so it implements the service API expected by Dapr. The `DaprClientImplBase` class is part of this SDK. In a real-world application, the service would still implement its main API as well. The Dapr's API would be exposed as an additional service. In this example, we are implementing Dapr's API only. Modifying this example to expose `HelloWorldService` is offered as an exercise to the reader.
|
||||
In the `HelloWorldService.java` file, you will find the `HelloWorldService` class, containing the main method. The service implementation happens in the `GrpcHelloWorldDaprService` class. You can see that it extends `DaprClientImplBase` instead of `HelloWorldImplBase`. This is because this service will be called by Dapr, so it implements the service API expected by Dapr. The `DaprClientImplBase` class is part of this SDK. In a real-world application, the service would still implement it's main API as well. The Dapr's API would be exposed as an additional service. In this example, we are implementing Dapr's API only. Modifying this example to expose `HelloWorldService` is offered as an exercise to the reader.
|
||||
```java
|
||||
private static class GrpcHelloWorldDaprService extends DaprClientGrpc.DaprClientImplBase {
|
||||
///...
|
||||
|
|
|
@ -43,6 +43,10 @@ Then get into the examples directory:
|
|||
cd examples
|
||||
```
|
||||
|
||||
### Initialize Dapr
|
||||
|
||||
Initialize Dapr in Self-Hosted Mode by running: `dapr init`
|
||||
|
||||
### Running the Demo service sample
|
||||
|
||||
The Demo service application is meant to expose a method that can be remotely invoked. In this example, the service code has two parts:
|
||||
|
@ -95,7 +99,7 @@ public class DemoServiceController {
|
|||
}
|
||||
```
|
||||
|
||||
Use the follow command to execute the demo service example:
|
||||
Use the following command to execute the demo service example:
|
||||
|
||||
<!-- STEP
|
||||
name: Run demo service
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
# Dapr Pub-Sub Sample
|
||||
|
||||
In this sample, we'll create a publisher and a subscriber java applications using Dapr, based on the publish-subscribe pattern. The publisher will generate messages of a specific topic, while subscriber will listen for messages of specific topic. See [Why Pub-Sub](#why-pub-sub) to understand when this pattern might be a good choice for your software architecture.
|
||||
In this sample, we'll create a publisher and a subscriber java applications using Dapr, based on the publish-subscribe pattern. The publisher will generate messages of a specific topic, while a subscriber will listen for messages of specific topic. See the [Dapr Pub-Sub docs](https://docs.dapr.io/developing-applications/building-blocks/pubsub/) to understand when this pattern might be a good choice for your software architecture.
|
||||
|
||||
Visit [this](https://docs.dapr.io/developing-applications/building-blocks/pubsub/pubsub-overview/) link for more information about Dapr and Pub-Sub.
|
||||
|
||||
|
@ -38,9 +38,13 @@ Then get into the examples directory:
|
|||
cd examples
|
||||
```
|
||||
|
||||
### Initialize Dapr
|
||||
|
||||
Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initialized.
|
||||
|
||||
### Running the subscriber
|
||||
|
||||
The first is the subscriber. It will subscribe to the topic to be used by the publisher and read the messages published. The Subscriber uses the Spring Boot´s DaprApplication class for initializing the `SubscriberController`. There are gRPC version and HTTP version of subscriber in grpc and http folders. In `Subscriber.java` file, you will find the `Subscriber` class and the `main` method. See the code snippet below:
|
||||
The subscriber will subscribe to the topic to be used by the publisher and read the messages published. The subscriber uses the Spring Boot´s DaprApplication class for initializing the `SubscriberController`. There is a gRPC version and HTTP version of the subscriber in the grpc and http folders. In `Subscriber.java` file, you will find the `Subscriber` class and the `main` method. See the code snippet below:
|
||||
|
||||
```java
|
||||
public class Subscriber {
|
||||
|
@ -52,11 +56,11 @@ public class Subscriber {
|
|||
}
|
||||
}
|
||||
```
|
||||
`DaprApplication.start()` Method will run an Spring Boot application that registers the `SubscriberController`, which exposes the message retrieval as a POST request, or the `SubscriberGrpcService`, which implemente the grpc methods that sidecar will call.
|
||||
`DaprApplication.start()` Method will run a Spring Boot application that registers the `SubscriberController`, which exposes the message retrieval as a POST request, or the `SubscriberGrpcService`, which implement the grpc methods that the sidecar will call.
|
||||
|
||||
**HTTP Version**
|
||||
|
||||
The Dapr's sidecar is the one that performs the actual call to the controller, based on the pubsub features. This Spring Controller handles the message endpoint, printing the message which is received as the POST body.
|
||||
The Dapr sidecar is the one that performs the actual call to the controller, based on the pubsub features. This Spring Controller handles the message endpoint, printing the message which is received as the POST body.
|
||||
|
||||
The subscription's topic in Dapr is handled automatically via the `@Topic` annotation - which also supports the same expressions in
|
||||
[Spring's @Value annotations](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-value-annotations).
|
||||
|
@ -86,7 +90,7 @@ public class SubscriberController {
|
|||
}
|
||||
```
|
||||
|
||||
The `@BulkSubscribe` annotation can be used with `@Topic` to receive multiple messages at once. See the example on how to handle the bulk messages and respond correctly.
|
||||
The `@BulkSubscribe` annotation can be used with `@Topic` to receive multiple messages at once. See the example below on how to handle the bulk messages and respond correctly.
|
||||
|
||||
```java
|
||||
@RestController
|
||||
|
@ -119,8 +123,7 @@ public class SubscriberController {
|
|||
```
|
||||
|
||||
|
||||
|
||||
Execute the follow script in order to run the HTTP Subscriber example:
|
||||
Execute the following command to run the HTTP Subscriber example:
|
||||
|
||||
<!-- STEP
|
||||
name: Run Subscriber
|
||||
|
@ -146,7 +149,7 @@ dapr run --components-path ./components/pubsub --app-id subscriber --app-port 30
|
|||
|
||||
The Spring GrpcService implements the methods required for gRPC communication with Dapr\`s sidecar.
|
||||
|
||||
The `SubscriberGrpcService.java` snippet below shows the details. Dapr\`s sidecar will call `listTopicSubscriptions` to get topic and pubsubname that are contained in response before subscription starts. After the pubsub component in sidecar subscribes successfully from the specified topic, message will be sent to the method `onTopicEvent` in request parameter.
|
||||
The `SubscriberGrpcService.java` snippet below shows the details. Dapr\`s sidecar will call `listTopicSubscriptions` to get the topic and pubsub name that are contained in the response before the subscription starts. After the pubsub component in the sidecar subscribes successfully to the specified topic, a message will be sent to the method `onTopicEvent` in the request parameter.
|
||||
|
||||
```java
|
||||
@GrpcService
|
||||
|
@ -189,8 +192,7 @@ public class SubscriberGrpcService extends AppCallbackGrpc.AppCallbackImplBase {
|
|||
}
|
||||
```
|
||||
|
||||
|
||||
Execute the follow script in order to run the gRPC Subscriber example:
|
||||
Execute the following command to run the gRPC Subscriber example:
|
||||
|
||||
```bash
|
||||
dapr run --components-path ./components/pubsub --app-id subscriber --app-port 3000 --app-protocol grpc -- java -jar target/dapr-java-sdk-examples-exec.jar io.dapr.examples.pubsub.grpc.Subscriber -p 3000
|
||||
|
@ -199,10 +201,10 @@ dapr run --components-path ./components/pubsub --app-id subscriber --app-port 30
|
|||
|
||||
### Running the publisher
|
||||
|
||||
Another component is the publisher. It is a simple java application with a main method that uses the Dapr gRPC Client to publish 10 messages to a specific topic.
|
||||
The publisher is a simple Java application with a main method that uses the Dapr gRPC Client to publish 10 messages to a specific topic.
|
||||
|
||||
In the `Publisher.java` file, you will find the `Publisher` class, containing the main method. The main method declares a Dapr Client using the `DaprClientBuilder` class. Notice that this builder gets two serializer implementations in the constructor: One is for Dapr's sent and received objects, and second is for objects to be persisted. The client publishes messages using `publishEvent` method. The Dapr client is also within a try-with-resource block to properly close the client at the end. See the code snippet below:
|
||||
Dapr sidecar will automatically wrap the payload received into a CloudEvent object, which will later on parsed by the subscriber.
|
||||
In the `Publisher.java` file, you will find the `Publisher` class, containing the main method. The main method declares a Dapr Client using the `DaprClientBuilder` class. Notice that this builder gets two serializer implementations in the constructor: one is for Dapr's sent and received objects, and the second is for objects to be persisted. The client publishes messages using the `publishEvent` method. The Dapr client is also within a try-with-resource block to properly close the client at the end. See the code snippet below:
|
||||
Dapr's sidecar will automatically wrap the payload received into a CloudEvent object, which will later on be parsed by the subscriber.
|
||||
```java
|
||||
public class Publisher {
|
||||
private static final int NUM_MESSAGES = 10;
|
||||
|
@ -233,7 +235,7 @@ public class Publisher {
|
|||
```
|
||||
|
||||
The `CloudEventPublisher.java` file shows how the same can be accomplished if the application must send a CloudEvent object instead of relying on Dapr's automatic CloudEvent "wrapping".
|
||||
In this case, the app MUST override the content-type parameter via `withContentType()`, so Dapr sidecar knows that the payload is already a CloudEvent object.
|
||||
In this case, the app MUST override the content-type parameter via `withContentType()`, so that Dapr's sidecar knows that the payload is already a CloudEvent object.
|
||||
|
||||
```java
|
||||
public class CloudEventPublisher {
|
||||
|
@ -264,7 +266,7 @@ public class CloudEventPublisher {
|
|||
}
|
||||
```
|
||||
|
||||
Use the follow command to execute the Publisher example:
|
||||
Execute the following command to run the Publisher example:
|
||||
|
||||
<!-- STEP
|
||||
name: Run Publisher
|
||||
|
@ -353,11 +355,11 @@ Messages have been retrieved from the topic.
|
|||
> Note : This API is currently in Alpha stage in Dapr runtime, hence the API methods in SDK are part of the DaprPreviewClient class.
|
||||
|
||||
Another feature provided by the SDK is to allow users to publish multiple messages in a single call to the Dapr sidecar.
|
||||
For this example, we have a simple java application with a main method that uses the Dapr gPRC Preview Client to publish 10 messages to a specific topic in a single call.
|
||||
For this example, we have a simple Java application with a main method that uses the Dapr gPRC Preview Client to publish 10 messages to a specific topic in a single call.
|
||||
|
||||
In the `BulkPublisher.java` file, you will find the `BulkPublisher` class, containing the main method. The main method declares a Dapr Preview Client using the `DaprClientBuilder` class. Notice that this builder gets two serializer implementations in the constructor: One is for Dapr's sent and recieved objects, and second is for objects to be persisted.
|
||||
In the `BulkPublisher.java` file, you will find the `BulkPublisher` class, containing the main method. The main method declares a Dapr Preview Client using the `DaprClientBuilder` class. Notice that this builder gets two serializer implementations in the constructor: one is for Dapr's sent and recieved objects, and the second is for objects to be persisted.
|
||||
The client publishes messages using `publishEvents` method. The Dapr client is also within a try-with-resource block to properly close the client at the end. See the code snippet below:
|
||||
Dapr sidecar will automatically wrap the payload received into a CloudEvent object, which will later on be parsed by the subscriber.
|
||||
Dapr's sidecar will automatically wrap the payload received into a CloudEvent object, which will later on be parsed by the subscriber.
|
||||
|
||||
```java
|
||||
public class BulkPublisher {
|
||||
|
@ -409,7 +411,7 @@ public class BulkPublisher {
|
|||
```
|
||||
The code uses the `DaprPreviewClient` created by the `DaprClientBuilder` is used for the `publishEvents` (BulkPublish) preview API.
|
||||
|
||||
In this case, when `publishEvents` call is made, one of the argument to the method is the content type of data, this being `text/plain` in the example.
|
||||
In this case, when the `publishEvents` call is made, one of the arguments to the method is the content type of data, this being `text/plain` in the example.
|
||||
In this case, when parsing and printing the response, there is a concept of EntryID, which is automatically generated or can be set manually when using the `BulkPublishRequest` object.
|
||||
The EntryID is a request scoped ID, in this case automatically generated as the index of the message in the list of messages in the `publishEvents` call.
|
||||
|
||||
|
@ -418,7 +420,7 @@ The response, will be empty if all events are published successfully or it will
|
|||
The code also shows the scenario where it is possible to start tracing in code and pass on that tracing context to Dapr.
|
||||
|
||||
The `CloudEventBulkPublisher.java` file shows how the same can be accomplished if the application must send a CloudEvent object instead of relying on Dapr's automatic CloudEvent "wrapping".
|
||||
In this case, the application **MUST** override the content-type parameter via `withContentType()`, so Dapr sidecar knows that the payload is already a CloudEvent object.
|
||||
In this case, the application **MUST** override the content-type parameter via `withContentType()`, so Dapr's sidecar knows that the payload is already a CloudEvent object.
|
||||
|
||||
```java
|
||||
public class CloudEventBulkPublisher {
|
||||
|
@ -467,7 +469,7 @@ public class CloudEventBulkPublisher {
|
|||
}
|
||||
```
|
||||
|
||||
Use the follow command to execute the BulkPublisher example:
|
||||
Execute the following command to run the BulkPublisher example:
|
||||
|
||||
<!-- STEP
|
||||
name: Run Bulk Publisher
|
||||
|
@ -533,7 +535,7 @@ The Subscriber started previously [here](#running-the-subscriber) should print t
|
|||
== APP == Subscriber got: {"id":"df20d841-296e-4c6b-9dcb-dd17920538e7","source":"bulk-publisher","type":"com.dapr.event.sent","specversion":"1.0","datacontenttype":"text/plain","data":"This is message #8","data_base64":null}
|
||||
```
|
||||
|
||||
> Note: Redis pubsub component does not have a native and uses Dapr runtime's default bulk publish implementation which is concurrent, thus the order of the events that are published are not guaranteed.
|
||||
> Note: the Redis pubsub component does not have a native bulk publish implementation, and uses Dapr runtime's default bulk publish implementation which is concurrent. Therefore, the order of the events that are published are not guaranteed.
|
||||
|
||||
Messages have been retrieved from the topic.
|
||||
|
||||
|
|
|
@ -43,7 +43,7 @@ public class QuerySavedState {
|
|||
private static final String STATE_STORE_NAME = "mongo-statestore";
|
||||
|
||||
/**
|
||||
* Executes the sate actions.
|
||||
* Executes the state actions.
|
||||
* @param args messages to be sent as state value.
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
|
|
@ -29,7 +29,11 @@ Then change into the `examples` directory:
|
|||
cd examples
|
||||
```
|
||||
|
||||
### Running the StateClient
|
||||
### Initialize Dapr
|
||||
|
||||
Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initialized.
|
||||
|
||||
### Running the State Client
|
||||
This example uses the Java SDK Dapr client in order to save bulk state and query state, in this case, an instance of a class. See the code snippets below:
|
||||
|
||||
The class saved and queried for is as below:
|
||||
|
@ -134,7 +138,7 @@ public class QuerySavedState {
|
|||
private static final String THIRD_KEY_NAME = "key3";
|
||||
|
||||
/**
|
||||
* Executes the sate actions.
|
||||
* Executes the state actions.
|
||||
* @param args messages to be sent as state value.
|
||||
*/
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
@ -204,12 +208,12 @@ public class QuerySavedState {
|
|||
}
|
||||
}
|
||||
```
|
||||
The code uses the `DaprClient` created by the `DaprClientBuilder` for waiting for sidecar to start as well as to save state. Notice that this builder uses default settings. Internally, it is using `DefaultObjectSerializer` for two properties: `objectSerializer` is for Dapr's sent and received objects, and `stateSerializer` is for objects to be persisted.
|
||||
The code uses the `DaprClient` created by the `DaprClientBuilder` for waiting for the sidecar to start as well as to save state. Notice that this builder uses default settings. Internally, it is using `DefaultObjectSerializer` for two properties: `objectSerializer` is for Dapr's sent and received objects, and `stateSerializer` is for objects to be persisted.
|
||||
|
||||
The code uses the `DaprPreviewClient` created by the `DaprClientBuilder` is used for the `queryState` preview API.
|
||||
The code uses the `DaprPreviewClient` created by the `DaprClientBuilder` which is used for the `queryState` preview API.
|
||||
|
||||
This example performs multiple operations:
|
||||
* `client.waitForSidecar(...)` for waiting until Dapr sidecar is ready.
|
||||
* `client.waitForSidecar(...)` for waiting until Dapr's sidecar is ready.
|
||||
* `client.saveBulkState(...)` for persisting an instance of `Listing`.
|
||||
* `client.query(...)` operation in order to query for persisted state.
|
||||
|
||||
|
@ -262,7 +266,7 @@ Once running, the QuerySaveState example should print the output as follows:
|
|||
== APP == Data: Listing{propertyType='apartment', id=1000, city='Seattle', state='WA'}
|
||||
== APP == Done
|
||||
```
|
||||
Note that the output is got in the descending order of the field `id` and all the `propertyType` field values are the same `apartment`.
|
||||
Note that the output is in descending order of the field `id`, and all the `propertyType` field values are the same `apartment`.
|
||||
|
||||
### Cleanup
|
||||
|
||||
|
|
|
@ -10,7 +10,7 @@ Visit [this](https://docs.dapr.io/developing-applications/building-blocks/secret
|
|||
|
||||
## Secret store sample using the Java-SDK
|
||||
|
||||
In this example, the component used is local file(not recommended for production use), but others are also available.
|
||||
In this example, the component used is a local file (not recommended for production use), but others are also available.
|
||||
|
||||
Visit [this](https://github.com/dapr/components-contrib/tree/master/secretstores) link for more information about secret store implementations.
|
||||
|
||||
|
@ -46,6 +46,10 @@ Then get into the examples directory:
|
|||
cd examples
|
||||
```
|
||||
|
||||
### Initialize Dapr
|
||||
|
||||
Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initialized.
|
||||
|
||||
### Creating a JSON secret file locally
|
||||
|
||||
Dapr's API for secret store only support read operations. For this sample to run, we will first create a secret file with a JSON string that contains two keys: `redisPassword` and `randomKey`.
|
||||
|
@ -103,7 +107,7 @@ public class SecretClient {
|
|||
}
|
||||
```
|
||||
The program receives two arguments at least: one's the secret store name and the others are secret's keys to be fetched.
|
||||
After identifying the secret store name that created and the keys to be fetched, it will retrieve them from the pre-defined secret store: `< repo dir >/examples/components/secrets/secret.json`.
|
||||
After identifying the secret store name that's created and the keys to be fetched, it will retrieve them from the pre-defined secret store: `< repo dir >/examples/components/secrets/secret.json`.
|
||||
The secret store's name **must** match the component's name defined in `< repo dir >/examples/components/secrets/local_file.yaml`.
|
||||
The Dapr client is also within a try-with-resource block to properly close the client at the end.
|
||||
|
||||
|
|
|
@ -32,6 +32,10 @@ Then change into the `examples` directory:
|
|||
cd examples
|
||||
```
|
||||
|
||||
### Initialize Dapr
|
||||
|
||||
Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initialized.
|
||||
|
||||
### Running the StateClient
|
||||
This example uses the Java SDK Dapr client in order to save, retrieve and delete a state, in this case, an instance of a class. Multiple state stores are supported since Dapr 0.4. See the code snippet bellow:
|
||||
|
||||
|
@ -128,7 +132,7 @@ This example performs multiple operations:
|
|||
* `client.getState(...)` operation in order to retrieve back the persisted state using the same key.
|
||||
* `client.executeStateTransaction(...)` operation in order to update existing state and add new state.
|
||||
* `client.getBulkState(...)` operation in order to retrieve back the persisted states using the same keys.
|
||||
* `client.deleteState(...)` operation to remove one of the persisted states. An example of etag mismatch error if a different than current etag is added to request.
|
||||
* `client.deleteState(...)` operation to remove one of the persisted states. An example of etag mismatch error is if something other than the current etag is added to request.
|
||||
* `client.executeStateTransaction(...)` operation in order to remove the other persisted state.
|
||||
|
||||
Finally, the code tries to retrieve the deleted states, which should not be found.
|
||||
|
|
|
@ -22,7 +22,7 @@ This sample uses the Client provided in Dapr Java SDK invoking a remote method a
|
|||
* [Oracle JDK 11](https://www.oracle.com/technetwork/java/javase/downloads/index.html#JDK11)
|
||||
* [OpenJDK 11](https://jdk.java.net/11/)
|
||||
* [Apache Maven](https://maven.apache.org/install.html) version 3.x.
|
||||
* [Configure Redis](https://docs.dapr.io/getting-started/configure-redis/) as a state store for Dapr.
|
||||
* [Configure Redis](https://docs.dapr.io/developing-applications/building-blocks/state-management/query-state-store/query-redis-store/) as a state store for Dapr.
|
||||
|
||||
### Checking out the code
|
||||
|
||||
|
@ -46,9 +46,13 @@ Then get into the examples directory:
|
|||
cd examples
|
||||
```
|
||||
|
||||
### Initialize Dapr
|
||||
|
||||
Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initialized.
|
||||
|
||||
### Verify Zipkin is running
|
||||
|
||||
Run `docker ps` to see if the container `dapr_zipkin` is running locally:
|
||||
Run `docker ps` to verify the container `dapr_zipkin` is running locally:
|
||||
|
||||
```bash
|
||||
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
|
||||
|
@ -78,7 +82,7 @@ public class TracingDemoService {
|
|||
}
|
||||
```
|
||||
|
||||
`DaprApplication.start()` Method will run a Spring Boot application that registers the `TracingDemoServiceController`, which exposes the invoking actions as POST requests. The Dapr's sidecar is the one that performs the actual call to the controller, triggered by client invocations or [bindings](https://docs.dapr.io/developing-applications/building-blocks/bindings/bindings-overview/).
|
||||
`DaprApplication.start()` Method will run a Spring Boot application that registers the `TracingDemoServiceController`, which exposes the invoking actions as POST requests. Dapr's sidecar is the one that performs the actual call to the controller, triggered by client invocations or [bindings](https://docs.dapr.io/developing-applications/building-blocks/bindings/bindings-overview/).
|
||||
|
||||
This Rest Controller exposes the `echo` and `sleep` methods. The `echo` method retrieves metadata from the headers and prints them along with the current date in console. The actual response from method is the formatted current date. See the code snippet below:
|
||||
|
||||
|
@ -111,7 +115,7 @@ public class TracingDemoServiceController {
|
|||
}
|
||||
```
|
||||
|
||||
The `sleep` methods simply waits for one second to simulate a slow operation.
|
||||
The `sleep` method simply waits for one second to simulate a slow operation.
|
||||
```java
|
||||
@RestController
|
||||
public class TracingDemoServiceController {
|
||||
|
@ -127,7 +131,7 @@ public class TracingDemoServiceController {
|
|||
|
||||
The instrumentation for the service happens via the `OpenTelemetryIterceptor` class. This class uses the [OpenTelemetrySDK](https://github.com/open-telemetry/opentelemetry-java) for Java.
|
||||
|
||||
Use the follow command to execute the service:
|
||||
Use the following command to execute the service:
|
||||
|
||||
<!-- STEP
|
||||
name: Run demo service
|
||||
|
@ -172,7 +176,7 @@ public class TracingDemoMiddleServiceController {
|
|||
}
|
||||
```
|
||||
|
||||
The request attribute `opentelemetry-context` in created by parsing the tracing headers in the [OpenTelemetryInterceptor](../OpenTelemetryInterceptor.java) class. See the code below:
|
||||
The request attribute `opentelemetry-context` is created by parsing the tracing headers in the [OpenTelemetryInterceptor](../OpenTelemetryInterceptor.java) class. See the code below:
|
||||
|
||||
```java
|
||||
@Component
|
||||
|
@ -214,7 +218,7 @@ public class OpenTelemetryConfig {
|
|||
}
|
||||
```
|
||||
|
||||
Use the follow command to execute the service:
|
||||
Use the following command to execute the service:
|
||||
|
||||
<!-- STEP
|
||||
name: Run proxy service
|
||||
|
@ -270,7 +274,7 @@ private static final String SERVICE_APP_ID = "tracingdemoproxy";
|
|||
}
|
||||
```
|
||||
|
||||
The class knows the app id for the remote application. It uses `invokeMethod` method to invoke API calls on the service endpoint. The request object includes an instance of `io.opentelemetry.context.Context` for the proper tracing headers to be propagated.
|
||||
The class knows the app id for the remote application. It uses the `invokeMethod` method to invoke API calls on the service endpoint. The request object includes an instance of `io.opentelemetry.context.Context` for the proper tracing headers to be propagated.
|
||||
|
||||
Execute the follow script in order to run the InvokeClient example, passing two messages for the remote method:
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## Unit testing sample
|
||||
|
||||
This sample illustrates how applications can write unit testing with Dapr's Java SDK, JUnit 5 and Mockito.
|
||||
This sample illustrates how applications can write unit tests with Dapr's Java SDK, JUnit 5 and Mockito.
|
||||
|
||||
## Pre-requisites
|
||||
|
||||
|
@ -32,6 +32,10 @@ Then change into the `examples` directory:
|
|||
cd examples
|
||||
```
|
||||
|
||||
### Initialize Dapr
|
||||
|
||||
Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initialized.
|
||||
|
||||
### Understanding the code
|
||||
|
||||
#### Example App Test
|
||||
|
@ -76,7 +80,7 @@ This example, found in `DaprExampleTest.java`, will simulate an application code
|
|||
```
|
||||
|
||||
This class has two constructors. The first one can be used by production code by passing the proper instances of `DaprClient` and `ActorClient`.
|
||||
Then, it contains two methods: `getState()` will retrieve a state from `DaprClient`, while `invokeActor()` will create an instance of Actor proxy for `MyActor` interface and invoke a method on it.
|
||||
The second, contains two methods: `getState()` will retrieve a state from the `DaprClient`, while `invokeActor()` will create an instance of the Actor proxy for `MyActor` interface and invoke a method on it.
|
||||
|
||||
```java
|
||||
@ActorType(name = "MyActor")
|
||||
|
@ -117,7 +121,7 @@ The second test uses a mock implementation of the factory method and checks the
|
|||
```
|
||||
|
||||
|
||||
##### Running the example
|
||||
#### Running the example
|
||||
<!-- STEP
|
||||
name: Check state example
|
||||
expected_stdout_lines:
|
||||
|
@ -184,7 +188,7 @@ private class DemoWorkflow extends Workflow {
|
|||
}
|
||||
```
|
||||
|
||||
The example provides its own workflow, but for a production system you would want to import and use your own workflow. The goal of unit testing a workflow is to ensure that the business logic functions as expected. For our example that is these two sections:
|
||||
The example provides its own workflow, but for a production system you would want to import and use your own workflow. The goal of unit testing a workflow is to ensure that the business logic functions as expected. For our example, that involves the following two sections:
|
||||
|
||||
```java
|
||||
String output = name + ":" + id;
|
||||
|
@ -248,7 +252,7 @@ The third test is similar but validates the inverse of the test above, ensuring
|
|||
```
|
||||
|
||||
|
||||
##### Running the example
|
||||
#### Running the example
|
||||
<!-- STEP
|
||||
name: Check state example
|
||||
expected_stdout_lines:
|
||||
|
|
|
@ -13,7 +13,6 @@ This example contains the follow classes:
|
|||
## Pre-requisites
|
||||
|
||||
* [Dapr and Dapr Cli](https://docs.dapr.io/getting-started/install-dapr/).
|
||||
* Run `dapr init`.
|
||||
* Java JDK 11 (or greater):
|
||||
* [Microsoft JDK 11](https://docs.microsoft.com/en-us/java/openjdk/download#openjdk-11)
|
||||
* [Oracle JDK 11](https://www.oracle.com/technetwork/java/javase/downloads/index.html#JDK11)
|
||||
|
@ -41,9 +40,13 @@ Get into the `examples` directory.
|
|||
cd examples
|
||||
```
|
||||
|
||||
### Initialize Dapr
|
||||
|
||||
Run `dapr init` to initialize Dapr in Self-Hosted Mode if it's not already initialized.
|
||||
|
||||
### Running the demo Workflow worker
|
||||
|
||||
The first Java class to consider is `DemoWorkflowWorker`. Its job is to register an implementation of `DemoWorkflow` in the Dapr's workflow runtime engine. In `DemoWorkflowWorker.java` file, you will find the `DemoWorkflowWorker` class and the `main` method. See the code snippet below:
|
||||
The first Java class to consider is `DemoWorkflowWorker`. It's job is to register an implementation of `DemoWorkflow` in Dapr's workflow runtime engine. In the `DemoWorkflowWorker.java` file, you will find the `DemoWorkflowWorker` class and the `main` method. See the code snippet below:
|
||||
|
||||
```java
|
||||
public class DemoWorkflowWorker {
|
||||
|
@ -60,7 +63,7 @@ public class DemoWorkflowWorker {
|
|||
|
||||
This application uses `WorkflowRuntime.getInstance().registerWorkflow()` in order to register `DemoWorkflow` as a Workflow in the Dapr Workflow runtime.
|
||||
|
||||
`WorkflowRuntime.getInstance().start()` method will build and start the engine within the Dapr workflow runtime.
|
||||
The `WorkflowRuntime.getInstance().start()` method will build and start the engine within the Dapr workflow runtime.
|
||||
|
||||
Now, execute the following script in order to run DemoWorkflowWorker:
|
||||
```sh
|
||||
|
|
|
@ -64,7 +64,7 @@ public class DaprClientBuilder {
|
|||
/**
|
||||
* Creates a constructor for DaprClient.
|
||||
*
|
||||
* {@link DefaultObjectSerializer} is used for object and state serializers by defaul but is not recommended
|
||||
* {@link DefaultObjectSerializer} is used for object and state serializers by default but is not recommended
|
||||
* for production scenarios.
|
||||
*/
|
||||
public DaprClientBuilder() {
|
||||
|
|
Loading…
Reference in New Issue