35,99 €
Create microservices using Java EE technologies with WildFly Swarm,deploy them in the OpenShift cloud, make them resilient to network failures using Hystrix, configure continuous integration using Jenkins, and security using Keycloak.
The book starts by introducing you to WildFly Swarm—a tool that allows you to create runnable microservices from Java EE components. You’ll learn the basics of Swarm operation—creating microservices containing only the parts of enterprise runtime needed in a specific case. Later, you’ll learn how to configure and test those services.
In order to deploy our services in the cloud, we’ll use OpenShift. You’ll get to know basic information on its architecture, features, and relationship to Docker and Kubernetes. Later, you’ll learn how to deploy and configure your services to run in the OpenShift cloud.
In the last part of the book, you’ll see how to make your application production-ready. You’ll find out how to configure continuous integration for your services using Jenkins, make your application resistant to network failures using Hystrix, and how to secure them using Keycloak.
By the end of the book, you’ll have a functional example application and will have practical knowledge of Java EE cloud development that can be used as a reference in your other projects.
If you're an experienced developer familiar with Java EE technologies and would like to learn how you can use those technologies in the cloud with WildFly and OpenShift, then this book is for you.
Tomasz Adamski is a software engineer at RedHat working on WildFly/JBoss EAP application server.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 263
Veröffentlichungsjahr: 2018
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: Amarabha BanerjeeAcquisition Editor: Shweta PantContent Development Editor: Arun NadarTechnical Editor: Surabhi KulkarniCopy Editor: Dhanya BaburajProject Coordinator: Sheejal ShahProofreader: Safis EditingIndexer: Pratik ShirodkarGraphics: Jason MonteiroProduction Coordinator: Shraddha Falebhai
First published: March 2018
Production reference: 1280318
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78646-237-4
www.packtpub.com
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.
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
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.
Tomasz Adamski is a software engineer at RedHat working on WildFly/JBoss EAP application server.
Deepak Vohra is a consultant and a principal member of the NuBean software company. He is a Sun-certified Java programmer and web component developer and has worked in the fields of XML, Java programming, and Java EE for 10 years. He is the coauthor of Pro XML Development with Java Technology; the technical reviewer of O'Reilly book WebLogic: The Definitive Guide; the technical reviewer for the Course Technology PTR book Ruby Programming for the Absolute Beginner; and the author of many Packt Publishing books, such as JDBC 4.0 and Oracle JDeveloper for J2EE Development.
Filippe Spolti is a software engineer and an open source and cloud computing enthusiast. On a day-to-day basis, he works with middleware products on OpenShift. He was also a technical support engineer who helps customers to solve issues and contributed to open source projects; he contributes to local conferences in Brazil as a speaker and also by coordinating tracks. He holds a bachelor's degree in information system and a specialization in information security and software engineering and has written a book on WildFly and helped other authors by reviewing their books.
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.
Title Page
Copyright and Credits
Hands-On Cloud Development with WildFly
PacktPub.com
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewers
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
Download the color images
Conventions used
Get in touch
Reviews
Java EE and Modern Architectural Methodologies
Java EE
Java Community Process
The basic architecture of Java EE applications
The scope of the Java EE standard
Implementation of Java EE standard
Current development trends
Cloud computing
Microservices
Advantages of implementing microservices
Challenges of implementing microservices
When to adopt the microservice architecture
Microservices and the cloud
Java EE microservices
The goal of the book
The pet store application
The technologies used
Summary
Further reading
Getting Familiar with WildFly Swarm
Introducing WildFly
Performance
Extensible nature
Deployment model
Meet WildFly Swarm
Java EE application
Adapting to WildFly Swarm
Does it really work?
What has just happened here?
Summary
Further reading
Right-Sizing Your Services
Catalog service
Draft version
Fractions
Fraction detection
Fraction detection mode
Thin and hollow JARs
Using hollow JARs
Using thin JARs
Summary
Tuning the Configuration of Your Services
Modifying Swarm configuration
System properties
Implementing your own main class
The Swarm class
Providing the configuration
Using your own main along with properties
Java API
Modifying your archive
The ShrinkWrap API
Obtaining the default archive
Swarm ShrinkWrap extensions
JARArchive
WARArchive
JAXRSArchive
 XML configuration
