Hands-On Reactive Programming with Reactor - Rahul Sharma - E-Book

Hands-On Reactive Programming with Reactor E-Book

Rahul sharma

0,0
36,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Discover how project Reactor enhances the reactive programming paradigm and allows you to build scalable asynchronous applications




Key Features



  • Use reactive APIs, Flux, and Mono to implement reactive extensions


  • Create concurrent applications without the complexity of Java's concurrent API


  • Understand techniques to implement event-driven and reactive applications





Book Description



Reactor is an implementation of the Java 9 Reactive Streams specification, an API for asynchronous data processing. This specification is based on a reactive programming paradigm, enabling developers to build enterprise-grade, robust applications with reduced complexity and in less time. Hands-On Reactive Programming with Reactor shows you how Reactor works, as well as how to use it to develop reactive applications in Java.







The book begins with the fundamentals of Reactor and the role it plays in building effective applications. You will learn how to build fully non-blocking applications and will later be guided by the Publisher and Subscriber APIs. You will gain an understanding how to use two reactive composable APIs, Flux and Mono, which are used extensively to implement Reactive Extensions. All of these components are combined using various operations to build a complete solution.







In addition to this, you will get to grips with the Flow API and understand backpressure in order to control overruns. You will also study the use of Spring WebFlux, an extension of the Reactor framework for building microservices.







By the end of the book, you will have gained enough confidence to build reactive and scalable microservices.




What you will learn



  • Explore benefits of the Reactive paradigm and the Reactive Streams API


  • Discover the impact of Flux and Mono implications in Reactor


  • Expand and repeat data in stream processing


  • Get to grips with various types of processors and choose the best one


  • Understand how to map errors to make corrections easier


  • Create robust tests using testing utilities offered by Reactor


  • Find the best way to schedule the execution of code





Who this book is for



If you're looking to develop event- and data-driven applications easily with Reactor, this book is for you. Sound knowledge of Java fundamentals is necessary to understand the concepts covered in the book.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 223

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Hands-On Reactive Programming with Reactor

 

 

 

 

Build reactive and scalable microservices using the Reactor framework

 

 

 

 

 

 

 

 

Rahul Sharma

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Hands-On Reactive Programming with Reactor

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 author, 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 LazarAcquisition Editor: Denim PintoContent Development Editor: Tiksha SarangTechnical Editor: Abhishek SharmaCopy Editor:Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer: Pratik ShirodkarGraphics: Jisha ChirayilProduction Coordinator: Shantanu Zagade

First published: September 2018

Production reference: 1280918

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78913-579-4

www.packtpub.com

 
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.

Contributors

About the author

Rahul Sharma is a seasoned Java developer with around 13 years' experience in Java/J2EE applications. He has worked at companies ranging from enterprises to start-ups. Being an open source enthusiast, he has contributed to various projects, including Apache Crunch. He is currently working with a Java framework, Project Reactor.

About the reviewer

Suchit Khanna is a seasoned developer, cricket enthusiast, and an avid traveler. He has worked for more than a decade in helping to build maintainable and scalable enterprise systems. When he's not writing code, he's most likely playing cricket or traveling with his better half. 

 

 

 

 

 

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

Title Page

Copyright and Credits

Hands-On Reactive Programming with Reactor

Packt Upsell

Why subscribe?

Packt.com

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Get in touch

Reviews

Getting Started with Reactive Streams

Technical requirements 

Reactive architecture

Reactive programming

ReactiveX

Composite streams

Flexible operators

Reactive Streams

Asynchronous processing

Subscriber backpressure

David Karnok's classification

Zero generation

First generation

Second generation

Third generation

Fourth generation

Fifth generation

Reactor

Infinite data streams

Push-pull model

Concurrency agnostic

Operator vocabulary

Project setup

Summary

Questions

Further reading

The Publisher and Subscriber APIs in a Reactor

Technical requirements

Stream publisher

Stream subscriber

Subscription

Reactive Streams comparison

The Observable interface

Java Messaging Service API

Learning about the Reactor Core API

The Flux API

Generating the Flux API

The Flux.just method

The Flux.from methods

Utility methods

The Flux.generate method

SynchronousSink

Flux.create

The Mono API

Generating a Mono

The Mono.just method

The Mono.from method

Utility methods

Mono.create

Building subscribers to Flux and Mono

Lifecycle hooks

Trying a hands-on project

Summary

Questions

Further reading

Data and Stream Processing

Technical requirements

Generating data

Filtering data

The filter() operator

The take operator

The skip operator

Converting data

The map() operator

The flatMap operator

The repeat operator

The collect operator

The collectMap operator

The reduce operator

Conditional tests

