Spring Microservices in Action PDF
Spring Microservices in Action PDF
PDF
John Carnell
Scan to Download
Spring Microservices in Action
Mastering Microservices with Spring Boot and
Cloud for Cloud Deployment
Written by Bookey
Check more about Spring Microservices in Action
Summary
Listen Spring Microservices in Action Audiobook
Scan to Download
About the book
In "Spring Microservices in Action," author John Carnell
guides Java developers through the transition from traditional
monolithic applications to agile, microservice architectures
using Spring Boot and Spring Cloud. This comprehensive
resource begins with a foundational understanding of the
microservice pattern and progresses into practical, hands-on
techniques for building and deploying cloud-native
applications. Through real-world examples, you'll learn to
configure Spring Boot, implement service discovery with
Netflix Eureka and Ribbon, and apply client-side resiliency
patterns using Netflix Hystrix. The book also delves into
creating service gateways with Spring Cloud Zuul and
managing event processing with Spring Cloud Stream. By the
conclusion, you'll be equipped not only to develop your own
microservices but also to effectively operationalize and scale
them for deployment on platforms such as AWS and
CloudFoundry.
Scan to Download
About the author
John Carnell is a seasoned software architect and developer
with a rich background in microservices and cloud-native
technologies. His expertise lies in designing and building
scalable applications, and he is dedicated to sharing his
knowledge through insightful writing. In "Spring
Microservices in Action," Carnell combines practical
experience with clear explanations, making complex concepts
accessible to developers of all skill levels. His passion for
technology and teaching helps readers navigate the evolving
landscape of microservices effectively.
Scan to Download
Summary Content List
Chapter 1 : Welcome to the cloud, Spring
configuration server
Stream
Zipkin
Scan to Download
Chapter 12 : Appendix B. OAuth2 grant types
Scan to Download
Chapter 1 Summary : Welcome to the
cloud, Spring
Overview of Microservices
Scan to Download
Understanding Microservices
Scan to Download
Spring Boot simplifies the development of microservices by
removing boilerplate code, enabling developers to create
applications quickly and easily. It allows developers to
package microservices without needing an external
application container. Spring Cloud complements Spring
Boot by providing tools for managing microservices in cloud
environments, including configuration management and
service discovery.
Learning Objectives
Scan to Download
Importance of Microservices in Modern
Development
Scan to Download
By the end of this chapter, readers are equipped with
foundational knowledge of microservices and the Spring
ecosystem, setting the stage for practical implementations in
upcoming chapters.
Scan to Download
Example
Key Point:Understanding Microservices
Example:Imagine you are a developer assigned a project
with a large team. Each team member is responsible for
different functionalities rather than a single monolithic
application. As you work on your microservice for user
authentication, you can develop, test, and deploy it
independently. This autonomy allows you to utilize
specific tools and technologies that best suit your
service's needs without interfering with other teams.
This modular approach not only enhances your
productivity but also drastically reduces the time needed
to bring new features to market, illustrating why
microservices are becoming essential in today’s
application development landscape.
Scan to Download
Chapter 2 Summary : Building
microservices with Spring Boot
Section Summary
Key Characteristics of
Microservices - Constrained: Each microservice addresses a specific business capability.
- Loosely Coupled: Services interact through standardized interfaces.
- Abstracted: Each microservice owns its data.
- Independent: Each can be deployed and updated without affecting others.
Cloud Architecture and Microservices are suitable for cloud applications due to their scalability and fault isolation.
Microservices
Roles in Microservices
Development 1. Architect: Focuses on service decomposition and interactions.
2. Developer: Implements microservices with an emphasis on maintainable code.
3. DevOps Engineer: Manages smooth deployment and operation of microservices.
Architectural Considerations
- Decompose business problems into domains.
- Establish service granularity to prevent overlapping responsibilities.
- Define service interfaces using REST principles.
Challenges to Avoid Avoid using microservices in small applications where complexity outweighs benefits.
Implementing Microservices Create a structured project setup with Maven and use Spring annotations for RESTful
with Spring Boot services.
DevOps Perspective Focus on operational readiness, service assembly, health monitoring, and apply
Twelve-Factor App principles.
Integration of Perspectives Collaboration among architects, developers, and DevOps is essential for building robust
microservices.
Scan to Download
Section Summary
Summary Microservices architecture enhances scalability through collaboration among all teams,
leveraging Spring Boot for efficient development.
Scan to Download
Independent
: Each can be deployed and updated without affecting others.
1.
Architect
: Designs the architecture, focusing on service decomposition
and interactions.
2.
Developer
: Implements microservices, prioritizing consistent and
maintainable code.
3.
DevOps Engineer
: Ensures smooth deployment and operational management
of microservices.
Scan to Download
Architectural Considerations
-
Decomposing Business Problems
: Identify discrete domains within business activities for
effective microservice mapping.
-
Establishing Service Granularity
: Aim for a balance between coarse and fine-grained services.
Avoid overlaps in responsibilities to maintain clarity.
-
Defining Service Interfaces
: Use REST principles to create intuitive and accessible
service interfaces.
Challenges to Avoid
Scan to Download
- Create a structured project setup using Maven and develop
a basic service as an example (e.g., a licensing microservice).
- Use Spring annotations for RESTful interface creation and
simplify code management.
DevOps Perspective
Integration of Perspectives
Summary
Scan to Download
hinges on effective collaboration among architects,
developers, and operational teams, leveraging Spring Boot as
a powerful framework for streamlined development and
deployment.
Scan to Download
Example
Key Point:Independence of Microservices
Example:Imagine you’re working on a customer
management application. You decide to build user
authentication as a separate microservice. This means
when you want to update the authentication logic, you
can do so without affecting the user data retrieval or
payment processing services. Each microservice can
evolve independently, enhancing your application’s
modularity and resilience.
Scan to Download
Chapter 3 Summary : Controlling your
configuration with Spring Cloud
configuration server
Topic Description
Separation of Configuration from Encourages developers to avoid hardcoding values, allowing for easier updates without
Code recompilation.
Importance of Configuration Vital for reducing human intervention during deployments, minimizing potential errors
Management and outages.
Principles for Effective Segregate, Abstract, Centralize, Harden - to manage configuration effectively.
Configuration Management
Architecture of Configuration Configuration data is loaded during the service bootstrapping phase from a centralized
Management repository.
Implementation Choices for Utilize open-source projects such as Etcd, Eureka, Consul, ZooKeeper, and Spring Cloud
Configuration Management configuration server.
Building the Spring Cloud Can be embedded in an existing application or started as new, requiring Maven and
Configuration Server application.yml setup.
Integrating with Spring Boot The licensing service must communicate with the Spring Cloud configuration server
Client based on the environment profile.
Protecting Sensitive Configuration Spring Cloud allows encryption of sensitive information such as database credentials.
Information
Setting Up Encryption Requires Oracle JCE jars, an encryption key as an environment variable, and sensitive
properties in encrypted format.
Client-Side Decryption of The licensing service is configured to decrypt properties on the client side, requiring
Properties specific properties and dependencies.
Summary Effective configuration management is crucial for cloud environments, enabling runtime
property injections and secure information handling.
Closing Thoughts Emphasizes the importance of configuration management for smooth operation and
scaling of microservices in cloud environments.
Scan to Download
This chapter covers several key topics related to
configuration management in cloud-based applications using
Spring Cloud configuration server.
Scan to Download
Chapter 4 Summary : On service
discovery
Scan to Download
Architecture of Service Discovery
Scan to Download
- Utilize different libraries (Spring Discovery Client, Spring
RestTemplate, Netflix Feign) to demonstrate how clients can
invoke services via Ribbon.
- Implement and register services with Eureka to enable
service discovery mechanisms.
Summary
Scan to Download
Example
Key Point:Dynamic Scalability
Example:Imagine you're running a popular online store
during a flash sale. As the number of customers spikes,
your microservices must seamlessly scale up to handle
the load. Thanks to service discovery, your application
can automatically locate new instances of services like
inventory management or payment processing without
requiring any manual intervention. You can focus on
ensuring that customer experience remains smooth and
uninterrupted, while the underlying infrastructure
dynamically adapts to the demands.
Scan to Download
Critical Thinking
Key Point:The limitation of traditional service
discovery methods compared to modern cloud-based
systems.
Critical Interpretation:While the summary emphasizes
the superiority of cloud-based service discovery, it's
important to acknowledge that traditional approaches
can still have relevance in certain contexts, particularly
in smaller or less complex applications. Critics argue
that moving entirely to cloud-based models without
consideration for existing infrastructure can lead to
unnecessary complexity and risks. For example, not all
services require the dynamic scaling and resilience that
cloud solutions offer, especially when conventional
methods can suffice and reduce operational burden (see
'Distributed Systems for Fun and Profit' by Mikito
Takada). Thus, readers should critically evaluate the
appropriateness of adopting cloud-based service
discovery depending on their specific architectural
needs and operational constraints.
Scan to Download
Chapter 5 Summary : When bad things
happen: client resiliency patterns with
Spring Cloud and Netflix Hystrix
Scan to Download
across service instances.
-
Circuit Breakers
: Prevent requests from overwhelming a failing service by
stopping calls after a certain failure threshold is reached.
-
Fallbacks
: Provide alternative actions when a service call fails instead
of raising exceptions.
-
Bulkheads
: Isolate different service calls by segregating them into
distinct thread pools to prevent one service failure from
impacting others.
Scan to Download
5.3 Enter Hystrix
Scan to Download
methods to execute when a service call fails, allowing
applications to continue functioning with limited data.
5.10 Summary
Scan to Download
Designing distributed applications requires integrating
resiliency patterns to manage service failures. Hystrix
provides flexible and powerful tools for implementing
client-side resiliency through circuit breakers, fallbacks, and
bulkhead patterns, ensuring applications remain functional
during service disruptions.
Scan to Download
Chapter 6 Summary : Service routing
with Spring Cloud and Zuul
Scan to Download
- Key features include static and dynamic routing,
authentication and authorization, metrics collection, and
logging.
Scan to Download
Chapter 7 Summary : Securing your
microservices
Overview
Scan to Download
OAuth2 Framework
Introduction to OAuth2
Scan to Download
Implementing Users and Roles
Authenticating Users
Scan to Download
- Discusses how to propagate OAuth2 tokens through
multiple service calls in a microservices architecture.
- Shows how to configure a Zuul gateway for token
forwarding.
Scan to Download
a service gateway, and limiting service access points.
- Recommends establishing a public and private API
designation to enforce least privilege security.
Chapter Summary
Scan to Download
Critical Thinking
Key Point:Complex Security Environment
Critical Interpretation:The chapter emphasizes the
criticality of security in microservices, focusing on
OAuth2 applications; however, this perception may
overlook alternative security frameworks and their
effectiveness. It's essential to recognize that the
complexities of security can vary widely across different
systems and organizations.
Key Point:Dependence on OAuth2
Critical Interpretation:While the chapter lauds OAuth2's
effectiveness, it’s important to question the reliability of
a singular framework in diverse environments. Other
authentication protocols may provide necessary
flexibility or features suited to specific use cases, as
indicated by sources like 'API Security in Action' by
Costas Ladas.
Scan to Download
Chapter 8 Summary : Event-driven
architecture with Spring Cloud Stream
Overview
Scan to Download
in microservices.
- EDA enhances the ability of microservices to quickly adapt
by listening to a stream of emitted events.
Scan to Download
- An example is provided to demonstrate how to implement a
message producer in the organization service and a consumer
in the licensing service.
- The process involves configuring dependencies for Spring
Cloud Stream and setting up message publication and
consumption using Kafka.
Scan to Download
Conclusion
Scan to Download
Chapter 9 Summary : Distributed
tracing with Spring Cloud Sleuth and
Zipkin
Overview
Key Topics
-
Using Spring Cloud Sleuth
: Injecting tracing information into service calls and
managing complex transactions.
Scan to Download
-
Log Aggregation
: Aggregating logs from multiple services into a searchable
database to make debugging easier.
-
Using OpenZipkin
: A visualization tool to understand user transactions across
multiple microservice calls.
-
Customizing Tracing Information
: Tailoring trace data and implementing correlation IDs to
link transactions across services.
Install
9.1.1 Bookey
Adding App to
Spring Cloud Unlock
Sleuth Full Text and
Audio
- Adding Maven dependency to services to enable tracing.
Scan to Download
Chapter 10 Summary : Deploying your
microservices
Section Content
Overview This chapter focuses on deploying microservices, emphasizing a well-structured pipeline for builds and
deployments, covering DevOps principles, Amazon infrastructure setup, and deployment processes.
Key Topics
Understanding DevOps for Microservices: Importance of DevOps for rapid deployment and
operational efficiency.
Amazon Infrastructure Configuration: Setup of core infrastructure using AWS for EagleEye services.
Manual Deployment Steps: Instructions for manually deploying services to AWS, configuring
services, and managing security groups.
Automated Deployment Pipeline Design: Design of a CI/CD pipeline using tools like Travis CI,
Maven, Docker, and AWS ECS.
Key Pipeline Characteristics:
Transitioning to Automation: Moving from manual to automated deployment for high throughput in
feature releases and bug fixes.
Build/Deployment Pipeline Architecture: Structured CI/CD approach emphasizing automated testing
and rollback capabilities.
Deployment
Steps
Setting Up Core Infrastructure: Distributing components across AWS services (e.g., RDS,
ElastiCache).
Creating and Configuring Services: Setting up PostgreSQL and Redis clusters on AWS.
Deploying Microservices on ECS: Using AWS ECS for container deployment and configuration.
Building and Pushing Docker Images: Utilizing Maven and Docker for compiling services and
pushing Docker images to Docker Hub.
Running Platform Tests After Deployment: Validating the functionality of deployed services in the
cloud environment.
Final This chapter emphasizes a robust build and deployment pipeline in microservices architecture, leading to rapid
Thoughts feature delivery and operational reliability through automation and standardization.
Scan to Download
Chapter 10: Deploying Your Microservices
Overview
-
Understanding DevOps for Microservices:
-
Amazon Infrastructure Configuration:
Scan to Download
- Outlines the setup of core infrastructure to support
microservices using Amazon Web Services (AWS) for
EagleEye services.
-
Manual Deployment Steps:
-
Automated:
Eliminate human intervention in build and deployment
processes.
-
Repeatable:
Ensure consistent operations to minimize bugs and errors.
Scan to Download
-
Complete:
Deliver a fully functional artifact ready for runtime.
-
Immutable:
Employ machine images that are never modified
post-creation.
-
Transitioning to Automation:
Deployment Steps
1.
Setting Up Core Infrastructure:
Scan to Download
- Split application components (e.g., databases, caching)
across AWS services such as RDS and ElastiCache for
efficiency.
2.
Creating and Configuring Services:
Scan to Download
deployed services in the cloud environment, ensuring
reliability.
Final Thoughts
Scan to Download
Chapter 11 Summary : Appendix A.
Running a cloud on your desktop
Software Requirements
-
Apache Maven
(Version 3.3.9) is the chosen build tool due to its prevalent
use in the Java ecosystem.
-
Java
(Version 1.8) is used for code compilation.
-
Docker
(Version 1.12 or later) is utilized for building and running
Docker container images.
Scan to Download
-
Git Client
(Version 2.8.4) is needed for sourcing the code from GitHub
repositories.
Scan to Download
Building the Docker Image
Scan to Download
Chapter 12 Summary : Appendix B.
OAuth2 grant types
Scan to Download
The Client Credentials grant is used when applications need
access without human involvement. The application
authenticates through its registered name and secret key. For
instance, data analytics jobs in the EagleEye application
operate independently while still adhering to security
requirements through this grant type.
Scan to Download
Best Quotes from Spring Microservices
in Action by John Carnell with Page
Numbers
View on Bookey Website and Generate Beautiful Quote Images
Scan to Download
database and don’t integrate with other applications are no
longer the norm.
6.The key items at play in each of these models are ones of
control: who’s responsible for maintaining the
infrastructure and what are the technology choices
available for building the application?
7.Small, Simple, and Decoupled Services = Scalable,
Resilient, and Flexible Applications.
8.Spring Boot is a re-envisioning of the Spring framework.
While it embraces core features of Spring, Spring Boot
strips away many of the 'enterprise' features found in
Spring and instead delivers a framework geared toward
Java-based, REST-oriented microservices.
9.Spring Cloud encapsulates several popular
cloud-management microservice frameworks under a
common framework and makes the use and deployment of
these technologies as easy to use as annotating your code.
10.Microservices are extremely small pieces of functionality
that are responsible for one specific area of scope.
Scan to Download
Chapter 2 | Quotes From Pages 102-159
1.The history of software development is littered
with the tales of large development projects that,
after an investment of millions of dollars and
hundreds of thousands of software developer
hours, somehow never managed to deliver
anything of value to their customers and literally
collapsed under their own complexity and weight.
2.The reality, though, is that software development isn’t a
linear process of definition and execution, but rather an
evolutionary one where it takes several iterations of
communicating with, learning from, and delivering to the
customer before the development team truly understands
the problem at hand.
3.Microservices should completely own their data structures
and data sources. Data owned by a microservice can only
be modified by that service.
4.It’s better to start broad with your microservice and refactor
to smaller services— It’s easy to go overboard when you
Scan to Download
begin your microservice journey and make everything a
microservice.
5.The client should never know the exact location of a
service. Instead, a microservice client should talk to a
service discovery agent that will allow the application to
locate an instance of a microservice without having to
know its physical location.
6.A microservice should communicate its health. This is a
critical part of your cloud architecture. Microservice
instances will fail, and clients need to route around bad
service instances.
7.The key takeaways for each of these perspectives are:
Focus on the natural contours of your business problem.
Describe your business problem domain and listen to the
story you’re telling. Target microservice candidates will
emerge.
8.Microservices are smaller in size and scope, but their use
introduces more moving parts in an application, especially
because microservices are distributed and running
Scan to Download
independently of each other.
Chapter 3 | Quotes From Pages 160-214
1.At one point or another, a developer will be forced
to separate configuration information from their
code.
2.Managing application configuration is critical for
microservices running in the cloud because microservice
instances need to be launched quickly with minimal human
intervention.
3.Segregate—We want to completely separate the services
configuration information from the actual physical
deployment of a service.
4.I can’t emphasize enough that the application configuration
data needs to be tracked and version-controlled because
mismanaged application configuration is a fertile breeding
ground for difficult-to-detect bugs and unplanned outages.
5.Not spending the time up front to figure out how you’re
going to do configuration management can have real (and
costly) downstream impacts.
Scan to Download
6.It’s critical that whatever solution you utilize can be
implemented to be highly available and redundant.
7.In a real-world deployment, I’d use a separate encryption
key for each environment I was deploying to and I’d use
random characters as my key.
8.Application configuration management might seem like a
mundane topic, but it’s of critical importance in a
cloud-based environment.
Scan to Download
Chapter 4 | Quotes From Pages 215-254
1.Service discovery is critical to microservice,
cloud-based applications for two key reasons.
2.The ability to quickly scale services without disrupting the
service consumers is an extremely powerful concept.
3.Service discovery helps abstract that these deployments are
occurring away from the service consumer.
4.A monolithic approach usually drives development teams
down the path of over-buying their capacity needs.
5.Service discovery needs to detect when a service instance
isn’t healthy and remove the instance from the list of
available services.
6.Using a centralized network infrastructure doesn’t
ultimately work as well because it doesn’t scale effectively
and isn’t cost-efficient.
7.The service discovery pattern is used to abstract away the
physical location of services.
Chapter 5 | Quotes From Pages 255-311
1.All systems, especially distributed systems, will
Scan to Download
experience failure. How we build our applications
to respond to that failure is a critical part of every
software developer’s job.
2.When a service crashes, it’s easy to detect that it’s no
longer there, and the application can route around it.
However, when a service is running slow, detecting that
poor performance and routing around it is extremely
difficult because degradation of a service can start out as
intermittent and build momentum.
3.The circuit breaker acts as a middle man between the
application and the remote service. In the previous
scenario, a circuit breaker implementation could have
protected Applications A, B, and C from completely
crashing.
4.A circuit breaker offers the ability for remote calls to fail
fast – when a remote service is experiencing a degradation,
the application will fail fast and prevent resource
exhaustion issues that normally shut down the entire
application.
Scan to Download
5.Fallbacks are a mechanism to provide a course of action
when a resource has timed out or failed. If you find
yourself using fallbacks to catch a timeout exception and
then doing nothing more than logging the error, then you
should probably use a standard try..catch block around your
service invocation.
6.The bulkhead pattern segregates remote resource calls
away from each other, isolating calls to a remote service
into their own thread pool. If one set of service calls is
failing, its failures shouldn’t be allowed to eat up all the
resources in the application container.
7.The Hystrix libraries are highly configurable, and can be
set at global, class, and thread pool levels. Hystrix supports
two isolation models: THREAD and SEMAPHORE.
Chapter 6 | Quotes From Pages 312-366
1.To implement this functionality, you’ll want these
attributes to be consistently enforced across all of
your services without the need for each individual
development team to build their own solutions.
Scan to Download
2.Unfortunately, for those of us working in a heavily
regulated industry, such as financial services or healthcare,
showing consistent and documented behavior in your
systems is often a key requirement for complying with
government regulations.
3.To solve this problem, you need to abstract these
cross-cutting concerns into a service that can sit
independently and act as a filter and router for all the
microservice calls in your application.
4.With a service gateway in place, your service clients never
directly call the URL of an individual service, but instead
place all calls to the service gateway.
5.The real power of Zuul comes into play when you want to
write custom logic that will be applied against all the
service calls flowing through the gateway.
6.While a servlet filter or Spring Aspect is localized to a
specific service, using Zuul and Zuul filters allows you to
implement cross-cutting concerns across all the services
being routed through Zuul.
Scan to Download
7.Building filters in Zuul is an extremely simple activity.
8.The ability to dynamically reload routes is useful because it
allows you to change the mapping of routes without having
to recycle the Zuul server(s).
9.Zuul allows you to implement custom business logic
through Zuul filters.
10.Once you’ve implemented the SpecialRoutesFilter, you
can see it in action by calling the licensing service.
Scan to Download
Chapter 7 | Quotes From Pages 367-421
1.A secure application involves multiple layers of
protection.
2.The real power behind OAuth2 is that it allows application
developers to easily integrate with third-party cloud
providers and do user authentication and authorization with
those services without having to constantly pass the user’s
credentials to the third-party service.
3.Web service security is an extremely complicated subject.
4.OAuth2 allows you to protect your REST-based services
across these different scenarios through different
authentication schemes called grants.
5.OAuth2 is a token-based authentication framework to
authenticate users.
6.Use HTTPS to encrypt all calls between services.
7.Every application that wants to call your services needs to
be registered with your OAuth2 authentication service.
Chapter 8 | Quotes From Pages 422-472
1.It’s message-driven, where we’re constantly
Scan to Download
sending and receiving messages.
2.What an EDA-based approach allows you to do is to build
highly decoupled systems that can react to changes without
being tightly coupled to specific libraries or services.
3.Loose coupling, durability, scalability, flexibility.
4.A messaging-based architecture can be complex and
requires the development team to pay close attention to
several key things, including message handling semantics.
5.Using messages in your microservices often means a mix
of synchronous service calls and processing in services
asynchronously.
Chapter 9 | Quotes From Pages 473-519
1.The microservices architecture is a powerful
design paradigm for breaking down complex
monolithic software systems into smaller, more
manageable pieces.
2.Because microservices are distributed by nature, trying to
debug where a problem is occurring can be maddening.
3.Fortunately, Spring Cloud Sleuth manages all this code
Scan to Download
infrastructure and complexity for you.
4.Consolidate logging and praise for the mundane.
5.A clean, concise picture can be worth more than a million
log entries.
6.Spring Cloud Sleuth allows you to seamlessly add tracing
information (correlation ID) to your microservice calls.
7.Cloud-based logging platforms are worth the money that’s
spent on them.
Scan to Download
Chapter 10 | Quotes From Pages 520-585
1.While most of this book has focused on designing,
building, and operationalizing Spring-based
microservices using the Spring Cloud technology,
we haven’t yet touched on how to build and deploy
microservices.
2.Creating a build and deployment pipeline might seem like a
mundane task, but in reality it’s one of the most important
pieces of your microservices architecture.
3.Velocity is the key word here because velocity implies that
little to no friction exists between making a new feature or
fixing a bug and getting your service deployed.
4.Lead times for deployment should be minutes, not days.
5.Automated—When you build your code, there should be
no human intervention in the build and deployment
process, particularly in the lower environments.
6.The provisioning of your machine images needs to be
completely automated via scripts and kept under source
control with the service source code.
Scan to Download
7.Remember, one of the core tenets of microservice
development is pushing complete operational responsibility
for the service down to the developers.
8.Immutable—Once the machine image containing your
service is built, the runtime configuration of the image
should not be touched or changed after the image has been
deployed.
9.The goal of this chapter is to provide you with the working
pieces of a build/deployment pipeline so that you can take
these pieces and tailor them to your specific environment.
10.The success of your microservice architecture depends on
more than just the code involved in the service.
Chapter 11 | Quotes From Pages 586-600
1.The first goal was make sure that the code
examples were consumable and easy to set up.
2.The second goal was for each chapter to be completely
standalone so that you could pick any chapter in the book
and have a complete runtime environment available.
3.I can build a complete runtime environment on the desktop
Scan to Download
that includes the application services and all the
infrastructure needed to support the services.
4.Using Docker, I can build a complete runtime environment
on the desktop that includes the application services and all
the infrastructure needed to support the services.
5.I’ve purposely avoided more sophisticated Docker
orchestration tools such as Kubernetes or Mesos to keep
the chapter examples straightforward and portable.
6.It becomes extremely simple to build the source code.
7.Next, your Dockerfile will make a directory for the
licensing service’s executable jar file and then copy the jar
file from the local file system to a directory that was
created on the Docker image.
8.Docker Compose is a service orchestration tool that allows
you to define services as a group and then launch together
as a single unit.
9.Every service will print its standard out to the console.
10.If you want to make your Postgres database persistent
between the starting and stopping of containers, I’d point
Scan to Download
you to the Postgres Docker notes.
Chapter 12 | Quotes From Pages 601-616
1.Unfortunately, the real world is never simple.
With the interconnected nature of the web and
cloud-based applications, users have come to
expect that they can securely share their data and
integrate functionality between different
applications owned by different services.
2.Fortunately, OAuth2 is a flexible authorization framework
that provides multiple mechanisms for applications to
authenticate and authorize users without forcing them to
share credentials.
3.The authorization code grant is by far the most complicated
of the OAuth2 grants, but it’s also the most common flow
used because it allows different applications from different
vendors to share data and services without having to
expose a user’s credentials across multiple applications.
4.The implicit grant is the only grant type where the OAuth2
access token is directly exposed to a public client (web
Scan to Download
browser).
5.The refresh token flow allows an application to get a new
access token without forcing the user to re-authenticate.
Scan to Download
Spring Microservices in Action
Questions
View on Bookey Website
Scan to Download
2.Question
How do Spring Boot and Spring Cloud contribute to
building microservices?
Answer:Spring Boot simplifies the development process by
allowing Java developers to quickly create stand-alone,
production-ready applications with minimal configuration. It
uses annotations to define application behavior, significantly
reducing the code required compared to traditional Java
applications. Spring Cloud adds capabilities for the
operational aspects of microservices, such as service
discovery, configuration management, load balancing, and
circuit breaker patterns, making it easier for developers to
build and manage cloud-native applications.
3.Question
What are the key characteristics of a microservice
architecture?
Answer:Key characteristics include:
1. **Independent deployment**: Each microservice can be
deployed independently.
Scan to Download
2. **Decoupling**: Microservices are loosely coupled,
enabling teams to develop and scale services independently.
3. **Domain specificity**: Each service should manage a
specific business domain.
4. **Inter-service communication**: Microservices
communicate across networks using lightweight protocols
like HTTP/JSON.
4.Question
Why might a company choose to migrate from a
monolithic application to a microservices architecture?
Answer:A company may choose this shift to enhance agility,
allowing for rapid development and deployment cycles.
Microservices support scalability by enabling specific
services to scale independently based on demand. They also
improve resilience; if one service fails, it doesn't impact the
availability of others, creating a more robust application
overall.
5.Question
What are the advantages of deploying microservices to
the cloud?
Scan to Download
Answer:Deploying microservices to the cloud offers several
advantages:
1. **Elasticity**: Resources can be scaled up or down
quickly in response to demand.
2. **Cost-efficiency**: You only pay for the resources you
use, optimizing operational costs.
3. **High availability and redundancy**: Cloud providers
typically offer geographic redundancy, decreasing the chance
of downtime.
6.Question
What challenges do microservices introduce that
developers must address?
Answer:While microservices offer many benefits, they also
introduce challenges such as:
1. **Complexity in management**: Managing multiple
microservices requires orchestration and monitoring tools.
2. **Service communication**: Ensuring reliable
communication can be difficult, especially with a high
number of services.
Scan to Download
3. **Data integrity**: Maintaining data consistency across
services may require implementing distributed transactions
or event sourcing solutions.
7.Question
How does Spring Cloud simplify the operational
management of microservices?
Answer:Spring Cloud provides robust tools to help manage
the complexity associated with microservices. It integrates
features for service discovery, configuration management,
and circuit breakers, enabling developers to focus on writing
business logic rather than managing infrastructure. This
enhances agility and speed in deploying applications,
allowing teams to rapidly iterate on services.
8.Question
How does the 'Carnell Monkey Test' relate to evaluating a
software framework like Spring Boot?
Answer:The 'Carnell Monkey Test' suggests that if a
developer can quickly understand and utilize a framework
(like Spring Boot) within ten minutes, it indicates the
Scan to Download
framework's usability and design effectiveness. Spring Boot
aims to be intuitive and straightforward, thus passing this
informal test for developers.
9.Question
What are the various cloud deployment models
mentioned, and how do they differ?
Answer:The chapter outlines three primary cloud models:
1. **Infrastructure as a Service (IaaS)**: Provides the
infrastructure needed but requires users to manage their own
applications and data.
2. **Platform as a Service (PaaS)**: Provides a platform
allowing users to develop, run, and manage applications,
abstracting the infrastructure.
3. **Software as a Service (SaaS)**: Delivers software
applications over the Internet, managed fully by the service
provider.
10.Question
What kinds of patterns are essential in microservice
development and management?
Scan to Download
Answer:Essential microservice patterns include:
1. **Core development patterns**: Techniques for building
and designing microservices.
2. **Routing patterns**: Managing how requests are routed
to the appropriate services.
3. **Client resiliency patterns**: Techniques for ensuring
services remain operational despite faults.
4. **Security patterns**: Protocols for authenticating and
authorizing service requests.
5. **Logging and tracing patterns**: Methods for tracking
and aggregating logs across distributed services.
Chapter 2 | Building microservices with Spring
Boot| Q&A
1.Question
What are the key characteristics of a microservice-based
architecture?
Answer:Microservice-based architectures have
several core characteristics: they are constrained to
a single responsibility and narrow in scope, loosely
coupled, independent (can be compiled and deployed
Scan to Download
separately), and have abstracted data ownership.
Each microservice focuses on doing one thing well,
interacts through non-proprietary interfaces, and
has complete control over its own data.
2.Question
Why is it important to consider when not to use
microservices?
Answer:Microservices introduce complexity and operational
requirements that may not be justified for smaller
applications or those with a limited user base. If your
application does not require high scalability, fault isolation,
or rapid feature updates, it might be more efficient to use a
monolithic architecture instead.
3.Question
How can architects effectively decompose a business
problem into microservices?
Answer:Architects should break down complex business
problems into manageable parts by identifying discrete
domains of activity, looking for common nouns and verbs
Scan to Download
that indicate core business logic, and consider the
relationships and interactions between these domains to
define service boundaries.
4.Question
What is the importance of establishing clear service
interfaces in a microservice architecture?
Answer:Establishing clear and intuitive service interfaces is
crucial for ease of use and understanding for developers.
Services should follow REST principles, utilize standard
HTTP methods, and have well-defined URIs to facilitate
interaction and integration with other components.
5.Question
What considerations should be made regarding
granularity when designing microservices?
Answer:Granularity is key to successful microservice design.
Services should neither be too coarse (with too many
responsibilities) nor too fine (leading to excessive
interdependencies). Starting with broader services and
refactoring into smaller ones is often a better approach than
Scan to Download
beginning too small, as this helps maintain manageability
and clarity in a complex system.
6.Question
How does Spring Boot support the development of
microservices?
Answer:Spring Boot simplifies the development of
microservices by reducing boilerplate code and configuration
requirements, allowing developers to build RESTful services
quickly with minimal setup. It provides built-in features for
creating executable JAR files, managing dependencies, and
handling logging and health checks.
7.Question
What operational principles should a DevOps engineer
consider when managing microservices?
Answer:A DevOps engineer should focus on packaging and
deploying microservices as independent artifacts, ensuring
they are configurable without human intervention,
maintaining transparency for clients during service
discovery, and communicating health status to monitor and
Scan to Download
manage service reliability.
8.Question
Why is it important to integrate perspectives from
architects, developers, and DevOps engineers in
microservice development?
Answer:Integrating these perspectives ensures a
well-rounded approach to building microservices. Architects
focus on the big picture and service boundaries, developers
handle implementation and logical design, while DevOps
engineers ensure operational efficiency and reliability. This
cohesive vision leads to successful microservice architecture.
Chapter 3 | Controlling your configuration with
Spring Cloud configuration server| Q&A
1.Question
Why is it important to separate configuration from
application code in microservices?
Answer:Separating configuration from application
code allows developers to modify application
settings without recompiling or redeploying the
application. This is critical in environments with
Scan to Download
dynamic scaling, where microservices might need to
be launched and adjusted quickly. It minimizes
configuration drift and potential outages, enhances
the ability to adapt to scalability challenges, and
simplifies maintenance.
2.Question
What are the four principles for managing application
configuration in microservices?
Answer:The four principles are: 1. **Segregate** -
completely separate configuration from application
deployment. Configuration should be passed as environment
variables or read from a centralized repository. 2.
**Abstract** - access configuration through a service
interface rather than hardcoding access methods. 3.
**Centralize** - minimize the number of repositories for
storing configuration to simplify management. 4.
**Harden** - ensure that configuration storage is highly
available and redundant.
3.Question
Scan to Download
Describe a scenario illustrating the consequences of poor
configuration management.
Answer:In a financial services company, a poorly managed
configuration strategy resulted in 12,000 configuration files
for 120 applications spread across multiple servers. This led
to failure in completing a crucial upgrade and cost the
company a million dollars in efforts, illustrating how
neglecting configuration management can lead to chaos and
significant financial losses.
4.Question
How does Spring Cloud configuration server improve
management of application configuration?
Answer:Spring Cloud configuration server allows centralized
management of application properties, supports multiple
backends (like Git), and offers the ability to encrypt sensitive
information. Additionally, it provides a systematic way for
microservices to access their configuration through a REST
interface, making it easier to manage environmental
differences and upgrades while keeping sensitive data secure.
Scan to Download
5.Question
What measures can be taken to protect sensitive
configuration information in microservices?
Answer:Using Spring Cloud Config, sensitive properties can
be encrypted using symmetric or asymmetric encryption. It is
crucial to not store sensitive information in plain text and
instead rely on environment variables and secure storage
mechanisms. Additionally, implementing client-side
decryption ensures that sensitive data is not exposed during
retrieval.
6.Question
What should developers be cautious about when
managing configuration for microservices?
Answer:Developers should ensure that configuration data is
version-controlled and properly managed to avoid bugs and
outages. They should also be cautious about how sensitive
data is stored and ensure that decryption occurs on the
client-side rather than exposing sensitive information through
REST calls from configuration services. Moreover, not all
Scan to Download
configuration servers support dynamic refresh of properties,
which can complicate real-time updates.
7.Question
How does the integration of Spring Cloud configuration
server with Git enhance configuration management?
Answer:Integrating Spring Cloud configuration server with
Git allows for version control of configuration properties,
easy collaboration, and automated deployment pipelines. It
eliminates the need to manually manage configuration files
while providing a reliable history of changes, thereby
simplifying the rollback process in case of errors and
ensuring consistent application behavior across
environments.
8.Question
Explain the significance of the @RefreshScope annotation
in Spring Cloud configuration.
Answer:The @RefreshScope annotation allows Spring Boot
applications to refresh their configuration properties
dynamically at runtime without restarting the application.
Scan to Download
This is particularly useful in cloud environments where
configuration changes can happen frequently and helps
ensure that instances of microservices have the latest
configuration values.
9.Question
What common pitfalls should developers avoid when
handling configuration in cloud-based applications?
Answer:Developers should avoid hardcoding configuration
values, neglecting version control for configuration files,
failing to encrypt sensitive information, and relying solely on
filesystem-based configurations in cloud deployments. They
should also be cautious about the potential for configuration
drift due to manual interventions in the deployment process.
10.Question
Why is it critical for applications in cloud environments
to be immutable?
Answer:Immutability in cloud environments ensures that
once a service is deployed, it does not change between
environments. This approach reduces risks of configuration
Scan to Download
drift, ensures consistency, and enhances reliability, as
applications can be promoted through staging and production
without manual reconfiguration, making it easier to replicate
environments and troubleshoot issues.
Scan to Download
Chapter 4 | On service discovery| Q&A
1.Question
What is service discovery in microservices architecture?
Answer:Service discovery is the process by which
microservices can locate each other in a distributed
environment. It allows applications to find the
network locations of service instances dynamically,
eliminating the need for hardcoding locations or
relying on static configurations.
2.Question
Why is service discovery important in cloud-based
applications?
Answer:Service discovery is crucial because it allows for
rapid scaling of services without disrupting consumers. It
abstracts the physical locations of service instances and
provides resilience by enabling the automatic routing around
unhealthy instances.
3.Question
How does service discovery improve the resiliency of
applications?
Scan to Download
Answer:Service discovery improves application resiliency by
removing unhealthy service instances from the pool of
available services. This minimizes downtime and ensures
that service consumers always interact with healthy
instances.
4.Question
What are the pros and cons of using service discovery
versus traditional load balancers?
Answer:Pros of service discovery include dynamic instances
registration, resilience to failures, and horizontal scalability.
Cons include added complexity and the necessity of a
reliable discovery mechanism which might introduce points
of failure if not managed well.
5.Question
What are some challenges with traditional load balancers
in cloud environments?
Answer:Traditional load balancers can act as single points of
failure, may have limited horizontal scalability due to
centralized architecture, and often require static
Scan to Download
configurations which are not ideal in a dynamic, cloud
environment.
6.Question
How can service discovery systems facilitate scaling in
microservices?
Answer:Service discovery allows for horizontal scaling by
enabling quick addition or removal of service instances
without affecting consumers. When a new instance registers,
it becomes available automatically, allowing the system to
adapt fluidly to load changes.
7.Question
What characteristics should a reliable service discovery
mechanism have in a cloud environment?
Answer:A reliable service discovery mechanism should be
highly available, support peer-to-peer communication,
dynamically load balance requests, have built-in resilience
and fault tolerance, and allow for local caching of service
information.
8.Question
What role does client-side load balancing play in service
Scan to Download
discovery?
Answer:Client-side load balancing caches service instance
locations, enabling clients to make calls without querying the
discovery service for every request. This reduces latency and
enhances performance by allowing clients to balance requests
among available instances.
9.Question
How can Spring Cloud and Netflix’s Eureka facilitate
service discovery?
Answer:Spring Cloud and Netflix’s Eureka provide an
elegant solution for service discovery by allowing
microservices to register themselves and discover instances
of other services, while also supporting client-side load
balancing with minimal configuration.
10.Question
What are the benefits of using Netflix’s Ribbon in
conjunction with Eureka?
Answer:Using Netflix's Ribbon alongside Eureka enhances
performance through client-side load balancing. It allows
Scan to Download
automatic caching of service locations, makes routing
decisions, and provides fault tolerance, ensuring resilient
communication between services.
11.Question
How does registration and deregistration of services work
in a service discovery pattern?
Answer:In a service discovery pattern, services register their
instance information with a discovery agent on startup and
deregister when shutting down. This dynamic management
facilitates real-time updates to service availability.
12.Question
What steps are involved in setting up a Spring Cloud
Eureka service?
Answer:To set up a Spring Cloud Eureka service, one needs
to create a Spring Boot application, add Eureka
dependencies, configure application properties for the Eureka
server, and enable the @EnableEurekaServer annotation in
the main application class.
13.Question
How does a Spring Boot application interact with Eureka
Scan to Download
after registration?
Answer:After registration with Eureka, a Spring Boot
application can use its service ID to retrieve other services
and utilize client-side load balancing via Ribbon or Feign to
communicate with them.
14.Question
What common mechanisms are available in Spring Cloud
to invoke services registered with Eureka?
Answer:Common mechanisms for invoking services
registered with Eureka include the Spring DiscoveryClient
interface, Spring Cloud's Ribbon-backed RestTemplate, and
Netflix's Feign client for easier REST service interaction.
15.Question
What are the implications of using Feign for REST
service interactions in microservices?
Answer:Using Feign simplifies REST service calls by
allowing developers to define interfaces with annotations
rather than boilerplate code. Feign automatically handles
service discovery, by dynamically generating the necessary
Scan to Download
HTTP calls to service instances.
16.Question
How can health monitoring contribute to effective service
discovery?
Answer:Health monitoring is essential for service discovery
as it allows the system to track the health of service
instances. Unhealthy instances can be removed from service
registries, preventing clients from experiencing outages and
improving overall system reliability.
Chapter 5 | When bad things happen: client
resiliency patterns with Spring Cloud and Netflix
Hystrix| Q&A
1.Question
What are client-side resiliency patterns and why are they
important in microservices?
Answer:Client-side resiliency patterns are strategies
designed to protect applications from remote service
failures, helping them to 'fail fast' and conserve
resources when a service is degraded or failing.
These patterns include client-side load balancing,
Scan to Download
circuit breakers, fallbacks, and bulkheads, which
work together to prevent problems from affecting
upstream consumers. Their importance lies in their
ability to prevent cascading failures in a
microservices architecture, ensuring that one poorly
performing service does not bring down multiple
applications, thereby maintaining overall system
stability.
2.Question
How does the circuit breaker pattern function? Can you
provide an analogy?
Answer:The circuit breaker pattern acts like an electrical
circuit breaker: it monitors calls to a remote service and, if it
detects that the calls are failing too often or taking too long,
it 'trips' to prevent future calls to that service. Instead of
allowing the system to hang or crash while waiting for a
response, it fails fast, allowing applications to respond
gracefully to issues. This analogy emphasizes the protective
nature of the circuit breaker, isolating the problematic
Scan to Download
interaction to maintain the integrity of the system.
3.Question
What is the purpose of fallback processing in client
resiliency patterns?
Answer:Fallback processing provides an alternative path or
solution when a remote service call fails, thereby enhancing
user experience by preventing error displays. For example, if
a user requests personalized recommendations from a service
that fails, a fallback might return a general list based on
average purchases instead. This mechanism ensures
continuity of service even when the primary service
encounters problems.
4.Question
Describe the bulkhead pattern and its significance in
microservices. How does it differ from traditional
resource management?
Answer:The bulkhead pattern segregates remote resource
calls into separate thread pools, similar to compartments in a
ship that contain water leaks. This isolation prevents a failure
in one service from exhausting all resources in the
Scan to Download
application, which can lead to catastrophic outages. Unlike
traditional resource management, which may allow resource
overload from any service, the bulkhead approach maintains
stability by containing issues within designated boundaries.
5.Question
Why is it crucial to tune Hystrix configurations such as
timeout values and request volume thresholds?
Answer:Tuning Hystrix configurations is essential to
optimize application performance and responsiveness under
load. Setting appropriate timeout values ensures that slow
services do not block resources, while adjusting request
volume thresholds allows the circuit breaker to accurately
assess when to trip. Misconfigured thresholds can lead to
unnecessary failures or service downtime, which can degrade
customer experience and erode trust in the application.
6.Question
What is a key challenge when implementing circuit
breakers in distributed systems, and how does Hystrix
address this?
Answer:A key challenge is ensuring that services can detect
Scan to Download
when they are degrading and return appropriate responses
before causing resource exhaustion. Hystrix addresses this by
providing a built-in circuit breaker that automatically detects
failure patterns, counts errors, and trips the circuit to prevent
excessive load. This proactive response helps maintain
system health and allows for graceful degradation without
overwhelming other components.
7.Question
Explain how Hystrix's concurrency strategy affects
performance and when to choose THREAD vs
SEMAPHORE isolation models.
Answer:Hystrix's concurrency strategy allows for two
isolation levels: THREAD and SEMAPHORE. Thread
isolation provides complete separation between service calls,
protecting the overall application from failures in specific
calls but at a higher resource cost. In contrast, SEMAPHORE
is more lightweight and shares contexts, which is efficient for
high-volume scenarios but can risk unpredictable behavior if
the parent thread is interrupted. Choosing between them
Scan to Download
depends on the specific performance needs and risk
management strategy of the application.
Chapter 6 | Service routing with Spring Cloud and
Zuul| Q&A
1.Question
What are the main advantages of using a service gateway
in a microservices architecture?
Answer:A service gateway simplifies and centralizes
management of service calls. It allows for consistent
implementation of cross-cutting concerns like
security, logging, and tracking across all
microservices, helping to maintain uniform behavior
and compliance with regulations. Additionally, it
abstracts away the complexities of individual service
endpoints, enabling clients to interact with a single
URL.
2.Question
How does Zuul facilitate service discovery and routing in
a microservices environment?
Answer:Zuul integrates seamlessly with service discovery
Scan to Download
tools like Eureka, automatically mapping service IDs to their
respective service instances. This allows developers to focus
on building individual services while Zuul handles the
routing of requests to the appropriate service instance,
significantly reducing operational complexity.
3.Question
What are the implications of relying on a centralized
service gateway like Zuul?
Answer:Relying on a centralized service gateway can create
a single point of failure if not properly implemented. It could
also become a performance bottleneck, thus requiring load
balancing and careful design to ensure scalability and
resilience within the architecture.
4.Question
In what scenarios would it be beneficial to use dynamic
routing with Zuul?
Answer:Dynamic routing is particularly valuable for features
like A/B testing, where a subset of users may be routed to
different versions of a service. This allows teams to test new
Scan to Download
features on a limited audience before a broader rollout,
enabling data-driven decision-making.
5.Question
How do Zuul filters enhance the functionality of a service
gateway?
Answer:Zuul filters allow developers to implement custom
logic for handling requests and responses, providing hooks
for before (pre-filters) and after (post-filters) service calls.
This capability enables operations such as security checks,
logging, and response modification to be consistently applied
across all service interactions.
6.Question
What technologies does Zuul rely on to manage service
timeouts effectively?
Answer:Zuul utilizes Netflix's Hystrix and Ribbon to manage
service timeouts. Developers can configure both Hystrix
timeouts for service processing and Ribbon timeouts for
network requests, enhancing the resilience and
responsiveness of the gateway.
Scan to Download
7.Question
What is the significance of correlation IDs in
microservices, and how are they handled in Zuul?
Answer:Correlation IDs are crucial for tracking requests
across multiple microservices, enabling comprehensive
logging and auditing. In Zuul, a pre-filter generates a unique
correlation ID for each incoming request, which is then
propagated through downstream service calls and injected
back into the HTTP response for client access.
8.Question
How does Zuul allow for the customization of route
mappings for services?
Answer:Zuul allows developers to define route mappings
manually in configuration files, providing flexibility to
customize how services are accessed. It also supports
automatic mapping via service IDs registered in Eureka,
streamlining the process of managing routes as service
instances change.
9.Question
What challenges might arise from using common libraries
Scan to Download
across microservices, and how can these be overcome?
Answer:Using common libraries can create tight coupling
between services, leading to difficulties in maintaining
independence. To mitigate these issues, it's recommended to
limit shared libraries to infrastructural concerns while
allowing business logic to reside in individual services,
thereby preserving service autonomy.
10.Question
In what ways can Zuul contribute to regulatory
compliance in heavily regulated industries?
Answer:Zuul helps enforce consistent security policies,
logging practices, and tracking mechanisms, which are
essential for demonstrating compliance with industry
regulations. By centralizing these cross-cutting concerns,
organizations can more easily manage and audit
compliance-related behavior across their microservices.
Scan to Download
Chapter 7 | Securing your microservices| Q&A
1.Question
Why does security matter in a microservice environment?
Answer:Security is crucial in a microservice
environment to protect sensitive data, maintain user
trust, and prevent unauthorized access. Each
microservice can potentially expose vulnerabilities;
hence, layers of security need to be implemented to
authenticate users and authorize their access.
2.Question
What are the main components of OAuth2?
Answer:OAuth2 breaks down security into four main
components: a protected resource (the microservice itself), a
resource owner (the user or application owner), an
application (the client that calls the service), and the OAuth2
authentication server (the intermediary for authentication
between the application and resource).
3.Question
How does OAuth2 help with user authentication and
authorization across multiple services?
Scan to Download
Answer:OAuth2 allows users to authenticate once and
receive a token that can be used across various microservices
without needing to present credentials each time,
streamlining the process and enhancing security.
4.Question
What is the role of Spring Cloud security in implementing
OAuth2?
Answer:Spring Cloud security provides out-of-the-box
support for OAuth2, making it easier for developers to secure
their Spring-based microservices with authentication and
authorization features.
5.Question
What is the importance of using a services gateway in
microservices architecture?
Answer:A services gateway acts as a gatekeeper, controlling
access to microservices, providing a single entry point for all
service calls, enforcing security protocols, and allowing for
central management of traffic.
6.Question
How should microservices manage user credentials and
Scan to Download
roles according to the chapter?
Answer:Microservices should leverage in-memory data
stores or relational databases to manage user credentials and
roles, ensuring that these systems can authenticate users and
enforce authorization rules effectively.
7.Question
What are some best practices for securing microservices
beyond OAuth2?
Answer:Implement HTTPS for all service communications,
zone services into public and private APIs, use a services
gateway for access control, and limit the attack surface by
restricting unnecessary network ports.
8.Question
Why is it beneficial to use JavaScript Web Tokens (JWT)
over traditional OAuth2 tokens?
Answer:JWTs offer advantages such as being small and
easily transmittable, cryptographically signed (ensuring
validity), self-contained (carrying necessary user info), and
extensible (allowing additional fields), making them robust
Scan to Download
for modern web applications.
Chapter 8 | Event-driven architecture with Spring
Cloud Stream| Q&A
1.Question
What is event-driven architecture (EDA) and why is it
significant for microservices?
Answer:Event-driven architecture (EDA) is a
software architecture pattern that uses events to
trigger and communicate between different
components of a system. It enables services to react
to events asynchronously, allowing for more
flexibility and scalability in microservices. EDA
facilitates loose coupling between services, which is
key for rapidly evolving applications.
2.Question
What is the main advantage of using a messaging
approach in microservices?
Answer:The main advantage of using a messaging approach
is loose coupling between services. Messages allow different
microservices to communicate without being directly aware
Scan to Download
of each other, reducing dependencies and potential points of
failure.
3.Question
How can Spring Cloud Stream simplify event processing
in microservices?
Answer:Spring Cloud Stream simplifies event processing by
abstracting away the complexities of the underlying
messaging systems (like Kafka or RabbitMQ) and allowing
developers to focus on defining message routes and formats
using simple annotations.
4.Question
What are the key components in the Spring Cloud Stream
architecture for message passing?
Answer:The key components are: Source (to publish
messages), Channel (the abstraction over queues), Binder
(that connects the application to the message platform), and
Sink (to consume messages).
5.Question
What considerations should be taken into account when
defining the data to include in messages?
Scan to Download
Answer:When defining the data in messages, consider the
amount of data needed, the relevance of stale data, and
always include a correlation ID for tracking purposes to
maintain consistency and accountability throughout the
service interactions.
6.Question
Can you explain the benefits of using a messaging queue
as an intermediary in microservices?
Answer:Using a messaging queue offers several benefits
including durability (messages aren’t lost if the consumer is
down), scalability (more consumers can be added to handle
increased load), flexibility (new consumers can be added
without impacting existing services), and loose coupling of
services.
7.Question
What challenges might arise with a messaging
architecture and how can they be addressed?
Answer:Challenges include ensuring the order of message
processing, handling message failures or exceptions, and
Scan to Download
managing message visibility. These can be addressed through
careful design of message handling semantics, implementing
retries with exponential backoff, and using correlation IDs
for tracking.
8.Question
What is Redis and how is it used in conjunction with
Spring Cloud Stream in microservices?
Answer:Redis is a high-performance key-value store used as
a database, cache, or message broker. In the context of
Spring Cloud Stream, Redis can be used as a distributed
cache to store and retrieve data quickly, improving
performance while reducing load on primary data stores.
9.Question
Describe a practical application of distributed caching in
microservices using Spring Cloud Stream. How does it
enhance performance?
Answer:In a practical setup, the licensing service can check a
Redis cache for organization data associated with a license. If
the cache does not contain the data, it queries the
organization service and updates the cache. This reduces the
Scan to Download
number of costly database accesses, enhances data retrieval
speeds, and improves overall application performance.
10.Question
How does Spring Cloud Stream enable flexibility in
adding new functionality to microservices?
Answer:Spring Cloud Stream allows for flexibility because
new functionalities can be introduced simply by adding new
message consumers that listen to existing messages. This
decouples enhancements from the logic of existing services,
facilitating easier updates and scalability.
Chapter 9 | Distributed tracing with Spring Cloud
Sleuth and Zipkin| Q&A
1.Question
What is the purpose of using Spring Cloud Sleuth in a
microservices architecture?
Answer:Spring Cloud Sleuth facilitates the tracing
of transactions across multiple microservices by
injecting correlation IDs into service calls. This
allows developers to track the flow of requests,
making it easier to identify where errors occur and
Scan to Download
to understand performance bottlenecks.
2.Question
How does log aggregation enhance the debugging of
microservices?
Answer:Log aggregation compiles logs from multiple
services into a unified database, making it easier to search,
filter, and analyze log data across different service instances.
This centralization simplifies the identification of issues
compared to checking logs on individual servers.
3.Question
Describe how correlation IDs help in tracing distributed
transactions.
Answer:Correlation IDs are unique identifiers assigned to
transactions when initiated. As transactions progress through
various services, these IDs are propagated, allowing
developers to link logs and trace the transaction from start to
finish across multiple microservices.
4.Question
What is Zipkin, and how does it relate to Spring Cloud
Sleuth?
Scan to Download
Answer:Zipkin is an open-source distributed tracing system
that provides a visual representation of transaction flows
across microservices. It integrates with Spring Cloud Sleuth,
which captures tracing data and sends it to Zipkin for
visualization, enabling better insight into service interactions
and performance metrics.
5.Question
Why might a developer choose a cloud-based logging
solution over an on-premise one?
Answer:Cloud-based logging solutions are typically easier to
set up and scale, require less infrastructure management, and
can provide immediate access to logs without the need for
substantial on-premise servers, making them more
convenient for most organizations.
6.Question
What steps are involved in setting up tracing with Spring
Cloud Sleuth and Zipkin?
Answer:Setting up tracing involves adding the necessary
dependencies for Spring Cloud Sleuth and Zipkin to your
Scan to Download
microservices, configuring the services to point to the Zipkin
server, installing the Zipkin server, and defining a sampling
strategy for how often tracing data should be sent.
7.Question
What kind of tracing data can you visualize using Zipkin?
Answer:Using Zipkin, you can visualize the flow of
transactions across microservices, view response times for
each service involved, identify performance bottlenecks, and
monitor dependencies between different services.
8.Question
How can custom spans enhance tracing for third-party
services?
Answer:Custom spans allow you to manually define
segments of tracing for operations performed by third-party
services, such as database calls or external API requests. This
provides detailed timing information and enhances visibility
into how these calls affect overall performance.
9.Question
What lessons can be drawn from the importance of
logging strategies in microservice development?
Scan to Download
Answer:Defining logging strategies early in development is
crucial, as implementing them later can be tedious and
error-prone. Strong logging frameworks help trace issues
effectively, aid in performance monitoring, and support quick
resolutions during service incidents.
10.Question
How does Spring Cloud Sleuth contribute to the
automation of tracing?
Answer:Spring Cloud Sleuth automates the instrumentation
needed for tracing by automatically generating correlation
IDs, injecting them into log statements, and propagating
them throughout service calls, thus removing the complexity
of manually handling tracing data.
Scan to Download
Chapter 10 | Deploying your microservices| Q&A
1.Question
Why is automating the deployment process in
microservices architecture important?
Answer:Automating the deployment process is
crucial because it enables rapid delivery of features
and fixes with minimal friction. In a microservices
architecture, where services can be developed and
deployed independently, minimizing lead times for
deployment to minutes instead of days is essential
for maintaining agility and responsiveness to
change.
2.Question
What are the key characteristics of a build and
deployment pipeline for microservices?
Answer:A well-designed build and deployment pipeline
should be automated, repeatable, and complete. Automation
eliminates human errors, repeatability ensures consistent
results with every build, and a complete pipeline produces
Scan to Download
fully configured virtual machines or container images ready
for deployment.
3.Question
How does treating infrastructure as code benefit
microservices?
Answer:Treating infrastructure as code allows developers to
version control their configuration scripts alongside
application code. This practice enhances collaboration among
development and operations teams (DevOps), ensures
consistency in environments, and simplifies the automation
process.
4.Question
What role does immutability play in deployment
pipelines?
Answer:Immutability in deployment pipelines ensures that
once a machine image is created, it cannot be altered. All
changes require rebuilding and redeploying a new image.
This practice helps prevent configuration drift and ensures
that every environment is consistent, enhancing reliability
Scan to Download
and simplifying troubleshooting.
5.Question
What testing strategies are essential in a deployment
pipeline?
Answer:Key testing strategies include unit tests, integration
tests, and platform tests. Unit tests verify individual
components; integration tests assess the interactions between
them, and platform tests check the entire application running
in a live environment, ensuring overall functionality and
performance.
6.Question
How can teams ensure traceability in their deployment
pipeline?
Answer:Traceability can be achieved by tagging builds and
their corresponding Docker images with unique identifiers
during the build process. This allows teams to link each
deployment back to the specific version of the source code
and the build job that produced it, facilitating audits and
compliance.
Scan to Download
7.Question
What tools can be used to implement a build and
deployment pipeline for microservices?
Answer:Common tools for implementing a build and
deployment pipeline include source control systems like
GitHub, CI/CD services like Travis CI, containerization
technologies like Docker, and orchestration platforms like
AWS ECS for deploying Docker containers.
8.Question
Why is velocity a crucial metric in microservices
deployment?
Answer:Velocity measures how quickly teams can move
from development to deployment. Higher velocity indicates
that teams can respond faster to market needs, adapt to
changes, and deliver features to users rapidly, which is a
major advantage in a competitive landscape.
9.Question
What does the concept of a 'Phoenix server' entail and
why is it relevant to microservices?
Answer:The 'Phoenix server' concept involves treating
Scan to Download
servers as disposable resources that can be easily replaced
without any residual state or configuration changes. This
practice is relevant in microservices because it helps
eliminate configuration drift, ensures consistency across
environments, and improves system resilience by regularly
testing recoverability.
10.Question
What steps should be taken to create a PostgreSQL
database using Amazon RDS for a microservice?
Answer:To create a PostgreSQL database using Amazon
RDS, log into the AWS console, navigate to the RDS
dashboard, select PostgreSQL as the database engine,
configure the instance settings, set up security groups, and
launch the database. These steps can typically be completed
in just a few clicks.
11.Question
How does the deployment process change when moving
from manual to automated processes?
Answer:When transitioning from manual to automated
Scan to Download
deployment processes, teams establish scripted workflows
that execute upon code commits. This shift reduces the
likelihood of human errors, ensures that deployments are
consistent, and allows for faster and more reliable releases.
12.Question
What are the benefits of using Docker for deploying
microservices?
Answer:Docker offers portability across environments,
lightweight deployment, and consistency in service
execution. It simplifies managing dependencies and scaling
services, while allowing seamless integration into different
cloud providers and development environments.
13.Question
What considerations should be made when setting up a
build and deployment pipeline for multiple
microservices?
Answer:Each microservice should ideally have its own
repository and independent build processes to allow for
isolated development and deployment. Ensure that the
pipeline is designed to handle inter-service communication
Scan to Download
and includes proper testing at each stage of the deployment,
with infrastructure-as-code practices to maintain consistency.
14.Question
How do environment variables play a role in the
deployment of microservices?
Answer:Environment variables are used to pass runtime
configuration to microservices without hardcoding values
into the application. This allows for flexible and secure
management of sensitive information, such as database
credentials and API keys, and helps tailor the application’s
behavior for different deployment environments.
15.Question
What is the significance of platform tests in the
deployment process?
Answer:Platform tests are crucial as they assess the
functionality of microservices once deployed in their actual
environments. Unlike unit and integration tests, which may
rely on mocked dependencies, platform tests verify that the
services work correctly in live integrations, ensuring that all
Scan to Download
components interact as expected.
Chapter 11 | Appendix A. Running a cloud on your
desktop| Q&A
1.Question
What were the primary goals of structuring the code
examples in the book?
Answer:The first goal was to make the code
examples consumable and easy to set up,
acknowledging the complexity inherent in
microservices with multiple moving parts. The
second goal was to ensure that each chapter was a
completely standalone unit, allowing readers to pick
any chapter and have a fully functional runtime
environment without needing to rely on other
chapters.
2.Question
Why was Apache Maven chosen as the build tool for the
projects?
Answer:Apache Maven was chosen due to its prominence in
the Java ecosystem, being the most widely used build tool
Scan to Download
despite other popular options like Gradle. Its consistency and
familiarity make it easier for developers to follow the
structure laid out in the book.
3.Question
How do Docker and Docker Compose contribute to the
development process outlined in the book?
Answer:Docker allows the encapsulation of the application
services and the necessary infrastructure into portable
containers, simplifying the deployment process across
different environments. Docker Compose, on the other hand,
helps in orchestrating multiple services as a unit, enabling
them to be launched together with a simple command,
thereby reducing setup complexity.
4.Question
Can you explain the purpose of the run.sh script used in
the Docker image?
Answer:The run.sh script is a custom Bash script that ensures
the service starts only after its dependencies, like the
database, are ready. It uses the 'nc' command to check if
Scan to Download
specific ports are open before launching the service, thus
preventing errors that can occur from trying to start services
out of order.
5.Question
How does the structure of each chapter support learning
about microservices?
Answer:Each chapter is structured around one or more
services, with each service kept in its own project directory
that follows a consistent Maven-based layout. This modular
approach allows readers to focus on individual services and
understand their functionalities in isolation while still seeing
how they interconnect within the overall application
architecture.
6.Question
What should a developer do to run example projects from
the book?
Answer:To run the example projects, a developer should first
ensure they have the necessary software installed (Apache
Maven, Docker, and Git). They then need to download the
Scan to Download
source code from the respective GitHub repositories, build
the projects using Maven, and launch the services using
Docker Compose.
7.Question
What role does the Dockerfile play in the Docker
workflow discussed in the book?
Answer:The Dockerfile contains the instructions required to
build a Docker image for a service. It outlines steps such as
copying executable files into the image, installing
dependencies, and setting up the environment needed for the
service to run correctly within the container.
8.Question
Why is it important that the Docker images are
ephemeral in nature?
Answer:The ephemeral trait of Docker containers means that
they do not retain data once stopped, which promotes a
robust development cycle where the environment can be
quickly recreated. This can be beneficial for testing and
continuously deploying microservices, but developers should
Scan to Download
be aware that this can lead to the loss of persistent data
unless additional measures, like Docker volumes, are taken.
9.Question
What is suggested for someone who wants to dive deeper
into Docker?
Answer:For those wanting to understand Docker more
thoroughly, the books 'Docker in Action' by Jeff Nickoloff
and 'Using Docker' by Adrian Mouat are recommended as
excellent resources to gain deeper insights and practical
knowledge.
Chapter 12 | Appendix B. OAuth2 grant types| Q&A
1.Question
What is the main purpose of OAuth2 in application
security?
Answer:OAuth2 provides a flexible authorization
framework that allows applications to authenticate
users and authorize access to their resources without
requiring them to share their credentials. This
facilitates secure data sharing and integration
Scan to Download
among different applications owned by different
services.
2.Question
How do the different grant types in OAuth2 enhance
security?
Answer:The various OAuth2 grant types, such as Password,
Client Credentials, Authorization Code, and Implicit grants,
are designed to handle distinct authentication scenarios,
ensuring that user credentials are not unnecessarily exposed.
For instance, the Authorization Code grant allows the user to
authenticate without directly exposing their credentials to
third-party applications.
3.Question
In what scenario would you use the Password grant type?
Answer:The Password grant type is suitable when two
applications share a natural trust relationship, such as when a
web application and its associated services are managed by
the same organization.
4.Question
What distinguishes the Client Credentials grant from
Scan to Download
other OAuth2 grants?
Answer:The Client Credentials grant is used for
client-to-client communication where no user interaction is
required. It only relies on the application’s credentials,
making it ideal for server-to-server interactions.
5.Question
Why is the Authorization Code grant considered the most
secure?
Answer:The Authorization Code grant introduces an
additional layer of security by issuing a temporary
authorization code instead of exposing the access token
immediately. This separates the user authentication phase
from the token exchange process, reducing the risk of
credential exposure.
6.Question
What complexity arises with the Implicit grant type in
OAuth2?
Answer:The Implicit grant type is inherently less secure
because it directly exposes the access token within the user's
Scan to Download
browser, making it more vulnerable to interception by
malicious scripts.
7.Question
How does the refresh token mechanism work in OAuth2?
Answer:When an access token expires, the application can
use a refresh token to obtain a new access token without
prompting the user to log in again. This maintains a seamless
user experience while ensuring ongoing authorization.
8.Question
Why is it crucial not to expose user credentials directly to
third-party applications?
Answer:Exposing user credentials directly can lead to
security vulnerabilities, allowing malicious applications to
impersonate users and compromise their accounts. OAuth2
eliminates this risk by facilitating token-based authorization.
9.Question
In what way does OAuth2 respond to the modern needs of
application integration?
Answer:OAuth2 addresses the need for secure application
integration by allowing different services to communicate
Scan to Download
and share user data without compromising sensitive
information, thus fostering interoperability in a cloud-based
environment.
10.Question
What challenges do developers face when implementing
OAuth2?
Answer:Developers often encounter complexity due to the
various grant types, deciding which flow to implement based
on their application's specific needs, while ensuring robust
security measures are in place to protect user data.
Scan to Download
Spring Microservices in Action Quiz and
Test
Check the Correct Answer on Bookey Website
Scan to Download
for implementing the microservices and ensuring consistent
and maintainable code.
3.Microservices should always be used for small applications
due to their ability to effectively scale and manage loads.
Chapter 3 | Controlling your configuration with
Spring Cloud configuration server| Quiz and Test
1.Developers are encouraged to hardcode values in
their application code to manage configuration.
2.Managing application configuration is vital for
microservices in cloud environments, as it reduces human
intervention during deployments.
3.Sensitive configuration information, such as database
credentials, should always be stored in plaintext in
configuration files.
Scan to Download
Chapter 4 | On service discovery| Quiz and Test
1.Service discovery is not important in cloud-based
applications.
2.Traditional service discovery methods like DNS are limited
due to their single point of failure.
3.Eureka is an effective service discovery engine when
integrated with Spring Cloud.
Chapter 5 | When bad things happen: client
resiliency patterns with Spring Cloud and Netflix
Hystrix| Quiz and Test
1.Client-side resiliency patterns help applications
conserve resources by failing fast when a remote
service fails.
2.Hystrix does not automate the complexities associated with
managing service failures.
3.The bulkhead pattern is used to ensure that a single service
failure can impact the entire application.
Chapter 6 | Service routing with Spring Cloud and
Zuul| Quiz and Test
1.In microservices architecture, it is important for
Scan to Download
each service to independently manage
cross-cutting concerns like security and logging.
2.Zuul serves as a reverse proxy and integrates seamlessly
with Spring Cloud.
3.Filters in Zuul execute only after a service call occurs.
Scan to Download
Chapter 7 | Securing your microservices| Quiz and
Test
1.Security in microservices is paramount and
involves multiple layers.
2.OAuth2 allows users to authenticate only via their own
credentials and does not support third-party services.
3.Custom JWTs can enhance the OAuth2 process.
Chapter 8 | Event-driven architecture with Spring
Cloud Stream| Quiz and Test
1.Event-Driven Architecture (EDA) allows tightly
coupled systems to react to state changes via
asynchronous messages.
2.Spring Cloud Stream abstracts the underlying messaging
platform's details, enabling easier message-based
application development.
3.Using Redis for caching in microservices architecture
improves lookup performance and resiliency.
Chapter 9 | Distributed tracing with Spring Cloud
Sleuth and Zipkin| Quiz and Test
1.Spring Cloud Sleuth automatically propagates
Scan to Download
correlation IDs within microservices to maintain
transaction context.
2.Zipkin is a tool used for aggregating logs from multiple
microservices into a single searchable database.
3.It is possible to customize tracing information in Spring
Cloud Sleuth by implementing correlation IDs.
Scan to Download
Chapter 10 | Deploying your microservices| Quiz
and Test
1.DevOps is essential for facilitating rapid
deployment and operational efficiency in
microservices.
2.Manual deployment is the only method discussed for
deploying microservices in the chapter.
3.AWS ECS is used for deploying containers without
exposing unnecessary ports in microservices.
Chapter 11 | Appendix A. Running a cloud on your
desktop| Quiz and Test
1.Apache Maven version 3.6.0 is the recommended
build tool in the book.
2.Java version 1.8 is used for code compilation in the
examples provided in the book.
3.Docker Compose is not essential for launching services as
per the appendix.
Chapter 12 | Appendix B. OAuth2 grant types| Quiz
and Test
1.The Password grant type is suitable for
Scan to Download
applications that do not trust each other.
2.Client Credentials grant allows applications to authenticate
without human involvement.
3.Implicit Grants are secure because they keep OAuth2
tokens away from the user's browser.
Scan to Download