YAML configuration
Project stages
YAML database configuration
Mixing the configurations
Summary
Further reading
Testing Your Services with Arquillian
Introducing Arquillian
Testing Swarm microservices with Arquillian
The default deployment
Swarm configuration
Testing from a standalone client
Summary
Further reading
Deploying Applications on the Cloud with OpenShift
Cloud computing
The cloud infrastructure deployment model
The public cloud
The private cloud
The hybrid cloud
The service model
Infrastructure as a Service
Platform as a Service
Software as a Service
The OpenShift architecture
Containerization
Virtualization
Containers
Kernel isolation tools
Namespaces
cgroups
The Docker implementation of containers
Images and containers
Docker registries
Docker wrap-up
Orchestrating Docker
Kubernetes
Nodes and master services
Volumes
Pods
Deployments
Services
Labels
Benefits
OpenShift
The build infrastructure
Management of projects and users
Minishift
Installation
Starting the cluster
Web console
YAML notation
CLI
Catalog-service on the OpenShift example
Summary
Further reading
Configuring Storage for Your Applications
OpenShift storage concepts
Volumes
Empty directory
Host path
Remote filesystems
PersistentVolume and PersistentVolumeClaims
The catalog-service with database
Configuring PostgreSQL database
Inspecting the volumes
Updating catalog-service
Summary
Scaling and Connecting Your Services
Deployments
Learning the basics of ReplicationController
Load balancing
Service discovery
New services
The pricing service
The customer gateway service
Environment variables
DNS discovery
Summary
Configuring Continuous Integration Using Jenkins
Learning OpenShift builds
Learning about the source-to-image build
Configuring environment variables
The whole source-to-image algorithm
Source-to-image summary
The developer view
Pipeline build
Continuous integration
Continuous deployment
Deployment pipeline
Configuring Continuous Deployment in OpenShift environments
Introducing Jenkins
Our first pipeline
Pipeline syntax language
Core pipeline elements
Standard Maven operation
OpenShift Pipeline Plugin
Summary
Further reading
Providing Security Using Keycloak
Token-based security
Rationale
A basic architecture
OpenID Connect
Authentication code flow
Introducing Keycloak
Cart-service
Installing Keycloak
Creating realm
Create a client
Users and roles
Scopes
Cart service
WildFly Swarm Keycloak adapter
SSL configuration
Secured cloud
Unsecured cloud
Summary
Further reading
Adding Resilience Using Hystrix
Unreliable network
Dependent services
The circuit breaker pattern
The Hystrix circuit breaker
Bulkheading
Fallbacks
The whole algorithm
Using Hystrix
Summary
Further reading
Future Direction
No more standards?
Eclipse MicroProfile
Jakarta EE
Summary
Further reading
Other Books You May Enjoy
Leave a review - let other readers know what you think
The mission of the book is to make you familiar with the tools that you can use to develop and deploy Java EE applications in the cloud. You will be led through the whole application development process: creating the application, deploying in the cloud, configuring Continuous Integration, and secure and fault-tolerant communication between the created services. As a result, you will gain practical knowledge of Java EE cloud development, which you can use as a reference for your further projects.
If you're an experienced developer who's familiar with Java EE technologies and would like to learn how you can use those technologies in the cloud with WildFly and OpenShift, then this book is for you.
Chapter 1, Java EE and Modern Architectural Methodologies, gives users an overview of the current state of Java EE and its relevance to modern architectural methodologies, that is, microservices and cloud computing. We will introduce the tools that will be used throughout the book and the application that we will be developing.
Chapter 2, Getting Familiar with WildFly Swarm, covers WildFly and how it relates to Java EE and its main features. We will introduce WildFly Swarm—WildFly's side project—describe its purpose, and show how it can be used to develop microservices.
Chapter 3, Right-Sizing Your Services, focuses on what Swarm does to create your services with only those dependencies that are necessary for them. You will learn in greater detail what a fraction is, how Swarm detects which fractions should be used, and how you can modify the fraction discovery behavior.
Chapter 4, Tuning the Configuration of Your Services, helps you to learn how to configure your Swarm services. We will show you practical examples of different configuration tools that are available and how you can use them to steer the behavior of your applications.
Chapter 5, Testing Your Services with Arquillian, teaches you how to test your microservices. This chapter will introduce Arquillian, the testing framework that will be used, and present the purpose of the project and its main features. Later, you will learn how to develop, write, and configure tests for your services based on practical examples.
Chapter 6, Deploying Applications on the Cloud with OpenShift, discusses how to deploy those services to the cloud, and this chapter uses OpenShift to achieve that.
Chapter 7, Configuring Storage for Your Applications, starts by helping you learn the theoretical basis of OpenShift storage configuration. Later, we will show you how to deploy a database in the cloud and configure your cloud applications to use it.
Chapter 8, Scaling and Connecting Your Services, looks in greater detail at the process of deploying, scaling, and connecting your applications running in an OpenShift environment.
Chapter 9, Configuring Continuous Integration Using Jenkins, teaches you how to integrate the pet store application with Jenkins, a Continuous Integration server. We will introduce CI concepts and show how they can be implemented using Jenkins.
Chapter 10, Providing Security Using Keycloak, deals with the basics of distributed, token-based security. We will introduce Keycloak, an authentication server, that can be used to secure distributed cloud applications. As a practical example, we will secure part of the API of the Petstore application.
Chapter 11, Adding Resilience Using Hystrix, discusses how to deal with network failures, which are inevitable in a distributed environment. In order to do that, we will introduce the circuit breaker architectural pattern and cover when it should be used and what are its benefits. We will look at its Netflix implementation, Hystrix. We will cover how it is implemented and how it can be used.
Chapter 12, Future Direction, describes briefly what the future of Java EE development is likely to look such as, the plans for evolving the platform and how concepts provided by applications described in the book may be standardized in the future. We will also take a look at MicroProfile and Jakarta EE, describe their purpose, and emphasize how they can help you to move the platform forward at a faster pace.
This book assumes that you are familiar with Java EE technology. Although we will be briefly reminding what Java EE constructs do in the examples, they won't be explained in detail.
The code repository contains the examples from all the chapters. In order to help you navigate through them, the examples are indexed from within the chapters.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit 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 at
www.packtpub.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-Cloud-Development-with-WildFly. 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!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here:
https://www.packtpub.com/sites/default/files/downloads/HandsOnCloudDevelopmentwithWildFly_ColorImages.pdf.
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: "Computer programming books often start with a Hello World application."
A block of code is set as follows:
package
org.packt.swarm
;
import
javax.ws.rs.
GET
;
import
javax.ws.rs.
Path
;
import
javax.ws.rs.
Produces
;
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
package
org.packt.swarm
;
import
javax.ws.rs.
ApplicationPath
;
import
javax.ws.rs.core.Application
;
@ApplicationPath("/")
public class
HelloWorldApplication
extends
Application {}
Any command-line input or output is written as follows:
mvn wildfly-swarm:run
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "we have to click on the Create a route in Services menu of the web console."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please 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.packtpub.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.
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 packtpub.com.
In this chapter, we will give users an overview of the current state of JavaEnterprise Edition (EE) and its relevance in modern architectural methodologies, that is, microservices and cloud computing. We will introduce the tools that will be used throughout the book and the application that we will be developing.
Let's start by recalling a few basic facts about Java EE.
Before sketching the Java EE architecture, let's take a quick look at the process through which the standard is created.
Java EE is a standard designed for building enterprise applications with the Java programming language. It contains a number of specifications, which define functionalities required by implementations of the standard.
Specifications that constitute Java EE are developed in an open, community-based process. Both organizations and individual users can join it and take part in the development.
As a standard, Java EE may possess multiple implementations. A vendor who is willing to create a product that is Java EE-certified has to pass a technology compliance test, which guarantees that the product is in alignment with the standard.
The standard provides the contract between enterprise application developers and the vendors of standard implementations. An application developer can be sure that their application will be supported and portable, as there are a number of standard implementations; they are not dependent on one vendor. Application developers are free to migrate their applications between different standard implementations.
It is also important to note that the standard does not determine the details of server implementation. As a result, vendors have to compete to provide the most efficient, robust, and easy-to-use implementation.
To sum up, the Java EE standard provides enterprise application developers with an ability to write supported and portable applications. Furthermore, the community-based specification development process and competition between vendors help the standard to evolve and allows users to choose the best implementation for their needs.
On the flip side, the fact that Java EE is a standard implementation result in a slower evolution and decision-making process than alternative frameworks. In a world in which technology is being developed rapidly, this becomes a bigger problem. As a result, recently, an effort has been made to refactor the way in which standards and specifications are created. Java EE is currently transforming into EE4J, a standard developed under Eclipse Foundation's governance. We will return to this topic in the final Chapter 12: Future Directions.
Java EE applications are written in the Java language and run on Java virtual machine (JVM). On top of the standard Java SE functionality, the Java EE implementation provider implements a number of services, which can be used by those applications. Examples of such services may be security, transactions, or dependency injection.
Applications don't interact with enterprise services directly. Instead, the specifications define the component and containers concepts. Components are software units written in the Java language and configured and built in a similar way to standard Java classes. The difference is that metatada provided with the component allows it to be run using a runtime provided by the Java EE implementation. Such a runtime, which may differ for the different types of component, is called a container. The container is responsible for providing access to all enterprise services required by the component.
As an example, let's take a look at the following component:
package
org.tadamski.examples.javaee
;
import
org.tadamski.examples.java.ee.model.Foo
;
import
javax.ejb.
Stateless
;
import
javax.enterprise.event.Event
;
import
javax.inject.
Inject
;
import
javax.persistence.EntityManager
;
//1
@Stateless
public class
FooDaoBean implements FooDao {
//2
@Inject
private
EntityManager
em
;
public void save
(Foo foo)
throws
Exception { //3
em
.persist(foo)
;
}}
The preceding script presents an ejb component (1), that is, FooDaoBean, which is responsible for saving objects of the Footype into the database.
The ejb container in which this component will run will be responsible for pooling instances of this component and managing the lifecycle for all of them. Furthermore, this concrete component takes advantage of the number of enterprise services: dependency injection (2), ORM persistence (3), and transactions (the default for this kind of component).
In general, the goal of the Java EE runtime is to take care of all technical aspects of enterprise applications so that the application developer can concentrate on writing business code. The preceding example demonstrates how it is realized in Java EE: the application developer writes their code using POJOs with minimal configuration (provided mostly by annotations). The code written by an application developer implements business functionalities declaratively, informing middleware about its technical requirements.
Traditionally, business applications written in the Java EE technology were based on a three-tier architectures, web, business, and enterprise information system tier:
Application server implements web and business tiers. It can be accessed by various types of clients
Web components, such as Servlets, JSPs, or JAX-RS, allow for the implementation of the web layer. They are able to respond to the HTTP requests from different kinds of clients. For example, JSF may be used to create web user interfaces in a convenient way, whereas the JAX-RS API allows for the implementation of RESTful services.
The business layer is implemented by EJBs, pooled POJO-based components that allow for the easy implementation of transactional operations and that can provide a wide array of capabilities such as security, database, external system integration, remote access, or dependency injection.
Although the bird's-eye view architecture is quite straightforward, it is very elastic and allows for the implementation of a wide array of enterprise applications. Moreover, the standard has evolved throughout the years, providing tools for a wide array enterprise usage.
If you take a look at Java EE specification (Further Reading, link 1) you will be able to see all the specifications that are part of the standard. The shared amount of them may be intimidating at first slight. It should be noted that, in most cases, you will have to deal with only a subset of those. On the other hand, when your applications require any kind of enterprise functionality, it is highly probable that the needed tool is already there for you—integrated with the whole platform and easy to use.
Java EE standard implementations are runtimes that allow us to run the components and provide them with the services specified in the Java EE standard. Such runtimes are called application servers.
Application developers create components based on the specification. Those components are assembled into archives, which can be deployed on application servers.
Application servers allow for the deployment of a number of applications. Furthermore, as hinted at the beginning of this chapter, an application can change the server implementation and deploy archives using the application server from the other vendor:
The way applications are developed evolves over time. Let's sketch concepts that have had a big impact on software development in recent years: cloud computing and microservices.
Cloud computing is an infrastructure that makes it possible to automatically provision computing resources on demand. The types of resource provided depend on the contract between the cloud provider and the customer—the cloud provider can provide software services, such as email or disk storage, platforms for software development, access to virtual machines, or infrastructure for running software applications.
The resources are provided dynamically and rapidly using the internet, and, as a result, the customer is able to use (and pay) for resources that they currently use. The cloud provider, on the other hand, can take advantage of economies of scale: specialization and optimal resource usage will result in quality improvements and cost optimization.
So, how does interaction with cloud computing infrastructures look from the developer's point of view? During the development, the cloud provider provides a platform that contains a number of tools: it enables developers to run multiple application frameworks, standalone services, and databases among others. It provides functionalities and tools needed by those applications: scaling, networking, security, and communication. Furthermore, as hinted earlier, a user pays only for the resources used; cloud infrastructure will adjust the resources provided based on the load used by your application.
The preceding description sounds promising, but it immediately raises a number of questions, such as how are the resources provisioned and scaled, what kinds of tools can I use, and what are the APIs for the tools provided.
One of the goals of this book is to provide you with all this information throughout. For the purpose of this introductory chapter, it is enough to acknowledge the most important information: cloud computing infrastructures will enable us to develop and deploy with a wide array of tools using computing resources provided on demand.
Microservices architecture is a software development methodology that advocates creating an application from loosely coupled services that cooperate together.
Such an architecture was researched and advertised for a long period of time: Some time ago, a lot of attention was given to Service-Oriented Architecture (SOA). Even earlier, CORBA, the standard for distributed computing, was designed. Furthermore, building your applications with loosely coupled, highly cohesive services is a good software practice, and it can (and should) also be applied in a traditional monolithic application. Why has the new concept been created then, and what distinguishes it?
In recent years, a number of companies building large distributed systems have found it harder to build and maintain their systems using the traditional monolithic software architectures and decided to refactor their systems to loosely coupled modular distributed systems. Looking at the experience of those companies that succeeded in doing so, we were able to gather common architectural patterns in the systems that they built. This gave birth to the microservice architecture concept. Put in another way, microservices can be thought of as a software architecture that is another iteration of distributed computing systems, whose characteristics were derived from practical experience. As a result, instead of providing a definition of microservice architectures to which all aspiring implementors have to adhere, it is easier to provide a common set of characteristics that microservice systems share (Further Reading, link 2). Let's do it now.
Microservices are built as standalone services that are independently deployable. From the technical point of view, it means that they run in different processes and communicate through the network using their APIs. Each of the services can be started, stopped, and updated independently. Each service is responsible for its own data and can modify the data of other services using only their API.
The system is decomposed into microservices around business functionalities. Each microservices is built by one, small team that consists of all necessary technical specialists. For example, in a store application, there may be a review service. The review service team may consist of programmers, database engineers, testers, and domain experts. The team is responsible for every aspect of this service—from getting customer feedback to database administration.
As you can see, instead of advertising a set of recommended characteristics that the applications should adhere to, successful microservice practitioners have created a technological environment that enforces modularity and loose coupling.
So, if you successfully implement a microservice architecture, what benefits will you obtain?
The first thing that is straightforward but should be emphasized is that if you successfully create a system whose architectural characteristics-force modularity and loose coupling, you will obtain a highly modular system as ad hoc fixes and extensions won't compromise and effectively abandon the boundaries between services throughout the development process.
Because of the modular characteristics of developed applications, components that constitute them may be developed more effectively: As there is a small, cross-sectional team working on each service, its members can concentrate on their own area of work relatively independently of other teams. As the practice suggests, as the team grows communication starts to inhibit work more and more. The small, focused team knows the domain well, and they also know each other well, can communicate immediately, and move the work forward.
Also, crucial is the fact that the service can be deployed independently of other services. A successful microservices architecture does not have the concept of big system release in which all teams gather their recent updates together and create a major release of the whole system. Instead, all teams are able to release and deploy their new functionalities independently of other services. There is no synchronization between the teams, and if there is a new version of a service that can be released, the service's team can just independently design to do it. Such a characteristic is a catalyst for Continous Integration. The team is able to build the pipeline so that each code triggers a test, review, and deploy process.
The characteristics described in the preceding paragraph—small, focused teams and independent and automated build and deployment processess—lead to very important characteristics of the successful microservices-based system: an ability to implement required changes very fast. This is crucial, as it allows for immediate responses to customer needs. This tightens the feedback loop between the customer and developer and allows the system to quickly evolve to meet the customer needs.
