41,99 €
Use Spring Boot to build lightning-fast apps
This book is designed for both novices and experienced Spring developers. It will teach you how to override Spring Boot's opinions and frees you from the need to define complicated configurations.
Spring Boot provides a variety of features that address today's business needs along with today's scalable requirements. In this book, you will learn how to leverage powerful databases and Spring Boot's state-of-the-art WebFlux framework. This practical guide will help you get up and running with all the latest features of Spring Boot, especially the new Reactor-based toolkit.
The book starts off by helping you build a simple app, then shows you how to bundle and deploy it to the cloud. From here, we take you through reactive programming, showing you how to interact with controllers and templates and handle data access. Once you're done, you can start writing unit tests, slice tests, embedded container tests, and even autoconfiguration tests.
We go into detail about developer tools, AMQP messaging, WebSockets, security, and deployment. You will learn how to secure your application using both routes and method-based rules. By the end of the book, you'll have built a social media platform from which to apply the lessons you have learned to any problem. If you want a good understanding of building scalable applications using the core functionality of Spring Boot, this is the book for you.
This book takes a tutorial-based approach to teach you all you need to know to get up and running with the latest version of Spring Boot. Filled with examples, you will gain hands-on experience of every area that Spring tackles.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 396
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: November 2014
Second edition: November 2017
Production reference: 1311017
ISBN 978-1-78646-378-4
www.packtpub.com
Author
Greg L. Turnquist
Copy Editor
Sonia Mathur
Reviewer
Zoltan Altfatter
Project Coordinator
Prajakta Naik
Commissioning Editor
Aaron Lazar
Proofreader
Safis Editing
Acquisition Editor
Chaitanya Nair
Indexer
Francy Puthiry
ContentDevelopmentEditor
Siddhi Chavan
Graphics
Abhinash Sahu
Technical Editor
Abhishek Sharma
Production Coordinator
Nilesh Mohite
Spring Framework is the most popular Java library. Its community keeps growing, and its appeal is being renewed in particular with Spring Boot.
In fact, we are lucky to count you in this open-source adventure as you read these lines!
A key to the Spring portfolio's success? It endures the challenge of time, and its ecosystem evolves and anticipates software industry changes with a carefully crafted domain.
So, why are Spring projects going Reactive now and what's Reactive anyway?
Without spoiling the friendly introduction Greg has prepared for you, let's focus on the "non-blocking" nature of Reactive Programming. Imagine yourself brewing beer. It does take a certain time to ferment the precious liquid before bottling it up. Would you stay for two weeks watching your preparation fermenting and do nothing else, such as answering a call or watching the last season of Rick and Morty? That's blocking, and you quickly realize that non-blocking is something we live with all the time.
Being "non-blocking" from a server perspective is the ability to decouple processing time from service time; therefore, greatly increasing the serving capacity.
Bingo, it perfectly fits with the full-scale software industry transformation to microservices architecture. Fortunately, Spring Boot is already on the case with its self-contained model and we want to offer new type of Boot apps, ones that are resource-efficient under concurrent access. Nowadays, users paint a different functional problem with each Boot app—a real challenge when it comes to aggregating other (Boot) microservice results. It's easy to mix remote access latency into processing time, and ultimately into serving time itself. Again, Reactive programming is about decoupling all of these times so the app does something else while it waits for a result. The app becomes 100% available because it never prevents servicing.
Microservice-based architectures are a major use-case Spring had waited for to expose to the this matured reactive programming model. Three years ago, the Spring Framework team and my team—an incubated initiative called Project Reactor—looked into supporting the emerging "Reactive Streams" standard within the Spring ecosystem. You probably know that Spring Framework is all about integrating, so the idea of a standard around reactive programming echoed well with us.
Reactor had some success in being an extremely efficient asynchronous library, yet it lacked a comprehensive domain to build on. Thanks to the RxJava community lead, David Karnok, not only did we work on game changing improvements, but we pushed Reactor 3's API into a de facto industrial standard: ReactiveX. Yet, our singularity comes from our focus on the new Reactive Streams standard with Java 8 and onward. Now, Reactor 3.1 is the official polished version and the product of many refinements. It is certified to support the needs of the new Reactive Spring initiatives including Spring Framework 5, Spring Boot 2, Spring Cloud, Spring Data, and even Spring Security.
These now reactive-ready Spring modules will help you build your next Spring Boot app fully reactive, connecting with each other using Reactor. As soon as Chapter 2, you will be progressing into the reactive space with concrete and well-known web examples. You will find the same web conventions Spring Framework has standardized over a decade to quickly reduce your knowledge gap with these updates. Chapter 3 will complete this tour with data access as you play with the Spring Data reactive support.
Greg has pragmatically shaped these sections to give you enough context for every subsequent reactive update introduced in this book or beyond. If you master chapters 1-3, you master them all, and I am confident that your readiness for these new patterns will bring you where you want. Efficient microservices? Mobile backends? Internet of Things? Function-as-a-Service? You name it. All these use cases share one concern: a critical need for connection scalability and resources efficiency.
Stéphane Maldini Lead developer, Project Reactor
When the first edition of Learning Spring Boot hit the streets, it was still early days. Anyone who picked up Spring Boot and started using it was immediately hooked, but not everyone did, and the book was a nice tool in driving adoption. Now, however, we are in a different phase of the life of the project. The Spring community is huge and diverse, but practically all of them now see Spring Boot as the best way to use Spring and the best way to write applications on the JVM. There are Spring Boot applications that have been in production for almost 4 years. Download numbers just grow month after month, so more and more people are using it for more and more things. The feature set of Spring and Spring Boot has grown, probably by a factor of two or more.
So, the time is ripe for a second edition. The content has been expanded and updated to cover the newest parts of the framework, and, just like Spring Boot itself, it tracks the latest developments in all the third-party libraries that people use in Spring applications. Greg has done a great job again of juggling his commitments to the Spring engineering team with his authoring, so the book is full of insights from a privileged viewpoint, as well as being a great practical tool to get off the ground with Spring Boot. His voice is authoritative, yet informal, so I hope it reaches an even bigger audience.
A book for first time users is an interesting angle. It should be valuable for anyone who wants to start using Spring or Java, but also for those already comfortable with the technology, and who want to learn about the newest features in Spring 5.0 and the entire new generation of Spring project releases that are coming down the pipe.
Dave Syer Co-Lead, Spring Boot
Greg L. Turnquist has been a software professional since 1997. In 2002, he joined the senior software team that worked on Harris' $3.5 billion FAA telco program, architecting mission-critical enterprise apps while managing a software team. He provided after-hours support to a nation-wide system and is no stranger to midnight failures and software triages. In 2010, he joined the SpringSource division of VMware, which was spun off into Pivotal in 2013.
As a test-bitten script junky, Java geek, and JavaScript Padawan, he is a member of the Spring Data team and the lead for Spring Session MongoDB. He has made key contributions to Spring Boot, Spring HATEOAS, and Spring Data REST while also serving as editor-at-large for Spring's Getting Started Guides.
Greg wrote technical best sellers Python Testing Cookbook and Learning Spring Boot, First Edition, for Packt. When he isn't slinging code, Greg enters the world of magic and cross swords, having written the speculative fiction action and adventure novel, Darklight.
He completed his master's degree in computer engineering at Auburn University and lives in the United States with his family.
Zoltan Altfatter (@altfatterz) is a software engineer, passionate about the JVM and Spring ecosystem. He has several years of industry experience working at small startups and big consultancy firms.
You can find more about him on his blog: http://zoltanaltfatter.com.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1786463784.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Quick Start with Java
Getting started
Spring Boot starters
Running a Spring Boot application
Delving into Spring Boot's property support
Bundling up the application as a runnable JAR file
Deploying to Cloud Foundry
Adding production-ready support
Pinging our app for general health
Metrics
Summary
Reactive Web with Spring Boot
Creating a reactive web application with Spring Initializr
Learning the tenets of reactive programming
Introducing Reactor types
Switching from Embedded Netty to Apache Tomcat
Comparing reactive Spring WebFlux against classic Spring MVC
Why is Spring doing this?
Showing some Mono/Flux-based endpoints
Creating a reactive ImageService
Creating a reactive file controller
Why use reactive programming?
Interacting with a Thymeleaf template
Illustrating how going from async to sync can be easy, but the opposite is not
Summary
Reactive Data Access with Spring Boot
Getting underway with a reactive data store
Solving a problem
Wiring up Spring Data repositories with Spring Boot
Creating a reactive repository
Pulling data through a Mono/Flux and chain of operations
Creating custom finders
Querying by example
Querying with MongoOperations
Logging reactive operations
Summary
Testing with Spring Boot
Test dependencies
Unit testing
Slice-based testing
Testing with embedded MongoDB
Testing with a real MongoDB database
Testing WebFlux controllers
Fully embedded Spring Boot app tests
Testing your custom Spring Boot autoconfiguration
Summary
Developer Tools for Spring Boot Apps
Using Spring Boot's DevTools for hot code reloading
Using Spring Boot's autoconfiguration report
Making local changes and seeing them on the target system
Writing a custom health check
Adding build data to /application/info
Creating custom metrics
Working with additional Actuator endpoints
Summary
AMQP Messaging with Spring Boot
Getting started with RabbitMQ
Installing RabbitMQ broker
Launching the RabbitMQ broker
Adding messaging as a new component to an existing application
Creating a message producer/message consumer
Displaying comments
Producing comments
AMQP fundamentals
Adding customized metrics to track message flow
Peeking at Spring Cloud Stream (with RabbitMQ)
Introduction to Spring Cloud
Logging with Spring Cloud Stream
Summary
Microservices with Spring Boot
A quick primer on microservices
Dynamically registering and finding services with Eureka
Introducing @SpringCloudApplication
Calling one microservice from another with client-side load balancing
Implementing microservice circuit breakers
Monitoring circuits
Offloading microservice settings to a configuration server
Summary
WebSockets with Spring Boot
Publishing saved comments to a chat service
Creating a chat service to handle WebSocket traffic
Brokering WebSocket messages
Broadcasting saved comments
Configuring WebSocket handlers
Consuming WebSocket messages from the web page
Moving to a fully asynchronous web client
Handling AJAX calls on the server
Introducing user chatting
Sending user-specific messages
Registering users without authentication
Linking a user to a session
Sending user-to-user messages
Checking out the final product
JSR 356 versus Spring WebFlux messaging
Summary
Securing Your App with Spring Boot
Securing a Spring Boot application
Using Spring Session
Creating a Gateway API
Securing the chat microservice
Authentication versus authorization
Sharing session details with other microservices
Securing the images microservice
Wiring in image ownership
Authorizing methods
Tailoring the UI with authorization checks
Securing WebSockets
Tracing calls
Securing the Config Server
Securing the Eureka Server
Summary
Taking Your App to Production with Spring Boot
Profile-based sets of beans
Creating configuration property beans
Overriding property settings in production
@ConfigurationProperties versus @Value
Pushing app to Cloud Foundry and adjusting the settings
Summary
@springboot allows me to focus on developing my app, not reinventing the wheel
@bananmuffins #VelocityConf @pivotal
– Faiz Parker @_CloudNinja
When Learning Spring Boot, First Edition, by Packt, made its debut, it was the first Spring Boot book to hit the international market. The user community ate it up, which is evidence of the popularity of Spring Boot. And today, Spring Boot is driven by the same, core principal stated in that book's preface, "How can we make Spring more accessible to new developers?"
By focusing on developers, community, and customers, Spring Boot has alleviated untold hours of time normally spent plumbing infrastructure. Andrew Clay Shafer, Pivotal's Senior Directory of Technology, has presented a most famous conference slide, "'Great job configuring servers this year'––No CEO Ever." We don't get bonus points for wasting time configuring web containers, database connectors, template view resolvers, and other mind-numbing infrastructure. However, we've done it for so long, we all assume it's a part and parcel of our trade.
Spring Boot has upset that apple cart and shown that we can, in fact, focus on building features our customers want on day one. As James Watters, Senior Vice President at Pivotal, has stated in countless presentations, when you focus on things above the value line, you build real confidence with your customers. This is demonstrated by the latest Zero Turnaround whitepaper showing that 46%, or almost one of every two Java developers, is using some part of the Spring portfolio. Spring Boot is solving problems for legions of customers, and this book can help you close the gap in your understanding.
Chapter 1, Quick Start with Java, explains how to rapidly craft a web application running on an embedded web container, access some data, and then deploy it into the cloud using minimal amounts of code and build settings.
Chapter 2, Reactive Web with Spring Boot, shows how to start building a social media service to upload pictures using Spring WebFlux, Project Reactor, and the Thymeleaf template engine.
Chapter 3, Reactive Data Access with Spring Boot, explains how we can pick up Spring Data MongoDB as a reactive-power data store and hook it to our social media platform. You'll find out how Spring Boot autoconfigures our app to persist data.
Chapter 4, Testing with Spring Boot, explains how we can write unit tests with JUnit, slice tests where small parts of our app uses real components, and full-blown embedded container testing. Also, you will see how to write an autoconfiguration policy for a browser-driving test toolkit and test that as well.
Chapter 5, Developer Tools for Spring Boot Apps, puts several tools in our hands to enhance developer experience, such as DevTools, LiveReload, and connecting our IDE to the cloud.
Chapter 6, AMQP Messaging with Spring Boot, explains how to use RabbitMQ as our message broker and reactively build up a reliable, streaming message service between components.
Chapter 7, Microservices with Spring Boot, introduces Spring Cloud and the ability to break up our social media platform into smaller, more manageable apps, dynamically talking to each other.
Chapter 8, WebSockets with Spring Boot, shows how to enhance the user experience by sending updates to all interested parties from various microservices. You will also see how to route all WebSocket messages through a RabbitMQ broker.
Chapter 9, Securing Your App with Spring Boot, lets us secure the social media platform for production with both URL-based and method-based tactics, so only registered users can get online, and only authorized admins and owners can actually delete uploaded pictures.
Chapter 10, Taking Your App to Production with Spring Boot, shows us how to bundle up our application and deploy to production without breaking the bank by using profile-based configurations to distinguish between local and cloud-based situations and creating custom properties to tailor application settings without rewriting code for every environment.
Spring Boot 2.0 requires Java Developer Kit (JDK) 8 or higher
A modern IDE (IntelliJ IDEA or Spring Tool Suite) is recommended
RabbitMQ 3.6 or higher must be installed (check out
https://www.rabbitmq.com/download.html
, or, when using Mac Homebrew, brew install RabbitMQ)
MongoDB 3.0 or higher must be installed (check out
https://www.mongodb.com/download-center
, or, when using Mac Homebrew, brew install MongoDB)
This book is designed for both novices and experienced Spring developers. It will teach you how to override Spring Boot's opinions and frees you from the need to define complicated configurations.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"The @Data annotation from Lombok generates getters, setters, a toString() method, an equals() method, a hashCode() method, and a constructor for all required (that is, final) fields."
A block of code is set as follows:
public interface MyRepository { List<Image> findAll(); }
Any command-line input or output is written as follows:
$ java -jar build/libs/learning-spring-boot-0.0.1-SNAPSHOT.jar
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "When the first user clicks on Submit, the message automatically appears on the second user's window."
Feedback from our readers is always welcome. Let us know what you think about this book--what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your email address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for macOS
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learning-Spring-Boot-2.0-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/LearningSpringBoot2.0_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books--maybe a mistake in the text or the code--we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Perhaps you've heard about Spring Boot? It's cultivated the most popular explosion in software development in years. Clocking millions of downloads per month, the community has exploded since its debut in 2013.
I hope you're ready for some fun, because we are going to take things to the next level as we use Spring Boot to build a social media platform. We'll explore its many valuable features, all the way from the tools designed to speed up development efforts to production-ready support as well as cloud-native features.
Despite some rapid fire demos you might have caught on YouTube, Spring Boot isn't just for quick demos. Built atop the de facto standard toolkit for Java, the Spring Framework, Spring Boot will help us build this social media platform with lightning speed and stability.
Also, this book will explore a new paradigm introduced in Spring Framework 5, reactive programming. In this day and age, as we build bigger systems, iterate faster, and host fleets of distributed microservices, it has become critical that we switch from a classic blocking programming style. As Josh Long would point out, this is nothing new. The network stacks of today's OSs are inherently asynchronous, but the JVM is not. Only in recent years have people realized the need to chop up tasks in a asynchronous, non-blocking fashion. However, the programming paradigm to handle potentially unlimited streams of data coming at fluctuating times requires a new programming model, which we will explore carefully alongside the power of Spring Boot itself.
In this chapter, we'll get a quick kick off with Spring Boot using the Java programming language. Maybe that makes you chuckle? People have been dissing Java for years as being slow, bulky, and not a good language for agile shops. In this chapter, we'll see how that is not the case.
In this chapter, we will cover the following topics:
Creating a bare project using the Spring Initializr found at
http://start.spring.io
Exploring Spring Boot's management of third-party libraries
Seeing how to run our app straight inside our
Integrated Development Environment (IDE)
with no standalone containers
Using Spring Boot's property support to make external adjustments
Packaging our app into a self-contained, runnable JAR file
Deploying our app into the cloud
Adding out-of-the-box production-grade support tools
No application is complete without specifying dependencies. A valuable feature of Spring Boot is its virtual packages. These are published packages that don't contain any code, but simply list other dependencies instead.
The following code shows all the dependencies we selected on the Spring Initializr site:
dependencies { compile('org.springframework.boot:spring-boot-starter-data- mongodb-reactive') compile('org.springframework.boot:spring-boot-starter-thymeleaf') compile('org.springframework.boot:spring-boot-starter-webflux') compile('org.projectlombok:lombok') compile('de.flapdoodle.embed:de.flapdoodle.embed.mongo') testCompile('org.springframework.boot:spring-boot-starter-test') }
You might have noticed that most of these packages are Spring Boot starters:
spring-boot-starter-data-mongodb-reactive
pulls in Spring Data MongoDB with the reactive bits enabled
spring-boot-starter-thymeleaf
pulls in the Thymeleaf template engine
spring-boot-starter-webflux
pulls in Spring WebFlux, Jackson JSON support, and embedded Netty
These starter packages allow us to quickly grab the bits we need to get up and running. Spring Boot starters have become so popular that many other third-party library developers are crafting their own.
In addition to starters, we have the following three extra libraries:
Project Lombok (
https://projectlombok.org
) makes it dead simple to define POJOs without getting bogged down in getters, setters, and other details.
Flapdoodle is an embedded MongoDB database that allows us to write tests, tinker with a solution, and get things moving before getting involved with an external database.
spring-boot-starter-test
pulls in Spring Boot Test, JSONPath, JUnit, AssertJ, Mockito, Hamcrest, JSONassert, and Spring Test, all within test scope.
The value of this last starter, spring-boot-starter-test, cannot be overstated. With a single line, the most powerful test utilities are at our fingertips, allowing us to write unit tests, slice tests, and full-blown our-app-inside-embedded-Netty tests. It's why this starter is included in all projects without checking a box on the Spring Initializr site.
Now, to get things off the ground, we need to shift focus to the tiny bit of code written for us by the Spring Initializr.
We just got things off the ground with an operational application, but that isn't the only killer feature of Spring Boot.
Spring Boot comes with a fistful of prebuilt properties. In fact, just about every autoconfigured component has some property setting (http://docs.spring.io/spring-boot/docs/2.0.0.M5/reference/htmlsingle/#common-application-properties) allowing you to override just the parts you like.
