Skip to content

Commit 7dcab0b

Browse files
salaboycicoyleartursouza
authored
Adding SpringBoot docs for new integrations (#1123)
* initial docs Signed-off-by: salaboy <Salaboy@gmail.com> * updating spring boot integration docs for Java SDK Signed-off-by: salaboy <Salaboy@gmail.com> * Update daprdocs/content/en/java-sdk-docs/spring-boot/_index.md Co-authored-by: Cassie Coyle <cassie.i.coyle@gmail.com> Signed-off-by: salaboy <Salaboy@gmail.com> * Update daprdocs/content/en/java-sdk-docs/spring-boot/_index.md Co-authored-by: Cassie Coyle <cassie.i.coyle@gmail.com> Signed-off-by: salaboy <Salaboy@gmail.com> * Update daprdocs/content/en/java-sdk-docs/spring-boot/_index.md Co-authored-by: Cassie Coyle <cassie.i.coyle@gmail.com> Signed-off-by: salaboy <Salaboy@gmail.com> * Update daprdocs/content/en/java-sdk-docs/spring-boot/_index.md Co-authored-by: Cassie Coyle <cassie.i.coyle@gmail.com> Signed-off-by: salaboy <Salaboy@gmail.com> --------- Signed-off-by: salaboy <Salaboy@gmail.com> Co-authored-by: Cassie Coyle <cassie@diagrid.io> Co-authored-by: Cassie Coyle <cassie.i.coyle@gmail.com> Co-authored-by: Artur Souza <artursouza.ms@outlook.com>
1 parent 6a6901d commit 7dcab0b

File tree

1 file changed

+285
-0
lines changed
  • daprdocs/content/en/java-sdk-docs/spring-boot

1 file changed

+285
-0
lines changed
Lines changed: 285 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,285 @@
1+
---
2+
type: docs
3+
title: "Getting started with the Dapr and Spring Boot"
4+
linkTitle: "Spring Boot Integration"
5+
weight: 4000
6+
description: How to get started with Dapr and Spring Boot
7+
---
8+
9+
By combining Dapr and Spring Boot, we can create infrastructure independent Java applications that can be deployed across different environments, supporting a wide range of on-premises and cloud provider services.
10+
11+
First, we will start with a simple integration covering the `DaprClient` and the [Testcontainers](https://testcontainers.com/) integration, to then use Spring and Spring Boot mechanisms and programming model to leverage the Dapr APIs under the hood. This help teams to remove dependencies such as clients and drivers required to connect to environment specific infrastructure (databases, key-value stores, message brokers, configuration/secret stores, etc.)
12+
13+
{{% alert title="Note" color="primary" %}}
14+
The Spring Boot integration explained in this page is still alpha, hence most artifacts are labeled with 0.13.0.
15+
16+
{{% /alert %}}
17+
18+
19+
## Adding the Dapr and Spring Boot integration to your project
20+
21+
If you already have a Spring Boot application (Spring Boot 3.x+), you can directly add the following dependencies to your project:
22+
23+
24+
```
25+
<dependency>
26+
<groupId>io.dapr.spring</groupId>
27+
<artifactId>dapr-spring-boot-starter</artifactId>
28+
<version>0.13.0-SNAPSHOT</version>
29+
</dependency>
30+
<dependency>
31+
<groupId>io.dapr.spring</groupId>
32+
<artifactId>dapr-spring-boot-starter-test</artifactId>
33+
<version>0.13.0-SNAPSHOT</version>
34+
<scope>test</scope>
35+
</dependency>
36+
```
37+
38+
By adding these dependencies you can:
39+
- Autowire a `DaprClient` to use inside your applications
40+
- Use the Spring Data and Messaging abstractions and programming model that uses the Dapr APIs under the hood
41+
- Improve your inner-development loop by relying on [Testcontainers](https://testcontainers.com/) to bootstrap Dapr Control plane services and default components
42+
43+
Once these dependencies are in your application, you can rely on Spring Boot autoconfiguration to autowire a `DaprClient` instance:
44+
45+
```java
46+
@Autowired
47+
private DaprClient daprClient;
48+
49+
```
50+
51+
This will connect to the default Dapr gRPC endpoint `localhost:50001`, requiring you to start Dapr outside of your application.
52+
53+
You can use the `DaprClient` to interact with the Dapr APIs anywhere in your application, for example from inside a REST endpoint:
54+
55+
```java
56+
@RestController
57+
public class DemoRestController {
58+
@Autowired
59+
private DaprClient daprClient;
60+
61+
@PostMapping("/store")
62+
public void storeOrder(@RequestBody Order order){
63+
daprClient.saveState("kvstore", order.orderId(), order).block();
64+
}
65+
}
66+
67+
record Order(String orderId, Integer amount){}
68+
```
69+
70+
If you want to avoid managing Dapr outside of your Spring Boot application, you can rely on [Testcontainers](https://testcontainers.com/) to bootstrap Dapr besides your application for development purposes.
71+
To do this we can create a test configuration that uses `Testcontainers` to bootstrap all we need to develop our applications using the Dapr APIs.
72+
73+
Using [Testcontaniners](https://testcontainers.com/) and Dapr integrations, we let the `@TestConfiguration` to bootstrap Dapr for our applications.
74+
Notice that for this example, we are configuring Dapr with a Statestore component called `kvstore` that connects to an instance of `PostgreSQL` also bootstrapped by Testcontainers.
75+
76+
```java
77+
@TestConfiguration(proxyBeanMethods = false)
78+
public class DaprTestContainersConfig {
79+
@Bean
80+
@ServiceConnection
81+
public DaprContainer daprContainer(Network daprNetwork, PostgreSQLContainer<?> postgreSQLContainer){
82+
83+
return new DaprContainer("daprio/daprd:1.14.1")
84+
.withAppName("producer-app")
85+
.withNetwork(daprNetwork)
86+
.withComponent(new Component("kvstore", "state.postgresql", "v1", STATE_STORE_PROPERTIES))
87+
.withComponent(new Component("kvbinding", "bindings.postgresql", "v1", BINDING_PROPERTIES))
88+
.dependsOn(postgreSQLContainer);
89+
}
90+
}
91+
```
92+
93+
Inside the test classpath you can add a new Spring Boot Application that uses this configuration for tests:
94+
95+
```java
96+
@SpringBootApplication
97+
public class TestProducerApplication {
98+
99+
public static void main(String[] args) {
100+
101+
SpringApplication
102+
.from(ProducerApplication::main)
103+
.with(DaprTestContainersConfig.class)
104+
.run(args);
105+
}
106+
107+
}
108+
```
109+
110+
Now you can start your application with:
111+
```bash
112+
mvn spring-boot:test-run
113+
```
114+
115+
Running this command will start the application, using the provided test configuration that includes the Testcontainers and Dapr integration. In the logs you should be able to see that the `daprd` and the `placement` service containers were started for your application.
116+
117+
Besides the previous configuration (`DaprTestContainersConfig`) your tests shouldn't be testing Dapr itself, just the REST endpoints that your application is exposing.
118+
119+
120+
## Leveraging Spring & Spring Boot programming model with Dapr
121+
122+
The Java SDK allows you to interface with all of the [Dapr building blocks]({{< ref building-blocks >}}).
123+
But if you want to leverage the Spring and Spring Boot programming model you can use the `dapr-spring-boot-starter` integration.
124+
This includes implementations of Spring Data (`KeyValueTemplate` and `CrudRepository`) as well as a `DaprMessagingTemplate` for producing and consuming messages
125+
(similar to [Spring Kafka](https://spring.io/projects/spring-kafka), [Spring Pulsar](https://spring.io/projects/spring-pulsar) and [Spring AMQP for RabbitMQ](https://spring.io/projects/spring-amqp)).
126+
127+
## Using Spring Data `CrudRepository` and `KeyValueTemplate`
128+
129+
You can use well known Spring Data constructs relying on a Dapr-based implementation.
130+
With Dapr, you don't need to add any infrastructure-related driver or client, making your Spring application lighter and decoupled from the environment where it is running.
131+
132+
Under the hood these implementations use the Dapr Statestore and Binding APIs.
133+
134+
### Configuration parameters
135+
136+
With Spring Data abstractions you can configure which statestore and bindings will be used by Dapr to connect to the available infrastructure.
137+
This can be done by setting the following properties:
138+
139+
```properties
140+
dapr.statestore.name=kvstore
141+
dapr.statestore.binding=kvbinding
142+
```
143+
144+
Then you can `@Autowire` a `KeyValueTemplate` or a `CrudRepository` like this:
145+
146+
```java
147+
@RestController
148+
@EnableDaprRepositories
149+
public class OrdersRestController {
150+
@Autowired
151+
private OrderRepository repository;
152+
153+
@PostMapping("/orders")
154+
public void storeOrder(@RequestBody Order order){
155+
repository.save(order);
156+
}
157+
158+
@GetMapping("/orders")
159+
public Iterable<Order> getAll(){
160+
return repository.findAll();
161+
}
162+
163+
164+
}
165+
```
166+
167+
Where `OrderRepository` is defined in an interface that extends the Spring Data `CrudRepository` interface:
168+
169+
```java
170+
public interface OrderRepository extends CrudRepository<Order, String> {}
171+
```
172+
173+
Notice that the `@EnableDaprRepositories` annotation, does all the magic of wiring the Dapr APIs under the `CrudRespository` interface.
174+
Because Dapr allow users to interact with different StateStores from the same application, as a user you need to provide the following beans as a Spring Boot `@Configuration`:
175+
176+
```java
177+
@Configuration
178+
@EnableConfigurationProperties({DaprStateStoreProperties.class})
179+
public class ProducerAppConfiguration {
180+
181+
@Bean
182+
public KeyValueAdapterResolver keyValueAdapterResolver(DaprClient daprClient, ObjectMapper mapper, DaprStateStoreProperties daprStatestoreProperties) {
183+
String storeName = daprStatestoreProperties.getName();
184+
String bindingName = daprStatestoreProperties.getBinding();
185+
186+
return new DaprKeyValueAdapterResolver(daprClient, mapper, storeName, bindingName);
187+
}
188+
189+
@Bean
190+
public DaprKeyValueTemplate daprKeyValueTemplate(KeyValueAdapterResolver keyValueAdapterResolver) {
191+
return new DaprKeyValueTemplate(keyValueAdapterResolver);
192+
}
193+
194+
}
195+
```
196+
197+
## Using Spring Messaging for producing and consuming events
198+
199+
Similar to Spring Kafka, Spring Pulsar and Spring AMQP you can use the `DaprMessagingTemplate` to publish messages to the configured infrastructure. To consume messages you can use the `@Topic` annotation (soon to be renamed to `@DaprListener`).
200+
201+
To publish events/messages you can `@Autowired` the `DaprMessagingTemplate` in your Spring application.
202+
For this example we will be publishing `Order` events and we are sending messages to the topic named `topic`.
203+
204+
```java
205+
@Autowired
206+
private DaprMessagingTemplate<Order> messagingTemplate;
207+
208+
@PostMapping("/orders")
209+
public void storeOrder(@RequestBody Order order){
210+
repository.save(order);
211+
messagingTemplate.send("topic", order);
212+
}
213+
214+
```
215+
216+
Similarly to the `CrudRepository` we need to specify which PubSub broker do we want to use to publish and consume our messages.
217+
218+
```properties
219+
dapr.pubsub.name=pubsub
220+
```
221+
222+
Because with Dapr you can connect to multiple PubSub brokers you need to provide the following bean to let Dapr know which PubSub broker your `DaprMessagingTemplate` will use:
223+
```java
224+
@Bean
225+
public DaprMessagingTemplate<Order> messagingTemplate(DaprClient daprClient,
226+
DaprPubSubProperties daprPubSubProperties) {
227+
return new DaprMessagingTemplate<>(daprClient, daprPubSubProperties.getName());
228+
}
229+
```
230+
231+
Finally, because Dapr PubSub requires a bidirectional connection between your application and Dapr you need to expand your Testcontainers configuration with a few parameters:
232+
233+
```java
234+
@Bean
235+
@ServiceConnection
236+
public DaprContainer daprContainer(Network daprNetwork, PostgreSQLContainer<?> postgreSQLContainer, RabbitMQContainer rabbitMQContainer){
237+
238+
return new DaprContainer("daprio/daprd:1.14.1")
239+
.withAppName("producer-app")
240+
.withNetwork(daprNetwork)
241+
.withComponent(new Component("kvstore", "state.postgresql", "v1", STATE_STORE_PROPERTIES))
242+
.withComponent(new Component("kvbinding", "bindings.postgresql", "v1", BINDING_PROPERTIES))
243+
.withComponent(new Component("pubsub", "pubsub.rabbitmq", "v1", rabbitMqProperties))
244+
.withAppPort(8080)
245+
.withAppChannelAddress("host.testcontainers.internal")
246+
.dependsOn(rabbitMQContainer)
247+
.dependsOn(postgreSQLContainer);
248+
}
249+
```
250+
251+
Now, in the Dapr configuration we have included a `pubsub` component that will connect to an instance of RabbitMQ started by Testcontainers.
252+
We have also set two important parameters `.withAppPort(8080)` and `.withAppChannelAddress("host.testcontainers.internal")` which allows Dapr to
253+
contact back to the application when a message is published in the broker.
254+
255+
To listen to events/messages you need to expose an endpoint in the application that will be responsible to receive the messages.
256+
If you expose a REST endpoint you can use the `@Topic` annotation to let Dapr know where it needs to forward the events/messages too:
257+
258+
```java
259+
@PostMapping("subscribe")
260+
@Topic(pubsubName = "pubsub", name = "topic")
261+
public void subscribe(@RequestBody CloudEvent<Order> cloudEvent){
262+
events.add(cloudEvent);
263+
}
264+
```
265+
266+
Upon bootstrapping your application, Dapr will register the subscription to messages to be forwarded to the `subscribe` endpoint exposed by your application.
267+
268+
If you are writing tests for these subscribers you need to ensure that Testcontainers knows that your application will be running on port 8080,
269+
so containers started with Testcontainers know where your application is:
270+
271+
```java
272+
@BeforeAll
273+
public static void setup(){
274+
org.testcontainers.Testcontainers.exposeHostPorts(8080);
275+
}
276+
```
277+
278+
You can check and run the [full example source code here](https://github.com/salaboy/dapr-spring-boot-docs-examples).
279+
280+
## Next steps
281+
282+
Learn more about the [Dapr Java SDK packages available to add to your Java applications](https://dapr.github.io/java-sdk/).
283+
284+
## Related links
285+
- [Java SDK examples](https://github.com/dapr/java-sdk/tree/master/examples/src/main/java/io/dapr/examples)

0 commit comments

Comments
 (0)