R2DBC Revealed: Reactive Relational Database Connectivity for Java and JVM Programmers 1st Edition Robert Hedgpeth download
R2DBC Revealed: Reactive Relational Database Connectivity for Java and JVM Programmers 1st Edition Robert Hedgpeth download
https://textbookfull.com/product/r2dbc-revealed-reactive-
relational-database-connectivity-for-java-and-jvm-
programmers-1st-edition-robert-hedgpeth/
https://textbookfull.com/product/java-8-pocket-guide-instant-
help-for-java-programmers-1st-edition-liguori-robert-liguori-
patricia/
https://textbookfull.com/product/computer-graphics-for-java-
programmers-3rd-edition-leen-ammeraal/
https://textbookfull.com/product/java-image-processing-recipes-
with-opencv-and-jvm-modrzyk/
https://textbookfull.com/product/java-image-processing-recipes-
with-opencv-and-jvm-1st-edition-nicolas-modrzyk/
Java 9 Revealed: For Early Adoption and Migration 1st
Edition Kishori Sharan (Auth.)
https://textbookfull.com/product/java-9-revealed-for-early-
adoption-and-migration-1st-edition-kishori-sharan-auth/
https://textbookfull.com/product/java-9-modularity-revealed-
project-jigsaw-and-scalable-java-applications-alexandru-jecan/
https://textbookfull.com/product/vert-x-in-action-asynchronous-
and-reactive-java-1st-edition-julien-ponge/
https://textbookfull.com/product/pro-sql-server-relational-
database-design-and-implementation-5th-edition-louis-davidson/
https://textbookfull.com/product/pro-sql-server-relational-
database-design-and-implementation-sixth-edition-louis-davidson/
R2DBC
Revealed
Reactive Relational Database Connectivity
for Java and JVM Programmers
—
Robert Hedgpeth
R2DBC Revealed
Reactive Relational Database
Connectivity for Java and JVM
Programmers
Robert Hedgpeth
R2DBC Revealed: Reactive Relational Database Connectivity for Java and JVM
Programmers
Robert Hedgpeth
Chicago, IL, USA
Introduction����������������������������������������������������������������������������������������������������������xxiii
v
Table of Contents
R2DBC Implementations������������������������������������������������������������������������������������������������������������� 20
Embracing Reactive Programming���������������������������������������������������������������������������������������� 21
Enabling Vendor Creativity����������������������������������������������������������������������������������������������������� 22
Enforcing Compliance����������������������������������������������������������������������������������������������������������� 22
Reactive Streams������������������������������������������������������������������������������������������������������������������������ 22
Another Specification������������������������������������������������������������������������������������������������������������ 23
API Fundamentals������������������������������������������������������������������������������������������������������������������ 23
Processors����������������������������������������������������������������������������������������������������������������������������� 25
JVM Interfaces����������������������������������������������������������������������������������������������������������������������� 26
Implementations�������������������������������������������������������������������������������������������������������������������� 27
Summary������������������������������������������������������������������������������������������������������������������������������������ 27
Chapter 4: Connections������������������������������������������������������������������������������������������ 41
Establishing Connections������������������������������������������������������������������������������������������������������������ 41
The Anatomy�������������������������������������������������������������������������������������������������������������������������� 42
R2DBC Hindsight������������������������������������������������������������������������������������������������������������������� 43
Connection Factory��������������������������������������������������������������������������������������������������������������������� 45
Driver Implementations��������������������������������������������������������������������������������������������������������� 45
Exposing Metadata���������������������������������������������������������������������������������������������������������������� 46
vi
Table of Contents
ConnectionFactories������������������������������������������������������������������������������������������������������������������� 47
Discovery������������������������������������������������������������������������������������������������������������������������������� 47
Bringing It All Together���������������������������������������������������������������������������������������������������������� 48
Connections�������������������������������������������������������������������������������������������������������������������������������� 48
Obtaining Connections���������������������������������������������������������������������������������������������������������� 51
Acquiring Metadata��������������������������������������������������������������������������������������������������������������� 51
Validating Connections���������������������������������������������������������������������������������������������������������� 51
Closing Connections�������������������������������������������������������������������������������������������������������������� 52
Summary������������������������������������������������������������������������������������������������������������������������������������ 52
Chapter 5: Transactions������������������������������������������������������������������������������������������ 53
Transaction Fundamentals���������������������������������������������������������������������������������������������������������� 53
The Need for Transactions����������������������������������������������������������������������������������������������������� 54
ACID Compliance������������������������������������������������������������������������������������������������������������������� 55
Methods of Control���������������������������������������������������������������������������������������������������������������� 56
R2DBC Transaction Management������������������������������������������������������������������������������������������������ 58
Auto-commit Mode���������������������������������������������������������������������������������������������������������������� 58
Explicit Transactions�������������������������������������������������������������������������������������������������������������� 59
Managing Savepoints������������������������������������������������������������������������������������������������������������ 60
Releasing Savepoints������������������������������������������������������������������������������������������������������������ 62
Isolation Levels��������������������������������������������������������������������������������������������������������������������������� 62
Managing Isolation���������������������������������������������������������������������������������������������������������������� 62
Performance Considerations������������������������������������������������������������������������������������������������� 63
Summary������������������������������������������������������������������������������������������������������������������������������������ 64
Chapter 6: Statements�������������������������������������������������������������������������������������������� 65
SQL Statements�������������������������������������������������������������������������������������������������������������������������� 65
R2DBC Statements���������������������������������������������������������������������������������������������������������������������� 66
The Basics����������������������������������������������������������������������������������������������������������������������������� 67
Dynamic Input����������������������������������������������������������������������������������������������������������������������� 68
Auto-generated Values���������������������������������������������������������������������������������������������������������������� 72
Performance Hints���������������������������������������������������������������������������������������������������������������������� 72
Summary������������������������������������������������������������������������������������������������������������������������������������ 73
vii
Table of Contents
viii
Table of Contents
ix
Table of Contents
x
Table of Contents
xi
Table of Contents
Chapter 16: Practical Applications with Spring Data and R2DBC������������������������ 185
Introduction to Spring��������������������������������������������������������������������������������������������������������������� 185
Spring Boot�������������������������������������������������������������������������������������������������������������������������� 186
Spring Data�������������������������������������������������������������������������������������������������������������������������� 187
Spring Data R2DBC�������������������������������������������������������������������������������������������������������������� 187
Getting Started�������������������������������������������������������������������������������������������������������������������������� 189
Spring Initializr�������������������������������������������������������������������������������������������������������������������� 189
Configuring Connections����������������������������������������������������������������������������������������������������� 194
Spring Data Repositories����������������������������������������������������������������������������������������������������� 195
Bringing It All Together�������������������������������������������������������������������������������������������������������� 199
Testing It Out����������������������������������������������������������������������������������������������������������������������������� 204
Build and Run the Project���������������������������������������������������������������������������������������������������� 204
Call an Endpoint������������������������������������������������������������������������������������������������������������������ 205
Show Me the Code�������������������������������������������������������������������������������������������������������������������� 205
Summary���������������������������������������������������������������������������������������������������������������������������������� 205
Index��������������������������������������������������������������������������������������������������������������������� 207
xii
About the Author
Robert Hedgpeth is a professional software engineer,
speaker, and developer relations enthusiast residing in the
bustling metropolis of Chicago, Illinois. Rob has more than
15 years of professional development experience, primarily
in the application development space. Throughout the years,
he has contributed to the architecture and development
of many solutions, using a large array of languages and
technologies. Now, as a developer advocate and evangelist,
Rob gets to combine his love for technology with his mission
to fuel developers' curiosity and passion. Follow him on
Twitter: @probablyrealrob.
xiii
About the Technical Reviewer
Brian Molt is a software developer at a manufacturing
company in Nebraska where he has been for 17 years.
During his time there, he has programmed with multiple
languages on a variety of platforms, including RPGLE on
an AS/400, web development with ASP.NET, and desktop
application development with JavaFX, and now he creates
REST services using JAX-RS.
xv
Acknowledgments
I’m not going to lie. Writing my first book has been an incredibly daunting and
challenging task. I spent many long nights, early mornings, and weekends researching,
writing, researching some more, and rewriting. But absolutely none of it would have
been possible without the help from some amazing people.
First, I’d like to thank the Apress team, as this book wouldn’t have been possible
without the opportunity provided by Jonathan Gennick, Jill Balzano, Laura Berendson,
and the rest of the amazing folks at Apress. A special thank you, Brian Molt, for not only
providing technical expertise but also the insight of a teammate who was truly invested
in the success of this book.
Next, I’d like to thank Mark Paluch, the spec lead for the R2DBC specification. You
were incredibly helpful and encouraging throughout the whole process and provided
extremely thorough feedback for all of my questions.
And last, and most importantly, I’d like to thank my wonderful wife, Tracy. Writing
a book isn’t easy. Writing a book during a global pandemic and as first-time parents
is a whole other level. Absolutely none of this would have been possible without your
support, encouragement, and patience.
xvii
The World at Scale
One of the few stable things in information technology is constant change.
Software, once written as machine code, then by using compilers, went (and still
goes) through various paradigm changes: procedural, data driven, object oriented,
functional. There have been many more programming models, and others will follow.
Patterns come and go as we speak. All this is driven by purpose, capabilities of our
runtime environments, constraints, and business requirements.
In a similar way, the way how we consume software services has changed many
times. Back in the 1990s, software was primarily installed locally and sometimes backed
by a server. Think of your good old desktop computer. The 2000s are characterized by
online services. More and more services became available through the Internet, all
hosted in their own data centers. Businesses began investigating web applications to
avoid installing software on each machine. Data centers grew.
The 2010s finally set the stage for software-backed services to run in the cloud. Many
online services were founded these years. It’s the golden digital age. Businesses driven
by software can simply scale by adding another batch of machines to their data center to
serve more customers, or in their cloud.
Scalability is only constrained by the remaining capacity in a data center, the
investment in servers, and the operational cost for computer systems. Scaling a business
comes with many challenges. One of them is efficiency. Efficiency becomes an important
metric to measure how well a system is utilized compared to its cost.
But what impacts the efficiency and scalability of an application?
To answer this question, we have to get to the bottom of an application and its
programming language. Are you ready to dig through the physiology of applications?
Ready? Go!
All applications have in common that they require computation power and memory
to fulfill their work. How many concurrent requests/users/processes/<insert your
measurement unit here> a single machine can handle depends primarily on CPU and
memory demand. It also depends on “how” CPU and memory are used with a strong tie
to the duration in which resources get occupied.
xix
The World at Scale
xx
The World at Scale
Over time, the number of reactive database clients grew, but all of these were
targeting NoSQL data stores: MongoDB, Redis, Cassandra, and Couchbase. However,
large parts of data are still hosted in SQL databases.
The standard way to access SQL databases on the JVM is JDBC. JDBC uses a blocking
API model which renders JDBC unusable for reactive programming.
The growing adoption of reactive programming raised continuously the question
of how to integrate with SQL databases in general and how to use existing libraries to
run queries and map objects in particular. Using JDBC on a ThreadPool may help for
small-scale applications. ThreadPools however do not turn blocking behavior into non-
blocking – the blocking problem is just put somewhere else instead of solving it.
Facing demand from reactive application developers, without an existing
standardized API, a small group of developers formed to investigate how reactive
applications could be integrated with SQL databases. And that was the inception
of R2DBC in 2017, an open standard to let the world run at scale using reactive
programming with SQL databases.
xxi
Introduction
I think it goes without saying that software users' expectations have never been higher.
With the standards of performance and usability continually rising, we developers have
been challenged to innovate like never before. Reactive programming has provided us an
avenue toward such innovation.
However, for far too long, we weren't able to achieve fully reactive solutions within
the Java ecosystem. We've been limited to trying to work around the blocking nature of
the Java Database Connectivity (JDBC) Application Programming Interface (API) within
our reactive solutions. But along came the Reactive Relational Database Connectivity
(R2DBC) specification, and suddenly the doors to developing fully reactive applications
flung open.
Starting by gaining a solid understanding of reactive programming and what it
means to use declarative programming techniques, we’ll lay the foundation for not only
what it is and how it works but why it’s so important.
Diving into the specification, you’ll learn how a relatively small collection of
interfaces and classes makes it possible to create a lightweight driver implementation
that, utilizing the power of the Reactive Streams API, completely unblocks your
applications’ interactions to underlying relational data storage solutions.
So, whether you’ve been creating reactive applications for years or at this very
moment are like “What the heck is reactive programming?”, my hope is that by the time
you’ve finished this book, you will have not only a solid understanding of the R2DBC
specification but also the confidence, provided in part by practical solution code and
samples, to start creating your own solutions using R2DBC.
xxiii
PART I
A Traditional Approach
Introducing new technologies can be challenging, but I’ve found that it can help to
identify a common, real-world use case that we, as developers, have encountered and
see how it fits within that context.
Imagine a basic solution that contains web request workflow between a client
application and a server application, and let’s start at the point where there’s an
asynchronous request initiated from the client to the server.
3
© Robert Hedgpeth 2021
R. Hedgpeth, R2DBC Revealed, https://doi.org/10.1007/978-1-4842-6989-3_1
Chapter 1 The Case for Reactive Programming
Upon receiving the request, the server spins up a new thread for processing
(Figure 1-1).
Request
Response
Figure 1-1. Executing a simple, synchronous web request from a client to server
Simple enough, and it runs, so ship it, right? Not so fast! Rarely is it the case that
requests are that simple. It could be the case, like in Figure 1-2, that the server thread
needs to access a database to complete the work requested by the client. However, while
the database is being accessed, the server thread waits, blocking more work from being
performed until a response is returned by the database.
4
Chapter 1 The Case for Reactive Programming
Request
Query
Result
Response
Figure 1-2. The server thread is blocked from performing work while the database
returns a response
Unfortunately, that’s probably not an optimal solution as there’s no way to know how
long the database call will take. That’s not likely to scale well. So, in an effort to optimize
the client’s time and keep it working, you could add more threads to process multiple
requests in parallel, like in Figure 1-3.
5
Chapter 1 The Case for Reactive Programming
Request 1
Query
Request 2
Response 2
Result
Response 1
Figure 1-3. Subsequent incoming requests are processed using additional threads
Now we’re cooking! You can just continue to add threads to handle additional
processing, right? Not so fast. As with most things in life, if something seems too good to
be true, it probably is. The trade-off for adding additional threads is pesky problems like
higher resource consumption, possibly resulting in decreased throughput, and, in many
cases, increased complexity for developers due to thread context management.
Note For many applications, using multiple threads will work as a viable solution.
Reactive programming is not a silver bullet. However, reactive solutions can help
utilize resources more efficiently. Read on to learn how!
6
Chapter 1 The Case for Reactive Programming
Declarative programming, on the other hand, does not focus on how to accomplish a
specific goal but rather the goal itself. But that’s fairly vague, so let’s back up a bit.
Consider the following analogies:
Tip Both imperative and declarative programming paradigms have strengths and
weaknesses. Like with any task, make sure you choose the right tool for the job!
For this book, I’m going to be using the Java programming languages for all the
examples. Now, it’s no secret that Java is an imperative language, and as such its focus
is on how to achieve the final result. That said, it’s easy for us to imagine how to write
imperative instructions using Java, but what you may not know is that you can also write
declarative flows. For instance, consider the following.
Here’s an imperative approach to summing a range of numbers, step-by-step, from
one to ten:
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
System.out.println(sum); // 55
7
Chapter 1 The Case for Reactive Programming
However, for the time being, it’s not important that you understand a Stream object
or the underlying IntStream specialization. No, for now, set the idea of a “stream” to the
side; we’ll get back to it.
The real takeaway here is that both approaches yield the same results, but the
declarative approach is merely setting an expectation for the result of an operation, not
dictating the underlying implementation steps. This is fundamentally, from a high level,
how reactive programming works. Still a little hazy? Let’s dive deeper.
Thinking Reactively
As I mentioned previously, reactive programming, at its core, is declarative. It aims
to circumvent blocking states by eliminating many of the issues caused by having to
maintain numerous threads. Ultimately, this is accomplished by managing expectations
between the client and server.
In fact, pursuing a more reactive approach, upon receiving a request from the client,
the server thread calls on the database for processing, but does not wait for a response.
This frees up the server thread to continue processing incoming requests. Then, at an
undetermined amount of time later, a response, in the form of an event, is received and
reacted to by the server thread from the database.
8
Chapter 1 The Case for Reactive Programming
Request 1
Query
Request 2
Response
Result
Response
Figure 1-4. The client does not wait for a direct response from the server
The non-blocking and event-driven behaviors displayed in Figure 1-4 are the
foundation which reactive programming is built on.
9
Chapter 1 The Case for Reactive Programming
Reactive Systems
The Reactive Manifesto was created to clearly define four objectives of reactive systems,
cited verbatim in the following:
10
Chapter 1 The Case for Reactive Programming
11
Another Random Document on
Scribd Without Any Related Topics
GENUINE IRISH LINENS AND LAWNS.
Where purchases are made by Gentlemen, or other Persons, for
Friends in the country, which fail to give satisfaction, the money is
invariably returned, excepting where an article is lessened in value,
by being separated from the piece.
HENRY GROVE,
(IMPORTER OF WINES AND SPIRITS,)
The airy situation of the above Inn, and its proximity to the Grand
Junction and London and Birmingham Railway Companies’ Offices,
render it most eligible for Commercial Gentlemen and others, and
will be found to possess the two important requisites of Comfort and
Economy combined.
T. J. MORRIS,
REPOSITORY OF ARTS,
COLMORE ROW, BIRMINGHAM,
MANUFACTURER OF
R. SIMS,
(TEN YEARS ASSISTANT TO MR. ENGLISH, COLMORE ROW,)
SURGEON DENTIST,
NO. 13,
UNION PASSAGE, NEW-STREET,
BIRMINGHAM,
Returns his sincere acknowledgments to the Inhabitants of
Birmingham and its vicinity, for the liberal support that has been
conferred upon him since his commencing Practice, and trusts that
his having had Ten Years’ experience with Mr. English, during which
he had nearly the whole of the Mechanical Department entrusted to
his care, will still entitle him to that support and patronage which
has hitherto been awarded to him.
In consequence of some unskilful pretenders having put themselves
forward to public notice as adepts in the above art, he thinks it
necessary to state that he never ties in teeth, which is the most that
these pretenders can ever accomplish; his superior Gold Plates never
in any instance require the painful and most injurious operation of
tying in; and he assures them they will wear more years than the
spurious bone teeth, which they put forth to the public, will last
months, at a less charge, and with greater comfort to the wearer.
FEES.
£ s. d. £ s. d.
A Single Tooth 0 10 0 usually charged 1 1 0
A Complete Set 10 0 0 usually charged 20 0 0
S. WALKER,
Military Percussion Cap Maker to Her Majesty’s
Honourable Board of Ordnance,
Begs most respectfully to inform her numerous Friends, and the
Public generally, that she has dissolved Partnership with her Son,
and that she will continue to carry on the Percussion Cap Business in
all its Branches.
S. WALKER’S Caps have been known and approved of by the
Sporting World for more than sixteen Years, and she can with
confidence assure them every exertion shall be made, this
seventeenth Season, to render them still superior to any yet
manufactured.
Sold in Boxes of 250 and 500 each, by most of the respectable Gun-
makers and Gunpowder Dealers throughout the Kingdom.
CHEMICALLY PREPARED GUN WADDING,
ABRAHAM ALLPORT,
WOOLLEN DRAPER, TAILOR, &c.
2, COLMORE ROW, BIRMINGHAM.
N.B. Sole Agents for the Whiston Copper Company. (Messrs. Sneyd,
Kinnersley & Co.)
HATS.
75, HIGH-STREET.
GOOD
FASHIONABLE GOSSAMERS
At 4s. 9d. to 10s.;
SUPERFINE SHORT-NAP STUFFS,
Best that can be made, 21s.;
TO BE HAD AT
WALKER’S
CHEAP HAT DEPÔT.
Also a large assortment of Fashionable CAPS and GRASS HATS for
Summer wear.
JAMES GRUNDY,
MANUFACTURER OF
JOHN GODFREY,
WORKING OPTICIAN, SILVERSMITH. &c.
NO. 93, COLESHILL-STREET,
CAPTAIN HOSKINS,
IMPORTER OF
TEETH.
MR. E. JONES,
DENTIST,
NO. 9, EASY ROW, BIRMINGHAM,
Six Years Assistant with Mr. Andrew Clark, of Brook-street,
Bond-street, London,
Begs to say he will continue to supply ARTIFICIAL TEETH upon the
same principle as Mr. A. Clark, and the only one that will ensure
ease, articulation, and mastication.
E. G., having undertaken several cases that had been refused by
other Dentists as impracticable, can give the most satisfactory
References as to the beneficial results of his Practice.
EVERY OPERATION IN
DENTAL SURGERY,
Performed on the most moderate Terms.
RICHARD FARMER,
Manufacturer,
With the greatest deference submits to the attention of his Friends
and the Public the subjoined Documents, as flattering Testimonies of
the high estimation in which the above very superior and much
approved Articles are held:—
From Sir John Conroy, Secretary to Her Royal Highness
The Duchess of Kent.
“Sir John Conroy is honoured with the Duchess of Kent’s
command to acquaint Mr. Farmer, that he has permission to use
Her Royal Highness’s Name and Arms, as Manufacturer of
Permanent Elastic Spring Hygeian Beds to Her Royal Highness.
“Malvern, Sept. 13, 1830.”
“Sir John Conroy is to acknowledge the receipt of the Bed and
Mattress of Mr. R. Farmer’s invention, which he has made for the
Princess Victoria; and Sir John is commanded by the Duchess of
Kent to express Her Royal Highness’s highest approval of the
principle of his Mattresses, Cushions, &c.
“Kensington Palace, Dec. 17, 1830.
“Mr. Richard Farmer, &c. &c.”
MANUFACTURERS OF
W. FLETCHER,
MANUFACTURER OF
LAMPS, CANDLESTICKS,
LUSTRES, INKSTANDS, VASES,
And all kinds of Ornaments in Bronze and Or-molu,
31,
LOVEDAY-STREET, BIRMINGHAM.
JUST PUBLISHED,
DRAKE’S
RAILROAD MAPS
OF THE ENTIRE LINE OF ROUTE
FROM
LONDON TO LIVERPOOL AND
MANCHESTER,
BEAUTIFULLY ENGRAVED AND COLOURED,
AND EXTENDING MANY MILES ON EACH SIDE OF THE LINE:
PRINTING OFFICE,
LAW STATIONERY, ACCOUNT BOOK,
AND PAPER WAREHOUSE,
52,
NEW-STREET, (OPPOSITE THE THEATRE,)
BIRMINGHAM.
JAMES DRAKE,
LAW BOOKSELLER, STATIONER, AND BINDER,
Takes this opportunity of presenting his grateful acknowledgments to
the Profession for their liberal support of his Establishment, and at
the same time he begs to assure them, that every article sold by him
will be found of superior quality and at reasonable prices, and will,
he hopes, induce a continuance of their esteemed favours.
J. D. takes this opportunity of calling the attention of the Profession
to his Law Stationery Business, established more than twenty years,
and which is conducted by himself and competent assistants.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com