Giter Club home page Giter Club logo

hands-on-microservices-with-spring-boot-and-spring-cloud's Introduction

$5 Tech Unlocked 2021!

If you have read this book, please leave a review on Amazon.com. Potential readers can then use your unbiased opinion to help them make purchase decisions. Thank you. The $5 campaign runs from December 15th 2020 to January 13th 2021.

Microservices with Spring Boot and Spring Cloud, 2nd edition

The second edition of the book is now released, see Amazon.com.

It has been updated for the most recent versions of Spring, Java, Kubernetes, and Istio. In addition, support is added for building and running all examples on a Windows PC using WSL 2. Finally, a chapter has been added about native compile, enabling Java-based microservices to start up in a fraction of a second.

Here is a summary of the most significant changes and news in the second edition: blog post.

The GitHub repo for the second edition can be found here: https://github.com/PacktPublishing/Microservices-with-Spring-Boot-and-Spring-Cloud-2E.git.

Hands-On Microservices with Spring Boot and Spring Cloud

Hands-On Microservices with Spring Boot and Spring Cloud

This is the code repository for Hands-On Microservices with Spring Boot and Spring Cloud , published by Packt.

Build and deploy Java microservices using Spring Cloud, Istio, and Kubernetes

What is this book about?

Microservices architecture allows developers to build and maintain applications with ease, and enterprises are rapidly adopting it to build software using Spring Boot as their default framework. With this book, you’ll learn how to efficiently build and deploy microservices using Spring Boot.

This book covers the following exciting features:

  • Build reactive microservices using Spring Boot
  • Develop resilient and scalable microservices using Spring Cloud
  • Use OAuth 2.0/OIDC and Spring Security to protect public APIs
  • Implement Docker to bridge the gap between development, testing, and production
  • Deploy and manage microservices using Kubernetes
  • Apply Istio for improved security, observability, and traffic management

If you feel this book is for you, get your copy today!

https://www.packtpub.com/

Instructions and Navigations

All of the code is organized into folders. For example, Chapter02.

The code will look like the following:

management.endpoint.health.show-details: "ALWAYS"
management.endpoints.web.exposure.include: "*"

logging.level.root: info

Following is what you need for this book: This book is for Java and Spring developers and architects who want to learn how to break up their existing monoliths into microservices and deploy them either on-premises or in the cloud using Kubernetes as a container orchestrator and Istio as a service Mesh. No familiarity with microservices architecture is required to get started with this book.

With the following software and hardware list you can run all code files present in the book (Chapter03-20).

Software and Hardware List

No. Software required OS required
1 Spring Windows, macOS, Linux
2 Docker CE Windows, macOS, Linux, see supported platforms

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. Click here to download it.

Errata

  • Page 5 (Contributors): My college Erik Lupander should be My colleague Erik Lupander

  • Page 14 (Paragraph 1, line 2): that we were not exposed should be that we were not exposed to

  • Page 40 (Paragraph 3, line 1): When the Spring Framework was released in v1.0 back in 2004, it was released in order to fix the overly complex… should be The Spring Framework v1.0 was released back in 2004 to fix the overly complex…

  • Page 102 (Last paragraph, line 2): Once the CoreOS server has started running in its container you can, for example, ask what version of CoreOS that it runs with the cat /etc/redhat-release command. should be Once the CoreOS server has started running in its container, you can, for example, ask what version of CoreOS it is running using the cat /etc/redhat-release command.

  • Page 370 (Adding programmable delays and random errors section) faultPercentage: Causes the getProduct API on the product microservice... should be faultPercent: Causes the getProduct API on the product microservice to..

  • Page 370 (Changes in the API definitions section) The two query parameters that we introduced previously, delay and faultPercentage, have been defined in the api project in the following two Java interfaces... should be The two query parameters that we introduced previously, delay and faultPercent, have been defined in the api project in the following two Java interfaces...

Source code changes

Related products

Get to Know the Author

Magnus Larsson has been in the IT industry for 35 years, working as a consultant for large companies in Sweden such as Volvo, Ericsson, and AstraZeneca. In the past, he struggled with the challenges associated with distributed systems. Today, these challenges can be handled with open source tools such as Spring Cloud, Kubernetes, and Istio. Over the last years, Magnus has been helping customers use these tools and has also given several presentations and written blog posts on the subject.

Suggestions and Feedback

Click here if you have any feedback or suggestions.

Download a free PDF

If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.

https://packt.link/free-ebook/9781789613476

