├── .gitignore
├── pom.xml
├── spring-data-r2dbc-wordpress.md
├── spring-data-r2dbc.md
└── src
└── main
├── kotlin
└── com
│ └── lankydanblog
│ └── tutorial
│ ├── Application.kt
│ ├── DatabaseConfiguration.kt
│ └── person
│ ├── Person.kt
│ └── repository
│ └── PersonRepository.kt
└── resources
└── application.properties
/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 |
4 | ### STS ###
5 | .apt_generated
6 | .classpath
7 | .factorypath
8 | .project
9 | .settings
10 | .springBeans
11 | .sts4-cache
12 |
13 | ### IntelliJ IDEA ###
14 | .idea
15 | *.iws
16 | *.iml
17 | *.ipr
18 |
19 | ### NetBeans ###
20 | /nbproject/private/
21 | /nbbuild/
22 | /dist/
23 | /nbdist/
24 | /.nb-gradle/
25 | /build/
26 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | org.springframework.boot
8 | spring-boot-starter-parent
9 | 2.2.0.M3
10 |
11 |
12 | com.lankydanblog.tutorial
13 | spring-r2dbc
14 | 0.0.1-SNAPSHOT
15 | spring-r2dbc
16 | Demo project for Spring Boot
17 |
18 |
19 | 1.8
20 | 1.3.21
21 |
22 |
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter
27 |
28 |
29 | org.springframework.data
30 | spring-data-r2dbc
31 | 1.0.0.M2
32 |
33 |
34 |
35 | io.r2dbc
36 | r2dbc-postgresql
37 | 0.8.0.M8
38 |
39 |
40 |
41 | io.projectreactor
42 | reactor-core
43 |
44 |
45 | org.jetbrains.kotlin
46 | kotlin-reflect
47 |
48 |
49 | org.jetbrains.kotlin
50 | kotlin-stdlib-jdk8
51 |
52 |
53 |
54 | org.springframework.boot
55 | spring-boot-starter-test
56 | test
57 |
58 |
59 |
60 |
61 |
62 | repository.spring.milestone
63 | Spring Milestone Repository
64 | http://repo.spring.io/milestone
65 |
66 |
67 |
68 |
69 | ${project.basedir}/src/main/kotlin
70 | ${project.basedir}/src/test/kotlin
71 |
72 |
73 | org.springframework.boot
74 | spring-boot-maven-plugin
75 | 2.1.5.RELEASE
76 |
77 |
78 | org.jetbrains.kotlin
79 | kotlin-maven-plugin
80 |
81 |
82 | -Xjsr305=strict
83 |
84 |
85 | spring
86 | jpa
87 |
88 |
89 |
90 |
91 | org.jetbrains.kotlin
92 | kotlin-maven-allopen
93 | ${kotlin.version}
94 |
95 |
96 | org.jetbrains.kotlin
97 | kotlin-maven-noarg
98 | ${kotlin.version}
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
--------------------------------------------------------------------------------
/spring-data-r2dbc-wordpress.md:
--------------------------------------------------------------------------------
1 |
2 |
Not too long ago, a reactive variant of the JDBC driver was released. Known as R2DBC. It allows data to be streamed asynchronously to any endpoints that have subscribed to it. Using a reactive driver like R2DBC together with Spring WebFlux allows you to write a full application that handles receiving and sending of data asynchronously. In this post, we will focus on the database. From connecting to the database and then finally saving and retrieving data. To do this, we will be using Spring Data. As with all Spring Data modules, it provides us with out of the box configuration. Decreasing the amount of boilerplate code that we need to write to get our application setup. On top of that, it provides a layer upon the database driver that makes doing the simple tasks easier and the more difficult tasks a little less painful.
3 |
4 |
5 |
6 | For the content of this post, I am making use of a Postgres database. At the time of writing only Postgres, H2 and Microsoft SQL Server have their own implementations of R2DBC drivers.
7 |
8 |
9 |
10 | I have previously written two posts about reactive Spring Data libraries, one on Mongo and another about Cassandra. You might have noticed that neither of these databases are RDBMS databases. Now there are other reactive drivers available for a long time (I wrote the Mongo post nearly 2 years ago) but at the time of writing a reactive driver for a RDBMS database is still a pretty new thing. This post will follow a similar format to those.
11 |
12 |
13 |
14 | Furthermore, I have also written a post about using Spring WebFlux which I mentioned in the introduction. Feel free to have a look at that if you are interested in producing a fully reactive web application.
15 |
16 |
17 |
18 | Dependencies
19 |
20 |
21 |
22 | [gist https://gist.github.com/lankydan/38b799a72c630d843c73ca5f6e75ac51 /]
23 |
24 |
25 |
26 | There are a few things to point out here.
27 |
28 |
29 |
30 | The more you use Spring Boot, the more you will get used to importing a single spring-boot-starter
dependency for the cool thing that you want to do. For example, I hoped that there would have been a spring-boot-starter-r2dbc
dependency, but unfortunately, there is not one. Yet. Simply put, this library is on the newer side and at the time of writing, does not have its own Spring Boot module that contains any dependencies it needs along with faster setup via auto-configuration. I am sure these things will come at some point and make setting up a R2DBC driver even easier.
31 |
32 |
33 |
34 | For now, we will need to fill in a few extra dependencies manually.
35 |
36 |
37 |
38 | Furthermore, the R2DBC libraries only have Milestone releases (more proof of them being new) so we need to make sure we bring in the Spring Milestone repository. I will probably need to update this post in the future when it gets a release version.
39 |
40 |
41 |
42 | Connecting to the database
43 |
44 |
45 |
46 | Thanks to Spring Data doing a lot of the work for us, the only Bean that needs to be created manually is the ConnectionFactory
that contains the database's connection details:
47 |
48 |
49 |
50 | [gist https://gist.github.com/lankydan/93431efc72485a1468ba489c08e66b40 /]
51 |
52 |
53 |
54 | The first thing to notice here is the extension of AbstractR2dbcConfiguration
. This class contains a load of Beans that we no longer need to manually create. Implementing connectionFactory
is the only requirement of the class as it is required to create the DatabaseClient
Bean. This sort of structure is typical of Spring Data modules so it feels quite familiar when trying out a different one. Furthermore, I'd expect this manual configuration to be removed once auto-configuration is available and be solely driven via the application.properties
.
55 |
56 |
57 |
58 | I have included the port
property here, but if you have not played around with your Postgres configuration then you can rely on the default value of 5432
.
59 |
60 |
61 |
62 | The four properties: host
, database
, username
and password
defined by the PostgresqlConnectionFactory
are the bare minimum to get it working. Any less and you will experience exceptions during startup.
63 |
64 |
65 |
66 | Using this configuration, Spring is able to connect to a running Postgres instance.
67 |
68 |
69 |
70 | The final piece of noteworthy information from this example is the use of @EnableR2dbcRepositories
. This annotation instructs Spring to find any repository interfaces that extend Spring's Repository
interface. This is used as the base interface for instrumenting Spring Data repositories. We will look at this a little closer in the next section. The main piece of information to take away from here is that you need to use the @EnableR2dbcRepositories
annotation to fully leverage Spring Data's capabilities.
71 |
72 |
73 |
74 | Creating a Spring Data Repository
75 |
76 |
77 |
78 | As touched on above, in this section we will look at adding a Spring Data Repository. These repositories are a nice feature of Spring Data, meaning that you don't need to write out a load of extra code to simply write a query. Unfortunately, at least for now, Spring R2DBC cannot infer queries in the same way that other Spring Data modules currently do (I am sure this will be added at some point). This means that you will need to use the @Query
annotation and write the SQL by hand. Let's take a look:
79 |
80 |
81 |
82 | [gist https://gist.github.com/lankydan/ec23a1ac53740365668bec2a8763fa79 /]
83 |
84 |
85 |
86 | This interface extends R2dbcRepository
. This in turn extends ReactiveCrudRepository
and then down to Repository
. ReactiveCrudRepository
provides the standard CRUD functions and from what I understand, R2dbcRepository
does not provide any extra functions and is instead an interface created for better situational naming.
87 |
88 |
89 |
90 | R2dbcRepository
takes in two generic parameters, one being the entity class that it takes as input and produces as output. The second being the type of the Primary Key. Therefore in this situation, the Person
class is being managed by the PersonRepository
(makes sense) and the Primary Key field inside Person
is an Int
.
91 |
92 |
93 |
94 | The return types of functions in this class and the ones provided by ReactiveCrudRepository
are Flux
and Mono
(not seen here). These are Project Reactor types that Spring makes use of as the default Reactive Stream types. Flux
represents a stream of multiple elements whereas a Mono
is a single result.
95 |
96 |
97 |
98 | Finally, as I mentioned before the example, each function is annotated with @Query
. The syntax is quite straight forward, with the SQL being a string inside the annotation. The $1
($2
, $3
, etc... for more inputs) represents the value input into the function. Once you have done this, Spring will handle the rest and pass the input(s) into their respective input parameter, gather the results and map it to the repository's designated entity class.
99 |
100 |
101 |
102 | A very quick look at the entity
103 |
104 |
105 |
106 | Not going to say much here but simply show the Person
class used by the PersonRepository
.
107 |
108 |
109 |
110 | [gist https://gist.github.com/lankydan/74e8736f9f6618172042686ea456a7de /]
111 |
112 |
113 |
114 | Actually, there is one point to make here. id
has been made nullable and provided a default value of null
to allow Postgres to generate the next suitable value itself. If this is not nullable and an id
value is provided, Spring will actually try to run an update instead of an insert upon saving. There are other ways around this, but I think this is good enough.
115 |
116 |
117 |
118 | This entity will map to the people
table defined below:
119 |
120 | [gist https://gist.github.com/lankydan/842f1521134ab4c2eb214fdafc624b9c /]
121 |
122 |
123 |
124 | Seeing it all in action
125 |
126 |
127 |
128 | Now let's have a look at it actually doing something. Below is some code that inserts a few records and retrieves them in a few different ways:
129 |
130 |
131 |
132 | [gist https://gist.github.com/lankydan/b6a9d7550b4ba6efe5c3846135062c43 /]
133 |
134 |
135 |
136 | One thing I will mention about this code. There is a very real possibility that it executes without actually inserting or reading some of the records. But, when you think about it. It makes sense. Reactive applications are meant to do things asynchronously and therefore this application has started processing the function calls in different threads. Without blocking the main thread, these asynchronous processes might never fully execute. For this reason, there are some Thread.sleep
calls in this code, but I removed them from the example to keep everything tidy.
137 |
138 |
139 |
140 | The output for running the code above would look something like the below:
141 |
142 |
143 |
144 | 2019-02-11 09:04:52.294 INFO 13226 --- [ main] reactor.Flux.ConcatMap.1 : onSubscribe(FluxConcatMap.ConcatMapImmediate)
2019-02-11 09:04:52.295 INFO 13226 --- [ main] reactor.Flux.ConcatMap.1 : request(unbounded)
2019-02-11 09:04:52.572 INFO 13226 --- [actor-tcp-nio-1] reactor.Flux.ConcatMap.1 : onNext(Person(id=35, name=Dan Newton, age=25))
2019-02-11 09:04:52.591 INFO 13226 --- [actor-tcp-nio-1] reactor.Flux.ConcatMap.1 : onNext(Person(id=36, name=Laura So, age=23))
2019-02-11 09:04:52.591 INFO 13226 --- [actor-tcp-nio-1] reactor.Flux.ConcatMap.1 : onComplete()
2019-02-11 09:04:54.472 INFO 13226 --- [actor-tcp-nio-2] com.lankydanblog.tutorial.Application : findAll - Person(id=35, name=Dan Newton, age=25)
2019-02-11 09:04:54.473 INFO 13226 --- [actor-tcp-nio-2] com.lankydanblog.tutorial.Application : findAll - Person(id=36, name=Laura So, age=23)
2019-02-11 09:04:54.512 INFO 13226 --- [actor-tcp-nio-4] com.lankydanblog.tutorial.Application : findAllByName - Person(id=36, name=Laura So, age=23)
2019-02-11 09:04:54.524 INFO 13226 --- [actor-tcp-nio-5] com.lankydanblog.tutorial.Application : findAllByAge - Person(id=35, name=Dan Newton, age=25)
145 |
146 |
147 |
148 | A few things to take away here:
149 |
150 |
151 |
152 | onSubscribe
and request
occur on the main thread where the Flux
was called from. Only saveAll
outputs this since it has included the log
function. Adding this to the other calls would have lead to the same result of logging to the main thread. - The execution contained within the subscribe function and the internal steps of the
Flux
are ran on separate threads.
153 |
154 |
155 |
156 | This is not anywhere close to a real representation of how you would use Reactive Streams in an actual application but hopefully demonstrates how to use them and gives a bit of insight into how they execute.
157 |
158 |
159 |
160 | Conclusion
161 |
162 |
163 |
164 | In conclusion, Reactive Streams have come to some RDBMS databases thanks to the R2DBC driver and Spring Data that builds a layer on top to make everything a bit tidier. By using Spring Data R2DBC we are able to create a connection to a database and start querying it without the need of to much code. Although Spring is already doing a lot for us, it could be doing more. Currently, it does not have Spring Boot auto-configuration support. Which is a bit annoying. But, I am sure that someone will get around to doing it soon and make everything even better than it already is.
165 |
166 |
167 |
168 | The code used in this post can be found on my GitHub.
169 |
170 |
171 |
172 | If you found this post helpful, you can follow me on Twitter at @LankyDanDev to keep up with my new posts.
173 |
--------------------------------------------------------------------------------
/spring-data-r2dbc.md:
--------------------------------------------------------------------------------
1 | Not too long ago, a reactive variant of the JDBC driver was released. Known as R2DBC. It allows data to be streamed asynchronously to any endpoints that have subscribed to it. Using a reactive driver like R2DBC together with Spring WebFlux allows you to write a full application that handles receiving and sending of data asynchronously. In this post, we will focus on the database. From connecting to the database and then finally saving and retrieving data. To do this, we will be using Spring Data. As with all Spring Data modules, it provides us with out of the box configuration. Decreasing the amount of boilerplate code that we need to write to get our application setup. On top of that, it provides a layer upon the database driver that makes doing the simple tasks easier and the more difficult tasks a little less painful.
2 |
3 | For the content of this post, I am making use of a Postgres database. At the time of writing only Postgres, H2 and Microsoft SQL Server have their own implementations of R2DBC drivers.
4 |
5 | I have previously written two posts about reactive Spring Data libraries, one on [Mongo](https://lankydanblog.com/2017/07/16/a-quick-look-into-reactive-streams-with-spring-data-and-mongodb/) and another about [Cassandra](https://lankydanblog.com/2017/12/11/reactive-streams-with-spring-data-cassandra/). You might have noticed that neither of these databases are RDBMS databases. Now there are other reactive drivers available for a long time (I wrote the Mongo post nearly 2 years ago) but at the time of writing a reactive driver for a RDBMS database is still a pretty new thing. This post will follow a similar format to those.
6 |
7 | Furthermore, I have also written a post about using [Spring WebFlux](https://lankydanblog.com/2018/03/15/doing-stuff-with-spring-webflux/) which I mentioned in the introduction. Feel free to have a look at that if you are interested in producing a fully reactive web application.
8 |
9 | ### Dependencies
10 | ```xml
11 |
12 |
13 | org.springframework.boot
14 | spring-boot-starter
15 |
16 |
17 | org.springframework.data
18 | spring-data-r2dbc
19 | 1.0.0.M1
20 |
21 |
22 | io.r2dbc
23 | r2dbc-postgresql
24 | 1.0.0.M6
25 |
26 |
27 | io.projectreactor
28 | reactor-core
29 |
30 |
31 |
32 |
33 |
34 | repository.spring.milestone
35 | Spring Milestone Repository
36 | http://repo.spring.io/milestone
37 |
38 |
39 | ```
40 | There are a few things to point out here.
41 |
42 | The more you use Spring Boot, the more you will get used to importing a single `spring-boot-starter` dependency for the cool thing that you want to do. For example, I hoped that there would have been a `spring-boot-starter-r2dbc` dependency, but unfortunately, there is not one. Yet. Simply put, this library is on the newer side and at the time of writing, does not have its own Spring Boot module that contains any dependencies it needs along with faster setup via auto-configuration. I am sure these things will come at some point and make setting up a R2DBC driver even easier.
43 |
44 | For now, we will need to fill in a few extra dependencies manually.
45 |
46 | Furthermore, the R2DBC libraries only have Milestone releases (more proof of them being new) so we need to make sure we bring in the Spring Milestone repository. I will probably need to update this post in the future when it gets a release version.
47 |
48 | ### Connecting to the database
49 |
50 | Thanks to Spring Data doing a lot of the work for us, the only Bean that needs to be created manually is the `ConnectionFactory` that contains the database's connection details:
51 | ```kotlin
52 | @Configuration
53 | @EnableR2dbcRepositories
54 | class DatabaseConfiguration(
55 | @Value("\${spring.data.postgres.host}") private val host: String,
56 | @Value("\${spring.data.postgres.database}") private val database: String,
57 | @Value("\${spring.data.postgres.username}") private val username: String,
58 | @Value("\${spring.data.postgres.password}") private val password: String
59 | ) : AbstractR2dbcConfiguration() {
60 |
61 | override fun connectionFactory(): ConnectionFactory {
62 | return PostgresqlConnectionFactory(
63 | PostgresqlConnectionConfiguration.builder()
64 | .host(host)
65 | .database(database)
66 | .username(username)
67 | .password(password).build()
68 | )
69 | }
70 | }
71 | ```
72 | The first thing to notice here is the extension of `AbstractR2dbcConfiguration`. This class contains a load of Beans that we no longer need to manually create. Implementing `connectionFactory` is the only requirement of the class as it is required to create the `DatabaseClient` Bean. This sort of structure is typical of Spring Data modules so it feels quite familiar when trying out a different one. Furthermore, I'd expect this manual configuration to be removed once auto-configuration is available and be solely driven via the `application.properties`.
73 |
74 | I have included the `port` property here, but if you have not played around with your Postgres configuration then you can rely on the default value of `5432`.
75 |
76 | The four properties: `host`, `database`, `username` and `password` defined by the `PostgresqlConnectionFactory` are the bare minimum to get it working. Any less and you will experience exceptions during startup.
77 |
78 | Using this configuration, Spring is able to connect to a running Postgres instance.
79 |
80 | The final piece of noteworthy information from this example is the use of `@EnableR2dbcRepositories`. This annotation instructs Spring to find any repository interfaces that extend Spring's `Repository` interface. This is used as the base interface for instrumenting Spring Data repositories. We will look at this a little closer in the next section. The main piece of information to take away from here is that you need to use the `@EnableR2dbcRepositories` annotation to fully leverage Spring Data's capabilities.
81 |
82 | ### Creating a Spring Data Repository
83 |
84 | As touched on above, in this section we will look at adding a Spring Data Repository. These repositories are a nice feature of Spring Data, meaning that you don't need to write out a load of extra code to simply write a query. Unfortunately, at least for now, Spring R2DBC cannot infer queries in the same way that other Spring Data modules currently do (I am sure this will be added at some point). This means that you will need to use the `@Query` annotation and write the SQL by hand. Let's take a look:
85 | ```kotlin
86 | @Repository
87 | interface PersonRepository : R2dbcRepository {
88 |
89 | @Query("SELECT * FROM people WHERE name = $1")
90 | fun findAllByName(name: String): Flux
91 |
92 | @Query("SELECT * FROM people WHERE age = $1")
93 | fun findAllByAge(age: Int): Flux
94 | }
95 | ```
96 | This interface extends `R2dbcRepository`. This in turn extends `ReactiveCrudRepository` and then down to `Repository`. `ReactiveCrudRepository` provides the standard CRUD functions and from what I understand, `R2dbcRepository` does not provide any extra functions and is instead an interface created for better situational naming.
97 |
98 | `R2dbcRepository` takes in two generic parameters, one being the entity class that it takes as input and produces as output. The second being the type of the Primary Key. Therefore in this situation, the `Person` class is being managed by the `PersonRepository` (makes sense) and the Primary Key field inside `Person` is an `Int`.
99 |
100 | The return types of functions in this class and the ones provided by `ReactiveCrudRepository` are `Flux` and `Mono` (not seen here). These are Project Reactor types that Spring makes use of as the default Reactive Stream types. `Flux` represents a stream of multiple elements whereas a `Mono` is a single result.
101 |
102 | Finally, as I mentioned before the example, each function is annotated with `@Query`. The syntax is quite straight forward, with the SQL being a string inside the annotation. The `$1` (`$2`, `$3`, etc... for more inputs) represents the value input into the function. Once you have done this, Spring will handle the rest and pass the input(s) into their respective input parameter, gather the results and map it to the repository's designated entity class.
103 |
104 | ### A very quick look at the entity
105 |
106 | Not going to say much here but simply show the `Person` class used by the `PersonRepository`.
107 | ```kotlin
108 | @Table("people")
109 | data class Person(
110 | @Id val id: Int? = null,
111 | val name: String,
112 | val age: Int
113 | )
114 | ```
115 | Actually, there is one point to make here. `id` has been made nullable and provided a default value of `null` to allow Postgres to generate the next suitable value itself. If this is not nullable and an `id` value is provided, Spring will actually try to run an update instead of an insert upon saving. There are other ways around this, but I think this is good enough.
116 |
117 | This entity will map to the `people` table defined below:
118 | ```sql
119 | CREATE TABLE people (
120 | id SERIAL PRIMARY KEY,
121 | name VARCHAR NOT NULL,
122 | age INTEGER NOT NULL
123 | );
124 | ```
125 |
126 | ### Seeing it all in action
127 |
128 | Now let's have a look at it actually doing something. Below is some code that inserts a few records and retrieves them in a few different ways:
129 | ```kotlin
130 | @SpringBootApplication
131 | class Application : CommandLineRunner {
132 |
133 | @Autowired
134 | private lateinit var personRepository: PersonRepository
135 |
136 | override fun run(vararg args: String?) {
137 | personRepository.saveAll(
138 | listOf(
139 | Person(name = "Dan Newton", age = 25),
140 | Person(name = "Laura So", age = 23)
141 | )
142 | ).log().subscribe()
143 | personRepository.findAll().subscribe { log.info("findAll - $it") }
144 | personRepository.findAllById(Mono.just(1)).subscribe { log.info("findAllById - $it") }
145 | personRepository.findAllByName("Laura So").subscribe { log.info("findAllByName - $it") }
146 | personRepository.findAllByAge(25).subscribe { log.info("findAllByAge - $it") }
147 | }
148 | }
149 | ```
150 | One thing I will mention about this code. There is a very real possibility that it executes without actually inserting or reading some of the records. But, when you think about it. It makes sense. Reactive applications are meant to do things asynchronously and therefore this application has started processing the function calls in different threads. Without blocking the main thread, these asynchronous processes might never fully execute. For this reason, there are some `Thread.sleep` calls in this code, but I removed them from the example to keep everything tidy.
151 |
152 | The output for running the code above would look something like the below:
153 | ```
154 | 2019-02-11 09:04:52.294 INFO 13226 --- [ main] reactor.Flux.ConcatMap.1 : onSubscribe(FluxConcatMap.ConcatMapImmediate)
155 | 2019-02-11 09:04:52.295 INFO 13226 --- [ main] reactor.Flux.ConcatMap.1 : request(unbounded)
156 | 2019-02-11 09:04:52.572 INFO 13226 --- [actor-tcp-nio-1] reactor.Flux.ConcatMap.1 : onNext(Person(id=35, name=Dan Newton, age=25))
157 | 2019-02-11 09:04:52.591 INFO 13226 --- [actor-tcp-nio-1] reactor.Flux.ConcatMap.1 : onNext(Person(id=36, name=Laura So, age=23))
158 | 2019-02-11 09:04:52.591 INFO 13226 --- [actor-tcp-nio-1] reactor.Flux.ConcatMap.1 : onComplete()
159 | 2019-02-11 09:04:54.472 INFO 13226 --- [actor-tcp-nio-2] com.lankydanblog.tutorial.Application : findAll - Person(id=35, name=Dan Newton, age=25)
160 | 2019-02-11 09:04:54.473 INFO 13226 --- [actor-tcp-nio-2] com.lankydanblog.tutorial.Application : findAll - Person(id=36, name=Laura So, age=23)
161 | 2019-02-11 09:04:54.512 INFO 13226 --- [actor-tcp-nio-4] com.lankydanblog.tutorial.Application : findAllByName - Person(id=36, name=Laura So, age=23)
162 | 2019-02-11 09:04:54.524 INFO 13226 --- [actor-tcp-nio-5] com.lankydanblog.tutorial.Application : findAllByAge - Person(id=35, name=Dan Newton, age=25)
163 | ```
164 | A few things to take away here:
165 | - `onSubscribe` and `request` occur on the main thread where the `Flux` was called from. Only `saveAll` outputs this since it has included the `log` function. Adding this to the other calls would have lead to the same result of logging to the main thread.
166 | - The execution contained within the subscribe function and the internal steps of the `Flux` are ran on separate threads.
167 |
168 | This is not anywhere close to a real representation of how you would use Reactive Streams in an actual application but hopefully demonstrates how to use them and gives a bit of insight into how they execute.
169 |
170 | ### Conclusion
171 |
172 | In conclusion, Reactive Streams have come to some RDBMS databases thanks to the R2DBC driver and Spring Data that builds a layer on top to make everything a bit tidier. By using Spring Data R2DBC we are able to create a connection to a database and start querying it without the need of to much code. Although Spring is already doing a lot for us, it could be doing more. Currently, it does not have Spring Boot auto-configuration support. Which is a bit annoying. But, I am sure that someone will get around to doing it soon and make everything even better than it already is.
--------------------------------------------------------------------------------
/src/main/kotlin/com/lankydanblog/tutorial/Application.kt:
--------------------------------------------------------------------------------
1 | package com.lankydanblog.tutorial
2 |
3 | import com.lankydanblog.tutorial.person.Person
4 | import com.lankydanblog.tutorial.person.repository.PersonRepository
5 | import org.slf4j.LoggerFactory
6 | import org.springframework.beans.factory.annotation.Autowired
7 | import org.springframework.boot.CommandLineRunner
8 | import org.springframework.boot.autoconfigure.SpringBootApplication
9 | import org.springframework.boot.runApplication
10 | import reactor.core.publisher.Mono
11 |
12 | @SpringBootApplication
13 | class Application : CommandLineRunner {
14 |
15 | @Autowired
16 | private lateinit var personRepository: PersonRepository
17 |
18 | override fun run(vararg args: String?) {
19 | personRepository.saveAll(
20 | listOf(
21 | Person(name = "Dan Newton", age = 25),
22 | Person(name = "Laura So", age = 23)
23 | )
24 | ).log().subscribe()
25 | Thread.sleep(2000)
26 | personRepository.findAll().log().subscribe { log.info("findAll - $it") }
27 | personRepository.findAllById(Mono.just(1)).log().subscribe { log.info("findAllById - $it") }
28 | personRepository.findAllByName("Laura So").log().subscribe { log.info("findAllByName - $it") }
29 | personRepository.findAllByAge(25).log().subscribe { log.info("findAllByAge - $it") }
30 | Thread.sleep(5000)
31 | }
32 |
33 | private companion object {
34 | val log = LoggerFactory.getLogger(Application::class.java)
35 | }
36 | }
37 |
38 | fun main(args: Array) {
39 | runApplication(*args)
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/lankydanblog/tutorial/DatabaseConfiguration.kt:
--------------------------------------------------------------------------------
1 | package com.lankydanblog.tutorial
2 |
3 | import io.r2dbc.postgresql.PostgresqlConnectionConfiguration
4 | import io.r2dbc.postgresql.PostgresqlConnectionFactory
5 | import io.r2dbc.spi.ConnectionFactory
6 | import org.springframework.beans.factory.annotation.Value
7 | import org.springframework.context.annotation.Configuration
8 | import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration
9 | import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories
10 |
11 | @Configuration
12 | @EnableR2dbcRepositories
13 | class DatabaseConfiguration(
14 | @Value("\${spring.data.postgres.host}") private val host: String,
15 | @Value("\${spring.data.postgres.port}") private val port: Int,
16 | @Value("\${spring.data.postgres.database}") private val database: String,
17 | @Value("\${spring.data.postgres.username}") private val username: String,
18 | @Value("\${spring.data.postgres.password}") private val password: String
19 | ) : AbstractR2dbcConfiguration() {
20 |
21 | override fun connectionFactory(): ConnectionFactory {
22 | return PostgresqlConnectionFactory(
23 | PostgresqlConnectionConfiguration.builder()
24 | .host(host)
25 | .port(port)
26 | .database(database)
27 | .username(username)
28 | .password(password).build()
29 | )
30 | }
31 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/lankydanblog/tutorial/person/Person.kt:
--------------------------------------------------------------------------------
1 | package com.lankydanblog.tutorial.person
2 |
3 | import org.springframework.data.annotation.Id
4 | import org.springframework.data.relational.core.mapping.Table
5 |
6 | @Table("people")
7 | data class Person(
8 | @Id val id: Int? = null,
9 | val name: String,
10 | val age: Int
11 | )
--------------------------------------------------------------------------------
/src/main/kotlin/com/lankydanblog/tutorial/person/repository/PersonRepository.kt:
--------------------------------------------------------------------------------
1 | package com.lankydanblog.tutorial.person.repository
2 |
3 | import com.lankydanblog.tutorial.person.Person
4 | import org.springframework.data.r2dbc.repository.R2dbcRepository
5 | import org.springframework.data.r2dbc.repository.query.Query
6 | import org.springframework.stereotype.Repository
7 | import reactor.core.publisher.Flux
8 |
9 | // need to define query "query derivation not yet supported"
10 | @Repository
11 | interface PersonRepository : R2dbcRepository {
12 |
13 | @Query("SELECT * FROM people WHERE name = $1")
14 | fun findAllByName(name: String): Flux
15 |
16 | @Query("SELECT * FROM people WHERE age = $1")
17 | fun findAllByAge(age: Int): Flux
18 | }
--------------------------------------------------------------------------------
/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.data.postgres.host=localhost
2 | spring.data.postgres.database=mytestdb
3 | spring.data.postgres.port=5432
4 | spring.data.postgres.username=admin
5 | spring.data.postgres.password=admin
6 |
7 | # create table people (id serial PRIMARY KEY, name varchar not null, age integer not null);
8 | # docker run -d --name postgres -p 5432:5432 -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=admin -e POSTGRES_DB=mytestdb postgres
--------------------------------------------------------------------------------