Hands-On Reactive Programming in Spring 5 Build cloud-ready, reactive systems with Spring 5 and Project Reactor Oleh Dokuka Igor Lozynskyi BIRMINGHAM - MUMBAI Hands-On Reactive Programming in Spring 5 Copyright © 2018 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 authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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. Commissioning Editor: Aaron Lazar Acquisition Editor: Alok Dhuri Content Development Editor: Tiksha Sarang Technical Editor: Abhishek Sharma Copy Editor: Safis Editing Project Coordinator: Prajakta Naik Proofreader: Safis Editing Indexer: Rekha Nair Graphics: Jisha Chirayil Production Coordinator: Arvindkumar Gupta First published: October 2018 Production reference: 2041018 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78728-495-1 www.packtpub.com In the memory of my father, Ivan – Igor Lozynskyi mapt.io Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? Spend less time learning and more time coding with practical eBooks and videos from over 4,000 industry professionals Improve your learning with Skill Plans built especially for you Get a free eBook or video every month Mapt is fully searchable Copy and paste, print, and bookmark content Packt.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.Packt.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.Packt.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. Foreword Reactive programming is finally getting the attention it deserves with the help of famous Java names such as Spring Boot and Spring Framework. Which qualifier would you use to describe Spring solutions? The usual answer I hear and read from various users—pragmatic. The reactive support offered is no exception, and the team has chosen to keep supporting both reactive and non-reactive stacks. With choice comes responsibility, it is, therefore, critical to understand when to design your application "the reactive way" and what best practices you can apply to your next production-ready systems. Spring positions itself as a provider of the best tooling available to write all kinds of microservices. With its reactive stack, Spring helps developers to create incredibly efficient, available, and resilient endpoints. As a byproduct, reactive Spring microservices tolerate network latency and cope with failure in a much less impacting way. Think about it—it's the right solution if you are writing an Edge API, a mobile backend, or a heavily mutualized microservice! The secret? Reactive microservices isolate slow transactions and reward the fastest. Once you have qualified your needs, Project Reactor will be a reactive foundation of choice that will naturally pair with your reactive Spring project. In its latest 3.x iterations, it implements most of the Reactive extensions described first by Microsoft in 2011. Along with a standard vocabulary, Reactor introduces first-class support for Reactive Streams flow control at every functional stage and unique features such as Context passing. In a synthetic but not simplistic set of example-driven chapters, Oleh and Igor describe a fantastic journey into reactive programming and reactive systems. After a quick context setting, reminding the history and challenges of Project Reactor, we quickly dive into ready-to-use examples running on Spring Boot 2. The book never does miss an occasion to seriously cover testing, giving a clear idea on how to produce quality reactive code. Oleh and Igor perfectly introduce their readers to those reactive design patterns for the scalability needs of today and tomorrow. The authors cover more than reactive programming with plenty of guidance on Spring Boot or Spring Framework. In a forward- looking chapter, authors stimulate the readers' curiosity with some details about reactive communications using RSocket—a promising technology poised to deliver reactive benefits to the transport layer. I hope you will take as much pleasure from reading this book as I did and keep learning new ways of writing applications. Stéphane Maldini Lead developer, Project Reactor Contributors About the authors Oleh Dokuka is an experienced software engineer, Pivotal Champion, and one of the top contributors to Project Reactor and Spring Framework. He knows the internals of both frameworks very well and advocates reactive programming with Project Reactor on a daily basis. Along with that, the author applies Spring Framework and Project Reactor in software development, so he knows how to build reactive systems using these technologies. Igor Lozynskyi is a senior Java developer who primarily focuses on developing reliable, scalable, and blazingly fast systems. He has over seven years of experience with the Java platform. He is passionate about interesting and dynamic projects both in life and in software development. About the reviewers Mikalai Alimenkou is a senior delivery manager, Java tech lead, and experienced coach. An expert in Java development, scalable architecture, agile engineering practices, QA processes, and project management, he has more than 14 years of development experience, specializes in complex, distributed, scalable systems, and global company transformations. He's an active participant and speaker at many international conferences and is the founder and an independent consultant at XP Injection—a training and consulting provider. He's an organizer and founder of Selenium Camp, JEEConf, and XP Days Ukraine international conferences, as well as the Active Anonymous Developers Club (UADEVCLUB). Nazarii Cherkas works as a solutions architect at Hazelcast—a company that develops open source projects such as Hazelcast IMDG and Hazelcast Jet. Nazarii has many years of experience of working in different positions, from Java engineer to team lead. He has been involved in various projects for different industries, from telecoms and healthcare to critical systems serving the infrastructure of one of world's biggest airlines. He holds a master's degree in computer science of the Yuriy Fedkovych Chernivtsi National University. Tomasz Nurkiewicz is a Java champion. He had spent half of his life programming. On a daily basis, he works in the e-commerce sector. He's involved in open source, is DZone's most valuable blogger, and used to be very active on Stack Overflow. He's an author, trainer, conference speaker, technical reviewer, and runner. He claims that code that's not tested automatically is not a feature but just a rumor. He also wrote a book on RxJava. Packt is searching for authors like you If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. Table of Contents Preface 1 Chapter 1: Why Reactive Spring? 6 Why reactive? 6 Message-driven communication 10 Reactivity use cases 15 Why Reactive Spring? 19 Reactivity on the service level 20 Summary 29 Chapter 2: Reactive Programming in Spring - Basic Concepts 30 Early reactive solutions in Spring 30 Observer pattern 31 Observer pattern usage example 35 Publish-Subscribe pattern with @EventListener 38 Building applications with @EventListener 40 Bootstrapping a Spring application 41 Implementing business logic 42 Asynchronous HTTP with Spring Web MVC 43 Exposing the SSE endpoint 44 Configuring asynchronous support 45 Building a UI with SSE support 46 Verifying application functionality 47 Criticism of the solution 48 RxJava as a reactive framework 49 Observer plus iterator equals Reactive Stream 50 Producing and consuming streams 52 Generating an asynchronous sequence 55 Stream transformation and marble diagrams 56 Map operator 56 Filter operator 57 Count operator 58 Zip operator 59 Prerequisites and benefits of RxJava 60 Rebuilding our application with RxJava 63 Implementing business logic 63 Custom SseEmitter 65 Exposing the SSE endpoint 66 Application configuration 67 Brief history of reactive libraries 68 Reactive landscape 69 Summary 72