hands-on-microservices-with-spring-boot-and-spring-cloud's People

Contributors

gaurav-packt avatar magnus-larsson avatar manikandankurup-packt avatar packt-itservice avatar packtutkarshr avatar shaileshj-packt avatar tikshas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hands-on-microservices-with-spring-boot-and-spring-cloud's Issues

Project Structure Issue leads to Inability to compile with Intellij

Hello,

This isn't so much an issue as perhaps a question about something that is not discussed in the book, namely, how do we create the project structure you have in your source code? For example, if I open Chapter05 in intellij and look at the project structure, it shows:

chapter5projstruct

By the project structure I get looks like this (I've played around with it and sometimes get a slightly different structure such as one where all the projects are on the same level):

myprojstruct

The result is that when gradle tries to sync in the IDE (Intellij Ultimate), I get the following error for every service:

A problem occurred evaluating root project 'product-service'.

Project with path ':api' could not be found in root project 'product-service'.

Would it be possible to give some references as to how to correctly build the project structure? I'm not very familiar with Gradle or Modules in general.

Note: regardless of this, I am able to build and run via the command-line. It's just it would be very helpful to be able to get this to work in the IDE as it is preventing me from getting Swagger to work in Chapter 5 since the libraries aren't getting pulled in (due to Gradle not syncing).

Thank you!
Christine

debug individual microservices outside of docker

My windows desktop , server 2012 R2, doesn't support containers, so i want to debug individual microservices within intellij outside of docker.

jars are not created for individual microservices, such as review

I am not familiar with gradle, however, i can if i convert to maven project i can create the missing jars

Defualt jwtDecoder unable to locate http://auth-server

The default WebClient used in the default JwtDecoder of composite-product and gateway server implementation does not have access to Eureka server 'names' resulting in a host not found exception for the JWT endpoint at http://auth-server:9999/.well-known/...

To get around this I create a custom implementation of JwtDecoder and injected the LoadBalancing WebClient created at application startup and this resolves the host lookup issues.

SecurityConfig class for composite-product now looks like this:

`@EnableWebFluxSecurity
public class SecurityConfig {

@Autowired
private WebClient.Builder webClientBuilder;

@Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
private String jwkSetUri;

@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
	http.authorizeExchange().pathMatchers("/actuator/**").permitAll()
			.pathMatchers(HttpMethod.POST, "/product-composite/**").hasAuthority("SCOPE_product:write")
			.pathMatchers(HttpMethod.DELETE, "/product-composite/**").hasAuthority("SCOPE_product:write")
			.pathMatchers(HttpMethod.GET, "/product-composite/**").hasAuthority("SCOPE_product:read").anyExchange()
			.authenticated().and().oauth2ResourceServer().jwt().jwtDecoder(nimbusReactiveJwtDecoder());
	return http.build();
}

@Bean
public NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder() {
	return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).webClient(webClientBuilder.build()).build();
}

}`

SecurityConfig class for gateway now looks like this:

@EnableWebFluxSecurity
public class SecurityConfig {

@Autowired
private WebClient.Builder webClientBuilder;

@Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
private String jwkSetUri;

@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) throws Exception {

	http.csrf().disable().authorizeExchange().pathMatchers("/headerrouting/**").permitAll()
			.pathMatchers("/actuator/**").permitAll().pathMatchers("/eureka/**").permitAll()
			.pathMatchers("/oauth/**").permitAll().anyExchange().authenticated().and().oauth2ResourceServer().jwt()
			.jwtDecoder(nimbusReactiveJwtDecoder());
	return http.build();
}

@Bean
public NimbusReactiveJwtDecoder nimbusReactiveJwtDecoder() {
	return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).webClient(webClientBuilder.build()).build();
}

}

Chapter 05 and on won't compile

Hi,
I am working through your book (great book btw!) and I have reached Chapter 05 where Swagger is introduced. The project is failing to compile because the springfox dependencies have versions that are no longer available in the http://oss.jfrog.org/artifactory/oss-snapshot-local/ repo. I updated the versions to version 3.0 SNAPSHOTS that do exist but then the tests start failing due to errors like method not found.

I tried moving on to Chapter 06 but it has the same issues.

I'm new to Gradle and Swagger, so I'm not sure what needs to be fixed.

Thanks!

Importing these projects into Eclipse

Is there a way to import these project into Eclipse? I'm trying to work with chapter 3, 2-basic-rest-service. I use Import and then Gradle project, but it ends up importing a "2-basic-service" project filled with broker references, and then each package is imported as a separate project.

