Learn Microservices with Spring Boot: A Practical Approach to RESTful Services using RabbitMQ, Eureka, Ribbon, Zuul and Cucumber 1st Edition Moises Macero (Auth.) - The full ebook with all chapters is available for download
Learn Microservices with Spring Boot: A Practical Approach to RESTful Services using RabbitMQ, Eureka, Ribbon, Zuul and Cucumber 1st Edition Moises Macero (Auth.) - The full ebook with all chapters is available for download
com
OR CLICK HERE
DOWLOAD EBOOK
https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-loucas/
textbookfull.com
https://textbookfull.com/product/learn-microservices-with-spring-boot-
second-edition-moises-macero-garcia-macero-garcia-moises/
textbookfull.com
Moises Macero
Learn Microservices with Spring Boot: A Practical Approach to
RESTful Services using RabbitMQ, Eureka, Ribbon, Zuul and Cucumber
Moises Macero
New York, USA
Chapter 1: Introduction������������������������������������������������������������������������1
Setting the Scene��������������������������������������������������������������������������������������������������1
Who Are You?��������������������������������������������������������������������������������������������������������2
How Is This Book Different from Other Books and Guides?����������������������������������3
Reasoning Behind the Techniques������������������������������������������������������������������3
Learning: An Incremental Process�������������������������������������������������������������������4
Is This a Guide or a Book?�������������������������������������������������������������������������������4
Contents����������������������������������������������������������������������������������������������������������������5
From the Basics to Advanced Topics���������������������������������������������������������������5
Skeleton with Spring Boot, the Professional Way��������������������������������������������5
Test-Driven Development��������������������������������������������������������������������������������6
Connecting Microservices�������������������������������������������������������������������������������6
Event-Driven System���������������������������������������������������������������������������������������6
End-to-End Testing������������������������������������������������������������������������������������������7
Summary��������������������������������������������������������������������������������������������������������������7
iii
Table of Contents
iv
Table of Contents
v
Table of Contents
vi
Table of Contents
Hands-On Code�������������������������������������������������������������������������������������������������218
Implementing the API Gateway with Zuul����������������������������������������������������218
Playing with Service Discovery�������������������������������������������������������������������237
Are Our Microservices Ready to Scale?������������������������������������������������������241
Load Balancing with Ribbon������������������������������������������������������������������������244
Circuit Breakers and REST Clients��������������������������������������������������������������������254
Circuit Breakers with Hystrix�����������������������������������������������������������������������254
Hystrix and Zuul�������������������������������������������������������������������������������������������255
Hystrix from a REST Client���������������������������������������������������������������������������258
REST Consumers with Feign�����������������������������������������������������������������������261
Microservices Patterns and PaaS���������������������������������������������������������������������263
Summary����������������������������������������������������������������������������������������������������������264
vii
Table of Contents
Afterword������������������������������������������������������������������������������������������323
Index�������������������������������������������������������������������������������������������������325
viii
About the Author
Moises Macero has been a software developer
since he was a kid. He has worked at big
companies and also at startups, where being
a full-stack developer was essential. During
his career, Moises has most often worked in
development, design, and architecture, for
small and large projects, and in both Agile and
waterfall environments. He likes working in
teams where he can not only coach others but
also learn from them.
Moises is also the author of the blog
thepracticaldeveloper.com, where he shares with others solutions for
technical challenges, guides and his view on ways of working in IT
companies. In his free time, he enjoys traveling and hiking.
You can follow Moisés on his twitter account @moises_macero.
ix
About the Technical Reviewer
Manuel Jordan Elera is an autodidactic
developer and researcher who enjoys learning
new technologies for his own experiments,
which focus on finding new ways to integrate
them.
Manuel won the 2010 Springy Award –
Community Champion and Spring Champion
2013. In his little free time, he reads the Bible
and composes music on his bass and guitar.
Manuel believes that constant education
and training is essential for all developers. You can reach him mostly
through his twitter account @dr_pompeii.
xi
CHAPTER 1
Introduction
S
etting the Scene
Microservices are getting very popular these days. It’s not a surprise; this
software architecture style has a lot of advantages, like flexibility and ease
of scale. Mapping them into small teams in an organization also gives you
a lot of efficiency in development. However, going on the adventure of
microservices knowing only the benefits is a wrong call: you need to know
what you are facing and be prepared for that in advance. You can get a lot
of knowledge from many books and articles on the Internet but, when you
get hands-on code, the story changes.
This book covers some of the most important concepts of microservices
in a practical way, but not without explaining the concepts. First, we define
a use case: an application to build. Then we start with a small monolith,
based on some sound reasoning. Once we have the minimal application in
place, we evaluate if it’s worthy to move to microservices, and what would
be a good way to do so. How should we communicate these different pieces?
Then we can describe and introduce the event-driven architecture pattern
to reach loose coupling by informing other parts of the system about what
happened in your part of the process, instead of explicitly calling others to
action. Once you have the microservices in place, you see in practice how
the surrounding tools work: service discovery, routing, etc. We don’t cover all
of them at once but include them one by one, explaining the benefits of each
for the application. Also, we analyze what would be a good way to test the
distributed system, end-to-end.
1
Don Quixote. Even though it is a long book, it is still a masterpiece.
2
Chapter 1 Introduction
3
Chapter 1 Introduction
This book uses that philosophy: it navigates through the code and
design patterns, explaining the reasons to follow one way and not others.
4
Chapter 1 Introduction
In any case, to keep it simple, from here onward we call this a book.
C
ontents
From the Basics to Advanced Topics
This book focuses first on some basics about how to design and implement
a production-ready Spring Boot application using well-known architecture
patterns (Chapters 2 and 3). From there, it takes you through the journey
of tools and frameworks related to microservices with the introduction of
a second piece of functionality in a different Spring Boot app (Chapters 4
and 5). It also shows you how to support such a distributed system with
end-to-end integration tests (Chapter 6).
If you already know how to design Spring Boot applications, you can
go quickly through Chapters 2 and 3 and focus more on the second part
of the book. There, we cover topics like service discovery, routing, event-
driven design, testing with Cucumber, etc. However, pay attention to the
strategy we set up in the first part—test-driven development, the focus on
the minimum viable product (MVP), and monolith-first.
5
Chapter 1 Introduction
Test-Driven Development
We use TDD to map the prerequisites presented to technical features (like
you should do in real life). TDD is a technique that sometimes can’t be
used at work (for many different reasons, none technical). But this book
tries to show it in a way that you can see the benefits from the beginning:
why it’s always a good idea to think about the test cases before writing your
code. AssertJ and Mockito will serve us to build useful tests efficiently.
The plan is the following: you’ll learn how to create the tests first, then
make them fail, and finally implement the logic to make them work.
Connecting Microservices
Once you have your first application ready, we introduce a second one
that will interact with the existing functionality. From that moment on,
you’ll have a microservices architecture. It doesn’t make any sense to try to
understand the advantages of microservices if you only have one of them.
The real-life scenarios are always distributed systems with functionality
split into different services. As usual, to keep it practical, you’ll see how
moving to microservices fits your needs.
The book covers not only the reasons to split the system but also what
the disadvantages are that come with that choice. And once you make the
decision, you’ll learn which tools you should use to make the system work
as a whole, and not as isolated services: service discovery, API gateway,
load balancing, and some other supporting tools.
Event-Driven System
An additional concept that does not always accompany microservices is an
event-driven architecture. This book uses it since it’s a pattern that fits very
well into a microservice architecture, and you’ll make your choice based
on good examples.
6
Chapter 1 Introduction
End-to-End Testing
If you want to code your project the professional way, you need to have a
production-ready mindset, so we’ll cover this functionality with tests. We
explain how to tackle the trickiest ones in a microservices architecture:
the end-to-end tests. We’ll use Cucumber since it’s a framework that
fits perfectly in many projects, filling the gap between the business
requirements and the test development. Even though nobody should need
reasons here to be convinced of why it is a good idea to have a proper test
base, we explain them to keep the testing skeptics happy.
Summary
This chapter introduced the main goals of this book: to teach you the
main aspects of a microservices architecture, by starting simple and then
growing your knowledge through the development of a sample project.
We also covered briefly the main contents of the book: from monolith-
first to microservices with Spring Boot, Test-Driven Development,
Event-Driven Systems and End-to-End testing with Cucumber.
Next chapter will start with the first step of our learning path: a basic
Spring Boot application.
7
CHAPTER 2
USER STORY 1
To make this work, we’ll split the user story into several sub-tasks:
10
Chapter 2 The Basic Spring Boot Application
C
reating the Skeleton
Hands-on code! The first thing you do is create a Spring Boot application
skeleton that will serve as the reference during the book. There are several
ways to do this. Navigate to the Spring Initializr web site at http://start.
spring.io/ and generate a project from there (see Figure 2-1).
11
Chapter 2 The Basic Spring Boot Application
Figure 2-1. The Spring Initializr web site helps you create a basic
application
12
Chapter 2 The Basic Spring Boot Application
including a Maven wrapper (mvnw) that you can execute from the source
folder. If you prefer, you can use your own Maven installation instead.
Now you can use your favorite shell to run the application with this
command:
$ mvnw spring-boot:run
Your application will start. The last line you should see there is
something like this:
m.book.SocialMultiplicationApplication : Started
SocialMultiplicationApplication in 2.385 seconds
(JVM running for 6.07)
This app, as you might have guessed, is not practical yet. There is
no functionality in there, even though it’s occupying a port at 8080. But
it’s useful to generate the skeleton project this way, having the Maven
configuration in place and the root packages.
From here onward, it will be assumed that you know how to run the Spring
Boot application. It’s also recommended that you use your preferred IDE to
work with the code or import the Maven projects (Eclipse, IntelliJ, Spring Tool
Suite, etc.). The most popular IDEs have good integration with Spring Boot and
Maven and allow you to run it directly without typing anything in the command
line. If you need more help with this, just visit the official guides for these
integrated development environments.
13
Chapter 2 The Basic Spring Boot Application
There are many reasons why, but the most important one is that TDD forces
you and the business person to think about the prerequisites in a deeper way.
This includes thinking about what the code should do under certain situations
or use cases. It will help you clarify vague prerequisites and reject invalid ones.
However, there is one idea usually associated with TDD that sometimes is
taken to the extreme: continuous refactoring of code in several iterations.
You should find a balance—it’s not a good idea to write poor quality,
unmaintainable code just to make the tests pass and then later refactor them.
You can find the code in this chapter in the v1 repository on GitHub at
https://github.com/microservices-practical.
package microservices.book.multiplication.domain;
/**
* This class represents a Multiplication in our application.
*/
public class Multiplication {
14
Chapter 2 The Basic Spring Boot Application
@Override
public String toString() {
return "Multiplication{" +
"factorA=" + factorA +
", factorB=" + factorB +
", result(A*B)=" + result +
'}';
}
15
Chapter 2 The Basic Spring Boot Application
Simple. It’s a basic class, and it contains the result as well. There is no
need to calculate it all the time across the application.
We define also the service interface, as shown in Listing 2-2.
package microservices.book.multiplication.service;
import microservices.book.multiplication.domain.Multiplication;
/**
* Creates a Multiplication object with two randomly-
generated factors
* between 11 and 99.
*
* @return a Multiplication object with random factors
*/
Multiplication createRandomMultiplication();
package microservices.book.multiplication.service;
16
Chapter 2 The Basic Spring Boot Application
/**
* @return a randomly-generated factor. It's always a
number between 11 and 99.
*/
int generateRandomFactor();
Once you have the interfaces you need, you can write the first test
version, as shown in Listing 2-4.
package microservices.book.multiplication.service;
import microservices.book.multiplication.domain.Multiplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MultiplicationServiceTest {
@MockBean
private RandomGeneratorService randomGeneratorService;
@Autowired
private MultiplicationService multiplicationService;
17
Chapter 2 The Basic Spring Boot Application
@Test
public void createRandomMultiplicationTest() {
// given (our mocked Random Generator service will
return first 50, then 30)
given(randomGeneratorService.generateRandomFactor()).
willReturn(50, 30);
// when
Multiplication multiplication = multiplicationService.
createRandomMultiplication();
// then
assertThat(multiplication.getFactorA()).isEqualTo(50);
assertThat(multiplication.getFactorB()).isEqualTo(30);
assertThat(multiplication.getResult()).isEqualTo(1500);
}
}
18
Chapter 2 The Basic Spring Boot Application
package microservices.book.multiplication.service;
import microservices.book.multiplication.domain.Multiplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
class MultiplicationServiceImpl implements
MultiplicationService {
@Autowired
public MultiplicationServiceImpl(RandomGeneratorService
randomGeneratorService) {
this.randomGeneratorService = randomGeneratorService;
}
@Override
public Multiplication createRandomMultiplication() {
int factorA = randomGeneratorService.
generateRandomFactor();
int factorB = randomGeneratorService.
generateRandomFactor();
return new Multiplication(factorA, factorB);
}
}
19
Exploring the Variety of Random
Documents with Different Content
III.
*****
Tuli pian ilta ja pimeä. Emme voineet tehdä mitään sinä päivänä.
Totesimme vain, että olimme eheät. Ruokaa Chimbillä oli riittävästi
meille kaikille viidelle; ei siis hätää pariin vuorokauteen. Muista
emme välittäneet. Seuraavana aamuna päivän valjetessa aloimme
korjata rataa ja nostaa kiskoille kelvollisia vaunuja; rikkinäiset saivat
jäädä tien viereen. Veturi oli eheä. Kolmantena päivänä puolipäivän
aikaan saavuimme Limaan. Liman ja Callaon välinen rataosa oli
epäkunnossa. Jatkoimme siis tuon viidentoista virstan lopputaipaleen
jalkaisin. Seuraavana aamuna heräsimme mr. Michel Kellyn boarding-
housissa (matkustajakoti merimiehiä varten). Me neljä olimme
nukkuneet samassa huoneessa, mutta Chimb erikseen.
Michel Kelly oli yksi noita tavallisia verenimijöitä, joita siihen aikaan
tapasi — ja kukaties nytkin tapaa — kaikissa satamakaupungeissa.
Hänen ammattinansa oli nousta vasta saapuneeseen laivaan
houkuttelemaan miehistöä karkaamaan. Useimmiten joku tarttui
onkeen. Nämä poistuivat laivasta vähää ennen sen lähtöä ja
piilottelivat, kunnes laiva oli jättänyt sataman. Sitten boardingmaster
möi heidät toiseen, miehien puutteessa olevaan laivaan. Yhden tai
kahden kuukauden palkan boardingmaster nosti etukäteen, olipa
mies asunut hänen luonaan pitkän tai lyhyen ajan. Tuon karanneen
miesraukan ainoa korvaus oli pari perinpohjaista humalaa,
saippuatanko ja naulan verran tupakkaa. Mutta hänen harminsa oli
se, että oli menettänyt monen kuukauden, usein vuodenkin palkan.
Boardingmastereilla oli sitä paitsi juoksukoiria, runnareja, jotka
saivat eri suuruisen maksun jokaisesta taloon hankkimastaan
miehestä, riippuen tämän arvosta ja ulkonäöstä.
— Pidä suusi kiinni, Mack! Sinä, joka ennen olet ollut hyvä toveri
ja harvapuheinen, olet yht'äkkiä muuttunut hävyttömäksi ja
suurisuiseksi. Jollet nyt ole vaiti ja tottele meitä, niin jätämme sinut
tänne.
Lamppu, jota oli muutettu paikasta toiseen, sen mukaan kuin sitä
paraiten tarvittiin, putosi lavitsalta lattialle. Onneksi se sammui eikä
särkynyt sytyttäen tulipaloa. Tulitikkumme eivät syttyneet. Hetken
hiljaisuus.
— Mitä sinä nyt lörpöttelet, West. Eihän täällä ole muita saksalaisia
kuin kapteeni itse, ja upseereilla ei ole lupa ottaa vaimoansa mukaan
merimatkalle, mutisivat toiset.
— Jos sinä lähdet pois, ei minulla ole ketään ystävää. Olla laivassa
näkemättä muita kuin miehiä, taivasta, vettä, kaunista ilmaa ja
myrskyä laivan ollessa satamissa, tai keinua aalloilla purjehduksen
aikana. Ei, minä tulen hulluksi.
— Eihän sinun tarvitse olla merillä. Jää kotimaahasi, vastasi
Chimb.
Onhan sinulla kai ystäviä siellä.
— Vai Peru, sanoi Chimb. Kuinka tuo kapteeni, jota niin rakastat ja
joka näkyy rakastavan sinua, on joutunut sinun isäksesi?
Charley sanoi:
Oli jo ilta ja tähdet alkoivat loistaa. Vene oli valmiiksi vedetty laivan
sivuun. Siinä oli kaksi tyhjää vesitynnyriä — meidän piti muka mennä
noutamaan vettä pienen joen suusta, joka sijaitsee metsän rajassa.
Tämä pieni joki saa alkunsa Andeilta ja laskee Tyyneenmereen
vetensä, joka muodostaa kosken parikymmentä syltä rannasta. Se
tulee semmoista vauhtia de los Andeilta, ettei juuri ennätä lämmetä
matkallaan mereen. Vesi on otettava pakoveden aikana, ennen kuin
suolainen merivesi ennättää kosken kohdalle. Pääsimme kunnialla
joen suuhun ja nousimme maihin, jonka jälkeen vene kahden
Cuxhavenin miehistöön kuuluvan miehen soutamana lähti pois,
täyttämättömine vesitynnyreineen. Seisoimme vähän aikaa
äänettöminä. Sitten kuiskasi Chimb:
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