Appending data

The concatWith operator

Summary

Questions

Processors

Technical requirements 

An introduction to processors

Understanding processor types

The DirectProcessor type

The UnicastProcessor type

The EmitterProcessor type

The ReplayProcessor type

The TopicProcessor type

The WorkQueueProcessor type

Hot versus Cold publishers

Summary

Questions

SpringWebFlux for Microservices

Technical requirements

Introduction to SpringWebFlux

Configuring annotations

SpringBoot Starter

Adding a controller

Method parameters

Exception handling

Configuring functions

The handler function

The router function

HandlerFilter

HttpHandler

Fibonacci functional router

Summary

Questions

Dynamic Rendering

Technical requirements 

View templates

Resolving views

Freemarker

Thymeleaf

Scripting

Mustache

Learning about static resources

WebClient

Summary

Questions

Flow Control and Backpressure

Technical requirements

Flow control

The groupBy operator

The buffer operator

The window operator

The sample operator

Backpressure

OnBackpressure

Summary

Questions

Handling Errors

Technical requirements

Generating errors

Checked exceptions

The doOnError hook

The doOnTerminate hook

The doFinally hook

Error recovery

The onErrorReturn operator

The onErrorResume operator

The onErrorMap operator

Timeout

WebClient

Summary

Questions

Execution Control

Technical requirements

Scheduler

Reactor schedulers

The immediate scheduler

The single scheduler

The parallel scheduler

The elastic scheduler

The ExecutorService scheduler

Parallel processing

PublishOn operator

SubscribeOn operator

ParallelFlux

Broadcasting

The replay operator

The publish operator

Summary

Questions

Testing and Debugging

Technical requirements

Testing Reactor pipelines

StepVerifier

expectError

expectNext

Capture values

Verify

Validating backpressure

Validating time operations

Publisher probe

Publisher stubs

Debugging Reactor streams

Debug hook

Checkpoint operator

Stream logging

Summary

Questions

Assessments

Chapter 1: Getting Started with Reactive Streams

Chapter 2: The Publisher and Subscriber APIs in a Reactor

Chapter 3: Data and Stream Processing

Chapter 4: Processors

Chapter 5: SpringWebFlux for Microservices

Chapter 6: Dynamic Rendering

Chapter 7: Flow Control and Backpressure

Chapter 8: Handling Errors

Chapter 9: Execution Control

Chapter 10: Testing and Debugging

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Reactor is an implementation of the Java 9 Reactive Streams specification, an API for asynchronous data processing. This specification is based on a reactive programming paradigm, enabling developers to build enterprise-grade, robust applications with reduced complexity and in less time. Hands-On Reactive Programming with Reactor shows you how Reactor works, as well as how to use it to develop reactive applications in Java.

The book begins with the fundamentals of Reactor and the role it plays in building effective applications. You will learn how to build fully non-blocking applications and will later be guided on the Publisher and Subscriber APIs. The first four chapters will help you to understand Reactive Streams and the Reactor framework. The following four chapters use Reactor to build a microservices SpringWebFlux extension to build REST-based web services. They demonstrate the concepts of the flow, backpressure, and execution models. You will gain an understanding of how to use two reactive composable APIs, Flux and Mono, which are used extensively to implement Reactive Extensions. In the final two chapters, you will gain an understanding of Reactive Streams and the Reactor framework.

The chapters explain the most important parts and build simple programs to establish a foundation. By the end of the book, you will have gained enough confidence to build reactive and scalable microservices.

Who this book is for

For anyone with a basic understanding of Java's fundamental concepts, and how to develop event-driven and data-driven applications easily with Reactor, this book is for you – a step-by-step guide to getting you up and running with Reactive Streams and the Reactor framework.

What this book covers

Chapter 1, Getting Started with Reactive Streams, explains the Reactive Streams API and introduces the reactive paradigm and its benefits. The chapter also introduces Reactor as an implementation of Reactive Streams.

Chapter 2, The Publisher and Subscriber APIs in a Reactor, explains the Producer and Subscriber APIs and the corresponding Flux and Mono implications of Reactor. It also discusses use cases of Flux and Mono and the respective Sinks. We will also look into Hot and Cold variants of the components.

Chapter 3, Data and Stream Processing, tackles how we can process data generated by a Publisher before it gets consumed by a Subscriber, the possible operations available, and combining them to build a robust stream-processing pipeline. Stream processing also involves converting, pivoting, and aggregating data, and then generating new data.

Chapter 4, Processors, introduces the out-of-the-box processors available in Reactor. Processors are special Publishers, which are also Subscribers, and it is quite important to understand why we need them before jumping into putting one into practice. 