Chap12 start docker compose config-server connection refused

After a day trying to understand chap 12, i had an issue on docker compose. On start eureka, gateway and auth-server had same issue http://config-server:8888 connection refused and all stop.

I finally found a "solution" add depends-on: config-server for them on docker-compose.yml.

config-server:
...
  healthcheck:
      test: [ "CMD", "curl", "-I", "http://config-server:8888" ]
      interval: 5s
      timeout: 5s
      retries: 10000

and

depends_on:
      config-server:
        condition: service_healthy

May be it's not the rigth way.

I use spring boot 2.4.3 and 2020.0.1 for spring cloud

Chapter 9 code has runtime errors

I run the Chapter 9 code with docker-compose up like the other chapters. When I use a curl POST command to create a product (as in previous chapters) and then a curl GET to read the product just created I get a 404 error.

Also in Chapter 9 test-em-all.bash doesn't start. It just keeps retrying.

Question about Chapter 7 createReview in Review service

From my understanding, reading through the book and code for section 7. When the Product Composite service creates new Product, Recommendations and Reviews, it would put the request on respectively topic where the core microservices will take from the queue and action it according to it message type.

For Product and Recommendation, since it using MongoDB which has support for non-blocking model, it using reactive programming. But for Review case, reading the code inside ReviewServiceImpl createReview, it creates review in a blocking sync manner? Is my understanding correct? I was wondering if using a threadpool is a improvement if the above case is correct?

public Review createReview(Review body) {
if (body.getProductId() < 1) throw new InvalidInputException("Invalid productId: " + body.getProductId());
try {
ReviewEntity entity = mapper.apiToEntity(body);
ReviewEntity newEntity = repository.save(entity);
LOG.debug("createReview: created a review entity: {}/{}", body.getProductId(), body.getReviewId());
return mapper.entityToApi(newEntity);
} catch (DataIntegrityViolationException dive) {
throw new InvalidInputException("Duplicate key, Product Id: " + body.getProductId() + ", Review Id:" + body.getReviewId());
}
}

Chapter 3: Implementing Our API (Step 7): gradlew build -> Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

Not exactly an issue, but I thought this might help some people…

On Win 10, executing the following command:

gradlew build
Yields this result/error:

Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

This can be fixed by changing the gradle-wrapper.properties as follows:

distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip
To:
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip

(The file can be found here: ../Chapter03/2-basic-rest-services/gradle/wrapper/gradle-wrapper.properties)

Just for reference, the configuration I used is:

>java --version
java 15.0.2 2021-01-19

>spring --version
Spring CLI v2.5.1

>gradle --version
Gradle 7.1
Kotlin:       1.4.31
Groovy:       3.0.7
Ant:          Apache Ant(TM) version 1.10.9 compiled on September 27 2020
JVM:          15.0.2 (Oracle Corporation 15.0.2+7-27)
OS:           Windows 10 10.0 amd64

Chapter03 implementing APIs "no active profile set...

Hi,

using
Java v. 11.0.13
git v. 2.25.1
curl v. 7.68.0
Spring CLI 2.6.4

I'm trying to build and run the product-service microservices (p. 78 Implementing our API, step 7, 8 and 9) but when I try curl I get an error "curl: (7) Failed to connect to localhost port 7001: Connection refused".
When launching the microservice I get a "No active profile set, falling back to default profiles: default".
I've read this issue: https://githubhot.com/repo/PacktPublishing/Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud/issues/28, but I cannot find which files I'm supposed to look at or how to resolve the issue.

image

image

blocking code in Chapter 7 only removed partially

is there a reason why the blocking code in Chapter 7 is only replaced partially?
For example in ProductServiceImp the method getProduct is refactored but the createProduct / deleteProduct is still blocking:

return newEntity.block();

repository.findByProductId(productId).log().map(e -> repository.delete(e)).flatMap(e -> e).block();

Chapter 18 - Rolling version v2 - what about Create/Delete?

This is not a bug.

Either, IMHO, is a missing content in the book.

When you describe the section "Performing zero-downtime deployments" in chapter 18, you miss totally the problematic regarding the StateFul/DML services.

When I have deployed versions v1 and v2, and submit a POST for creation, the both versions read the RabbitMQ message, and try to create the record (one of them will fail with duplicate, but this is not the question).

Is there any alternative (like version partition added to the queue by Istio)?

At least, comment this question, telling us that this is not contemplated.

