Learn Microservices with Spring Boot A Practical Approach to RESTful Services using RabbitMQ, Eureka, Ribbon, Zuul and… (Moises Macero (auth.)) (Z-Library)

Author: Moises Macero (auth.)

Java

Build a microservices architecture with Spring Boot, by evolving an application from a small monolith to an event-driven architecture composed of several services. This book follows an incremental approach to teach microservice structure, test-driven development, Eureka, Ribbon, Zuul, and end-to-end tests with Cucumber. Author Moises Macero follows a very pragmatic approach to explain the benefits of using this type of software architecture, instead of keeping you distracted with theoretical concepts. He covers some of the state-of-the-art techniques in computer programming, from a practical point of view. You’ll focus on what's important, starting with the minimum viable product but keeping the flexibility to evolve it. What You'll Learn Build microservices with Spring Boot Use event-driven architecture and messaging with RabbitMQ Create RESTful services with Spring Master service discovery with Eureka and load balancing with Ribbon Route requests with Zuul as your API gateway Write end-to-end rests for an event-driven architecture using Cucumber Carry out continuous integration and deployment Who This Book Is For Those with at least some prior experience with Java programming. Some prior exposure to Spring Boot recommended but not required.

📄 File Format: PDF
💾 File Size: 5.1 MB
45
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
Learn Microservices with Spring Boot A Practical Approach to RESTful Services using RabbitMQ, Eureka, Ribbon, Zuul and Cucumber — Moises Macero
📄 Page 2
Learn Microservices with Spring Boot A Practical Approach to RESTful Services using RabbitMQ, Eureka, Ribbon, Zuul and Cucumber Moises Macero
📄 Page 3
Learn Microservices with Spring Boot: A Practical Approach to RESTful Services using RabbitMQ, Eureka, Ribbon, Zuul and Cucumber ISBN-13 (pbk): 978-1-4842-3164-7 ISBN-13 (electronic): 978-1-4842-3165-4 https://doi.org/10.1007/978-1-4842-3165-4 Library of Congress Control Number: 2017962334 Copyright © 2017 by Moises Macero This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Cover image by Freepik (www.freepik.com) Managing Director: Welmoed Spahr Editorial Director: Todd Green Acquisitions Editor: Steve Anglin Development Editor: Matthew Moodie Technical Reviewer: Manuel Jordan Elera Coordinating Editor: Mark Powers Copy Editor: Kezia Endsley Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail rights@apress.com, or visit http://www.apress.com/rights-permissions. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the book’s product page, located at www.apress.com/ 9781484231647. For more detailed information, please visit http://www.apress.com/ source-code. Printed on acid-free paper Moises Macero New York, USA
📄 Page 4
iii About the Author ���������������������������������������������������������������������������������ix About the Technical Reviewer �������������������������������������������������������������xi Table of Contents 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
📄 Page 5
iv Chapter 2: The Basic Spring Boot Application ��������������������������������������9 Business Requirements ����������������������������������������������������������������������������������������9 The Skeleton App ������������������������������������������������������������������������������������������������10 Skinny vs� Real-Life Apps ������������������������������������������������������������������������������10 Creating the Skeleton ������������������������������������������������������������������������������������11 Warming Up: Some TDD in Action �����������������������������������������������������������������������13 Summary�������������������������������������������������������������������������������������������������������������21 Chapter 3: A Real Three- Tier Spring Boot Application ������������������������23 Introduction ���������������������������������������������������������������������������������������������������������23 Completing the Basics ����������������������������������������������������������������������������������������26 Designing the Domain �����������������������������������������������������������������������������������������33 The Business Logic Layer �����������������������������������������������������������������������������������38 The Presentation Layer (REST API) ����������������������������������������������������������������������41 The Multiplication Controller �������������������������������������������������������������������������43 The Results Controller �����������������������������������������������������������������������������������48 The Frontend (Web Client) �����������������������������������������������������������������������������������53 Playing with the Application (Part I) ��������������������������������������������������������������������58 New Requirements for Data Persistence ������������������������������������������������������������59 Refactoring the Code ������������������������������������������������������������������������������������������63 The Data Layer ����������������������������������������������������������������������������������������������������68 The Data Model ���������������������������������������������������������������������������������������������71 The Repositories ��������������������������������������������������������������������������������������������77 Completing User Story 2: Going Through the Layers�������������������������������������������87 Playing with the Application (Part II) �������������������������������������������������������������������94 Summary�������������������������������������������������������������������������������������������������������������97 Table of ConTenTs
📄 Page 6
v Chapter 4: Starting with Microservices ����������������������������������������������99 The Small Monolith Approach �����������������������������������������������������������������������������99 Analyzing the Monolith ��������������������������������������������������������������������������������103 Moving Forward �������������������������������������������������������������������������������������������105 Gamification Basics ������������������������������������������������������������������������������������������106 Points, Badges, and Leaderboards ��������������������������������������������������������������106 Applying It to the Example ���������������������������������������������������������������������������107 Moving to a Microservices Architecture ������������������������������������������������������������108 Separation of Concerns and Loose Coupling �����������������������������������������������108 Independent Changes ����������������������������������������������������������������������������������109 Scalability ����������������������������������������������������������������������������������������������������109 Connecting Microservices ���������������������������������������������������������������������������������110 Event-Driven Architecture ���������������������������������������������������������������������������������112 Related Techniques �������������������������������������������������������������������������������������113 Pros and Cons of Event-Driven Architecture �����������������������������������������������114 Further Reading �������������������������������������������������������������������������������������������117 Applying Event-Driven Architecture to the Application ��������������������������������118 Going Event-Driven with RabbitMQ and Spring AMQP ��������������������������������������119 Using RabbitMQ in Your System ������������������������������������������������������������������120 Spring AMQP ������������������������������������������������������������������������������������������������121 Sending Events from Multiplication ������������������������������������������������������������������121 RabbitMQ Configuration ������������������������������������������������������������������������������122 Modeling the Event ��������������������������������������������������������������������������������������125 Sending the Event: Dispatcher Pattern ��������������������������������������������������������128 Deeper Look at the New Gamification Microservice �����������������������������������134 Table of ConTenTs
📄 Page 7
vi Receiving Events with RabbitMQ ����������������������������������������������������������������������154 The Subscriber’s Side ����������������������������������������������������������������������������������154 RabbitMQ Configuration ������������������������������������������������������������������������������154 The Event Handler ���������������������������������������������������������������������������������������157 Requesting Data Between Microservices ���������������������������������������������������������160 Combining Reactive Patterns and REST ������������������������������������������������������160 Keeping Domains Isolated ���������������������������������������������������������������������������162 Implementing the REST Client ���������������������������������������������������������������������165 Updating Gamification’s Business Logic������������������������������������������������������170 Playing with the Microservices �������������������������������������������������������������������������173 Summary�����������������������������������������������������������������������������������������������������������176 Chapter 5: The Microservices Journey Through Tools ����������������������179 Introduction �������������������������������������������������������������������������������������������������������179 Extracting the UI and Connecting It to Gamification �����������������������������������������180 Moving the Static Content ���������������������������������������������������������������������������182 Connecting UI with Gamification �����������������������������������������������������������������184 Changes to Existing Services ����������������������������������������������������������������������187 A New, Better UI with (Almost) No Effort �����������������������������������������������������190 The Current Architecture �����������������������������������������������������������������������������������200 Service Discovery and Load Balancing �������������������������������������������������������������202 Service Discovery ����������������������������������������������������������������������������������������202 Load Balancing ��������������������������������������������������������������������������������������������205 Polyglot Systems, Eureka, and Ribbon ��������������������������������������������������������207 Routing with an API Gateway ����������������������������������������������������������������������������209 The API Gateway Pattern �����������������������������������������������������������������������������209 Zuul, Eureka, and Ribbon Working Together ������������������������������������������������214 Table of ConTenTs
📄 Page 8
vii 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 Chapter 6: Testing the Distributed System ���������������������������������������267 Introduction �������������������������������������������������������������������������������������������������������267 Setting the Scene ����������������������������������������������������������������������������������������������269 How Cucumber Works ���������������������������������������������������������������������������������������271 Hands-On Code �������������������������������������������������������������������������������������������������273 Creating an Empty Project and Choosing the Tools �������������������������������������274 Making the System Testable ������������������������������������������������������������������������278 Writing the First Cucumber Test ������������������������������������������������������������������287 Linking a Feature to Java Code �������������������������������������������������������������������291 The Supporting Classes �������������������������������������������������������������������������������302 Reusing Steps Across Features �������������������������������������������������������������������308 Running Tests and Checking Reports ����������������������������������������������������������311 Summary�����������������������������������������������������������������������������������������������������������314 Table of ConTenTs
📄 Page 9
viii Appendix A: Upgrading to Spring Boot 2�0 ���������������������������������������315 Introduction �������������������������������������������������������������������������������������������������������315 Upgrading the Dependencies ����������������������������������������������������������������������������316 Fixing the Breaking Changes ����������������������������������������������������������������������������319 The CrudRepository Interface Does Not Include findOne( ) ��������������������������319 Actuator Endpoints Have Been Moved ��������������������������������������������������������320 Applying Optional Updates ��������������������������������������������������������������������������������321 The WebMvcConfigurerAdapter Class Has Been Deprecated ����������������������321 Working with Spring Boot 2�0 ���������������������������������������������������������������������������322 Afterword ������������������������������������������������������������������������������������������323 Index �������������������������������������������������������������������������������������������������325 Table of ConTenTs
📄 Page 10
ix 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.
📄 Page 11
xi 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.
📄 Page 12
1© Moises Macero 2017 M. Macero, Learn Microservices with Spring Boot, https://doi.org/10.1007/978-1-4842-3165-4_1 CHAPTER 1 Introduction Setting 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.
📄 Page 13
2 The advantage of going step-by-step, pausing when it’s needed to settle down the concepts, is that you will understand which problem each tool is trying to solve. That’s why the evolving example is an essential part of this book. You can also grasp the concepts without coding one single line: most of the source code is included so you can read it if you prefer. The source code included in this book is available on the GitHub repository https://github.com/microservices-practical. It’s divided into different versions, which makes it easier for you to see how the application evolves along the chapters. The book includes notes with the version that is being covered in that section. Who Are You? Let’s first start with this: how interesting is this book going to be for you? This book is practical, so let’s play this game. If you identify with any of these statements, this book might be good for you. • I would like to learn how to build microservices with Spring Boot and how to use the related tools. • Everybody is talking about microservices but I have no clue what a microservice is yet: either I read theoretical explanations or just hype-enforcing articles. I can’t understand the advantages, even though I work in IT… • I would like to learn how to design and develop Spring Boot applications, but people are recommending Don- Quixote- sized books,1 sometimes even several of them. Is there any single source from which I can get a quick, practical grip on microservices without reading 1,000 pages? 1 Don Quixote. Even though it is a long book, it is still a masterpiece. Chapter 1 IntroduCtIon
📄 Page 14
3 • I got a new job, and they’re using a microservices architecture. I’ve been working mainly in big, monolithic projects, so I’d like to have some knowledge and guidance to learn how everything works there. • Every time I go to the cafeteria developers are talking about microservices… I can’t socialize anymore with my colleagues if I don’t get what they’re saying. Okay, this is a joke; don’t read this book because of that, especially if you’re not interested in programming. Regarding the knowledge required to read this book, the following topics should be familiar to you: • Java (some code parts use Java 8 in this book) • Spring (you don’t need strong experience but you should know, at least, how dependency injection works) • Maven (if you know Gradle, you’ll be fine as well) How Is This Book Different from Other Books and Guides? Reasoning Behind the Techniques Software developers and architects read many technical books and guides, either because we’re interested in learning new technologies or just because we need it for our work. We need to do that anyway since it’s a constantly-changing world. We can find all kinds of books and guides out there. Good ones are usually those from which you learn quickly, and ones that teach you not only how to do stuff, but also why you should do it that way. Using new techniques just because they’re new is the wrong way to go about it; you need to understand the reasoning behind them so you use them in the best way possible. Chapter 1 IntroduCtIon
📄 Page 15
4 This book uses that philosophy: it navigates through the code and design patterns, explaining the reasons to follow one way and not others. Learning: An Incremental Process If you look at the guides available on the Internet, you’ll notice quickly that they are not real-life examples. Usually, when you apply those cases to more complex scenarios, they don’t fit. Guides are too shallow to help you building something real. Books, on the other hand, are much better at that. There are plenty of good books explaining concepts around an example; they are good because applying theoretical concepts to code is not always easy if you don’t see the code. The problem with some of these books is that they’re not as practical as guides. You need to read them first to understand the concepts, then code (or see) the example, which is frequently given as a whole piece. It’s difficult to put into practice concepts when you see the final version directly. This book stays on the practical side and starts with code that evolves through refactoring, so the concepts are understood step-by-step. We cover the problem before exposing the solutions. Because of this incremental way of presenting concepts, this book also allows you to code as you learn and to reflect on the challenges by yourself. Is This a Guide or a Book? The pages you have in front of you can’t be called a guide: it won’t take you 15 or 30 minutes to finish them. But this is not the typical book either, in which you go through concepts illustrated with some code fragments. Instead, you start with a version of the code that is not yet optimal, and you learn how to evolve it, after learning about the benefits you can extract from that process. That does not mean that you can’t just sit down and read it, but it’s better if you code at the same time and play with the options and alternatives presented. That’s the part of the book that makes it similar to a guide. Chapter 1 IntroduCtIon
📄 Page 16
5 In any case, to keep it simple, from here onward we call this a book. Contents 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. Skeleton with Spring Boot, the Professional Way First, the book guides you through the creation of an application using Spring Boot. It’s mainly focused on the backend side, but you will create a simple web page to demonstrate how to expose functionality as a REST API. It’s important to point out that we don’t create “shortcut code” just to see Spring Boot running: that’s not the objective of this book. We use Spring Boot as a vehicle to teach concepts, but we could use any other technique, and the ideas of this book would still be valid. You learn how to design and implement the application following the well-known three-tier, three-layer pattern. You do this supported by an incremental example, with hands-on code. The result will be more than enough for you to understand the professional way of writing applications. Chapter 1 IntroduCtIon
📄 Page 17
6 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. Chapter 1 IntroduCtIon
📄 Page 18
7 This asynchronous way of thinking introduces new ways of designing code; you’ll look at it while coding your project, using RabbitMQ to support it. 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. Chapter 1 IntroduCtIon
📄 Page 19
9© Moises Macero 2017 M. Macero, Learn Microservices with Spring Boot, https://doi.org/10.1007/978-1-4842-3165-4_2 CHAPTER 2 The Basic Spring Boot Application Business Requirements We could start writing code directly but that, even being pragmatic, would be far from being a real case. Software should have a goal: in this case, we do it purely for the fact of learning but, anyway, we’ll give it a reason (a fictional one). This requirements-oriented approach is used throughout the book to make it more practical. We want to write an application to encourage users to train their math skills every day. To begin with, we will have two-digit multiplications presented to users, one every time they access the page. They will type their alias (a short name) and the result of the operation, and for that they should use only mental calculation. After they send the data, a success or failure result will be presented. In order to motivate the users, we will also introduce some simple gamification techniques: a ranking of users based on points they get when they try the calculation every day, and also when they succeed. We will show this on the results page. This is the main idea of the whole application we will build (our vision) and this book will emulate an Agile way of working in which requirements come in the form of user stories. Agile, in spite of being criticized by many software developers, has become the standard methodology applied in
📄 Page 20
10 a vast majority of IT companies. The reality is that, when implemented properly, it’s a way of working that allows teams to deliver software that can be used as early as possible and to get a valuable feedback out of it. Supported by Agile, we start simple, and then we build on top of that. Consider the first user story here. USER STORY 1 As a user of the application, I want to be presented with a random multiplication that I can solve online—not too easy, so I can use mental calculation and make my brain work every day. To make this work, we’ll split the user story into several sub-tasks: 1. Create a basic service with the business logic. 2. Create a basic API endpoint to access this service (REST API). 3. Create a basic web page to ask the users to solve that calculation. The Skeleton App Skinny vs. Real-Life Apps The first thing you’ll find if you search Spring Boot tutorial on Google is the Getting Started guide from Pivotal (see https://spring.io/guides/ gs/spring-boot/). Following the guide, you can build a Hello World (or Greetings) app, but that’s not exciting when you already have some ChApter 2 the BAsIC sprIng Boot ApplICAtIon
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List