Chapter 5, SpringWebFlux for Microservices, introduces SpringWebFlux, a Reactor web extension. It explains the concepts of the RouterFunction, HandlerFunction, and FilterFunction. We will then build a REST-based microservice using Mongo as a store.

Chapter 6, Dynamic Rendering, integrates a templating engine into the REST-based microservice we introduced in the previous chapter, to render dynamic content. It also demonstrates request filters.

Chapter 7, Flow Control and Backpressure, discusses flow control, an important aspect of reactive programming, which is essentially required to control overruns by a fast Publisher. It also discusses various ways to control the complete pipeline processing.

Chapter 8, Handling Errors, as its title suggests, explains how to handle errors. All Java developers are accustomed to the try-catch-finally block of error handling. This chapter translates it for stream processing. It also covers how we can recover from an error and how can we go about generating errors. This is an essential requirement for all enterprise applications.

Chapter 9, Execution Control, looks at the various strategies available in Reactor for processing the built stream. It could be scheduled at some interval or batched in groups, or all operations can be performed in parallel. 

Chapter 10, Testing and Debugging, lists ways we can test a stream, because no development is complete without being tested. We will build JUnit tests that will use some of the testing utilities offered by Reactor to create robust tests. The chapter also lists ways to go about debugging asynchronous flows built over Reactor.

To get the most out of this book

It is essential to have a sound understanding of the basic Java concepts

Java Standard Edition, JDK 8, and IntelliJ IDEA IDE or above are required

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.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 at

www.packt.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

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 Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Reactive-Programming-with-Reactor. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "All Subscribe methods return a Disposable type. This type can also be used to cancel the subscription."

A block of code is set as follows:

public interface Publisher<T> {

public void subscribe(Subscriber<? super T> s); }

Any command-line input or output is written as follows:

gradlew bootrun

Bold: Indicates a new term, an important word, or words that you see onscreen.

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Getting Started with Reactive Streams

Over the years, application architecture has evolved. Businesses increasingly need to build systems that remain responsive and can scale when required. Systems should also be maintainable and quickly releasable. In accordance with these needs, we have started to build applications as loosely coupled services. We no longer build a system as one big application. Instead, we split systems into multiple independent, autonomous services. The objective for such services is to do one thing, and do it well.

In this chapter, we will discuss concerns associated with building such services. We will also look at how to address those concerns.

Technical requirements 

Java Standard Edition, JDK 8 or above

IntelliJ IDEA IDE, 2018.1 or above

The GitHub link for this chapter is https://github.com/PacktPublishing/Hands-On-Reactive-Programming-with-Reactor/tree/master/Chapter01.

Reactive architecture

When we start to build microservice architecture, we try to involve different services to deliver business solutions. We often build services as traditional API models, where each of the services can interact with other services. This is referred to as distributed architecture. If a distributed architecture is designed incorrectly, performance issues surface very quickly. It can be difficult to have numerous distributed services that work concurrently to deliver the intended performance. Companies that offer services requiring large data exchange (such as Netflix, Amazon, or Lightbend) have therefore seen a need for alternative paradigms, which can be used for systems with the following characteristics:

Consisting of very loosely coupled components

Responding to user inputs

Resilient to varying load conditions

Always available

In order to achieve the preceding characteristics, we need to build event-driven, modular services that communicate with each other by using notifications. In turn, we can respond to the system's flow of events. The modular services are more scalable, as we can add or remove service instances without halting the complete application. The complete architecture will be fault tolerant if we can isolate errors and take corrective actions. The preceding four characteristics are the basic principles of the Reactive Manifesto. The Reactive Manifesto states that each reactive system should consist of loosely coupled components that rely on asynchronous, message-driven architecture. They must remain responsive to user input and isolate failures to individual components. Replication must be done in order to respond to varying load conditions. The following is a diagram of the Reactive Manifesto:

The Reactive Manifesto describes a reactive system. It does not required that the system be based on reactive programming, or any other reactive library. We can build a message-driven, resilient, scalable, and responsive application without using a reactive library, but it is easier to build an application based on reactive libraries.

ReactiveX

Reactive Extensions, also known as ReactiveX, enable us to express the asynchronous events in an application as a set of observable sequences. Other applications can subscribe to these observables, in order to receive notifications of events that are occurring. A producer can then push these notification events to a consumer as they arrive. Alternatively, if a consumer is slow, it can pull notification events according to its own consumption rate. The end-to-end system of a producer and its consumers is known as a pipeline. It is important to note that pipelines are lazy by default and do not materialize until they are subscribed to by a consumer. This is very different from eager Java types, like Future, which represent active work. The ReactiveX API consists of the following components:

Observables

:

Observables represent the core concept of ReactiveX. They represent the sequences of emitted items, and they generate events that are propagated to the intended subscribers.

Observer:

Any application can express its intent for events published by an observable by creating an observer and subscribing to the respective observable. The intent is expressed in terms of the 

OnNext

,

OnCompleted

, and

OnError

methods. Each observable sends a stream of events, followed by a completion event, which executes these methods.

Operators

:

O

perators enable us to transform, combine, and manipulate the sequences of items emitted by observables. The operators on an observable provide a new observable, and thus, they can be tied together. They do not work independently on the original observable; instead, they work on the observable generated by the previous operator to generate a new observable.

The complete operator chain is lazy. It is not evaluated until an observer is subscribed to it. The complete chain is shown as follows:

ReactiveX provides the architecture design to build reactive applications. Individual libraries were built around it in different imperative languages to enable its use. These abstractions allow us to build asynchronous, non-blocking applications, and provide the additional benefits listed in the following sections.

Composite streams

In software design, composition refers to grouping different entities and treating each group as a single entity. Additionally, the single entity exhibits the same behavior as the type it refers to. ReactiveX streams are composite in nature. They make it possible to combine existing data streams, add transformations, and generate new data streams. Moreover, all of this can be done in a declarative manner, making the overall solution maintainable in the long run. 

Flexible operators

The libraries offer a range of operators for all kinds of functions. Each of the operators accomplishes its tasks similarly to that of a workstation on an assembly line. It takes input from the previous workstation and provides input to the next workstation. These operators offer all kinds of data transformation, stream orchestration, and error handlers.

ReactiveX makes its easier to build event-based applications. However, the framework does not present the ways in which different event-driven applications should interact with each other. In a microservice architecture consisting of numerous event-driven services, the gains made are often offset by the workarounds required for inter-process communication.

Reactive Streams

Reactive Streams is a specification that determines the minimum set of interfaces required to build the asynchronous processing of a large volume of unbounded data. It is a specification aimed at JVM and JavaScript runtime. The main goal of the Reactive Streams specification is to standardize the exchange of stream data across an asynchronous boundary of applications. The API consists of the following four interfaces:

Publisher: The publisher is responsible for the generation of an unbounded number of asynchronous events and pushing those events to the associated subscribers.

Subscriber: The subscriber is a consumer of the events published by a publisher. The subscriber gets events for subscription, data, completion, and error. It can choose to perform actions on any of them.

Subscription: A subscription is a shared context between the publisher and subscriber, for the purpose of mediating the data exchange between the two. The subscription is available with the subscriber only, and enables it to control the flow of events from the publisher. The subscription becomes invalid if there is an error or a completion. A subscriber can also cancel the subscriptions, in order to close its stream.

Processor: The processor represents a stage of data processing between a subscriber and a publisher. Consequently, it is bound by both of them. The processor has to obey the contract between the publisher and the subscriber. If there is an error, it must propagate it back to the subscriber.

The Reactive Streams specification is the result of a collaborative effort of engineers from Kaazing, Netflix, Pivotal, Red Hat, Twitter, Typesafe, and many other companies.

While there are only four interfaces, there are around 30 rules that govern the data exchange between the publisher and the subscriber. These rules are based on the two principles covered in the following sections.

Asynchronous processing

Asynchronous execution refers to the ability to execute tasks without having to wait to finish previously executed tasks first. The execution model decouples tasks, so that each of them can be performed simultaneously, utilizing the available hardware.

The Reactive Streams API delivers events in an asynchronous manner. A publisher can generate event data in a synchronous blocking manner. On the other hand, each of the on-event handlers can process the events in a synchronously blocking manner. However, event publishing must occur asynchronously. It must not be blocked by the subscriber while processing events.

Subscriber backpressure

A subscriber can control events in its queue to avoid any overruns. It can also request more events if there is additional capacity. Backpressure enforces the publisher to bound the event queues according to the subscriber. Furthermore, a subscriber can ask to receive one element at a time, building a stop-and-wait protocol. It can also ask for multiple elements. On the other hand, a publisher can apply the appropriate buffers to hold non-delivered events, or it can just start to drop events if the production rate is more than the consumption rate.

It is important to note that the Reactive Streams API is aimed at the flow of events between different systems. Unlike ReactiveX, it does not provide any operators to perform transformations. The API has been adopted as a part of the java.util.concurrent.Flow package in JDK 9.

David Karnok's classification

David Karnok, a veteran of various reactive projects like Rxjava and Reactor, has categorized the evolution of reactive libraries into the following generations.

Zero generation

The zero generation revolves around the java.util.observable