Chapter 13 - Resilience4J with SpringBoot 2.4.0

Hi,

I have suffered the bug you reported about incompatibility between Resilience4J 1.6.1 and SpringBoot 2.4.0

The Reactor based RetryOperator uses a deprecated method that is removed in Reactor 3.4.0 used by Spring Boot 2.4.0

I'm trying to update to version 1.7.0. For this, I have tried to update my build.gradle to

// ... Not relevant
ext {
   resilience4jVersion = "1.7.0"
}
dependencies {
// ... Not relevante
	implementation("io.github.resilience4j:resilience4j-spring-boot2:${resilience4jVersion}")
	implementation("io.github.resilience4j:resilience4j-reactor:${resilience4jVersion}")
}

But then, when I try gradle build, I the test phase, I get the error

Caused by: java.lang.ClassNotFoundException: io.github.resilience4j.core.ContextAwareScheduledThreadPoolExecutor

Have you got this working? Which are the right dependencies?

BTW, I have also tried (with the same result) adding all dependencies, as

  implementation("io.github.resilience4j:resilience4j-spring-boot2:${resilience4jVersion}")
  implementation("io.github.resilience4j:resilience4j-reactor:${resilience4jVersion}")
  implementation "io.github.resilience4j:resilience4j-circuitbreaker:${resilience4jVersion}"
  implementation "io.github.resilience4j:resilience4j-ratelimiter:${resilience4jVersion}"
  implementation "io.github.resilience4j:resilience4j-retry:${resilience4jVersion}"
  implementation "io.github.resilience4j:resilience4j-bulkhead:${resilience4jVersion}"
  implementation "io.github.resilience4j:resilience4j-cache:${resilience4jVersion}"
  implementation "io.github.resilience4j:resilience4j-timelimiter:${resilience4jVersion}"
	

PWD not found defaulting to blank string on Windows - Containers not starting

From Chapter 12 onwards, the 'config-server' gets a warning that '$PWD var' can't be found (on a windows machine) during the 'docker-compose up' phase. The net result is that all dependant Containers will fail on starting unable to get credentials.

The fix to this (for Windows) is to replace in config-server/../application.yml:

  • spring.cloud.config.server.native.searchLocations: file:${PWD}/config-repo

with:

  • spring.cloud.config.server.native.searchLocations: file:./config-repo

The same is true for this line in the the docker-compose.yml files (from '${PWD} to '.')

Hope this helps

review-service: DB requests run under wrong thread pool

Hi Magnus,

Sorry for bothering you, I'm reading your book, by the way it's a good one ;), right now I'm on chapter 7 and I realised that there is an improvement that I guess could be added to this code.

It seems to be that in review-service DB request doesn't run under blocking thread pool that you created, this means that you could run out of non-blocking threads which are in charge of receiving incoming requests.

I'm not an expert of Spring Reactive Framework, but after a small test, it seems that this could be fixed starting the Flux stream before sending any request to the DB.

Here a code example:
/review-service/src/main/java/se/magnus/microservices/core/review/services/ReviewServiceImpl.java
private Flux<Review> asyncFlux(int productId) { return Flux.just(productId) .subscribeOn(scheduler) .map( id -> getByProductId(id) ) .flatMap(Flux::fromIterable); }

Thanks a lot for the book. I'm learning about this topic so maybe what I wrote above could be improved.

Multi-Module Spring Boot Application with Gradle not work IntelliJ

cordial greetings
when I try to use the api library in the product-service microservice using IntelliJ, it says that the project is not found, I followed the instructions in the book but the project is not found.

Caused by: org.gradle.api.UnknownProjectException: Project with path ':api' could not be found in root project 'product-service'.

this is the settigs.gradle

include ':microservices:product-service'
include ':microservices:review-service'
include ':microservices:recommendation-service'
include ':microservices:product-composite-service'
include ':api'
include ':util'

this is the dependency call in product-service

dependencies {
compile project(':api')
implementation project(':util')
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-webflux'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.projectreactor:reactor-test'
}

fluentd daemonset send same log from each cluster node

Hi,
I run the example with the fluentd daemonset and the EFK Stack.
My cluster has 4 nodes. I get the the same log entry in the Elastic Index 4 times - obviously sends each fluentd pod on each node the same log file to elastic.

The _id Entry in the index is different most of the time, but sometimes the _id is identical between to entries.

How can I achieve that I get a Log Entry only once in the Elastic Index?

Best regards
Stefan

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.