Git Product home page Git Product logo

spring-microservice-loja's Introduction

Microservices with Spring Boot - Store βœ…

Version Stars Forks License

Microservices with Spring and best of all with MIT license😍, so that we can use these projects as a study or as a basis for new projects, even sharing new ideasπŸ’‘. Feel free to contribute to these projects right here.❀️

Index πŸ“Œ

About the project πŸ”—

I developed this project using Spring Boot (2.1.5.RELEASE), so it adopts an architecture based on microservices using all the power of Spring Cloud and its technologies. When we are working with Spring, we have several advantages for gaining technologies and solutions already ready to be implemented, so we made use of some of them.

Breaking the domain into services

  • I broke the domain of the solution into three projects (loja, fornecedor, transportador), so in our APIs, we use some technologies and solutions to build a robust, secure, traceable and scalable architecture.

Spring Cloud Netflix Eureka

  • We use Netflix Eureka as a Service Discovery solution, it is very simple and easy to implement.

Spring Cloud Config

  • The yaml configurations of the projects were all exported and configured through the Config Server microservice.

Spring Cloud OpenFeign

  • Used Spring Feign to make calls between microservices in a simple way for its customers, it is a project that was inspired by Retrofit, JAXRS-2.0 and WebSocket. With it we are also able to use the Client Side Load Balancer because Feign is integrated with the Ribbon, which in turn is also integrated with Eureka.

Spring Cloud Sleuth

  • Used Spring Cloud Sleuth to assist with Distributed Tracing, responsible for implementing a distributed tracking solution, which helps us track requests between microservices through a correlation ID, so that we can track the entire flow of a request that goes through several microservices. To observe the logs we use Papertrail.

Netflix Hystrix

  • Used Netflix Hystrix that implements the Circuit Breaker standard, which very quickly is a failover for calls between microservices, that is, if a microservice is down, a fallback method is called and that flood of failures is avoided.
  • We also managed to use the Bulkhead Pattern using Hystrix's own threadPoolKey to isolate the threads and not block our services.

Netflix Zuul

  • Used Spring Zuul as an API Gateway because its implementation and its high integration with Netflix Eureka are very simple. Zuul uses Eureka to know the instances of microservices and, using the Ribbon, is able to load balance user requests.

Spring Cloud OAuth (OAuth2) - Authentication and authorization between microservices

  • Set up all security with Spring Security and Spring Cloud OAuth and plugged in through standard spring security adapters with OAuth2. The username and password are in memory to facilitate testing.
  • A token in the standard JSON Web Tokens (JWT) format was implemented.
  • For each microservice that we want to assign security, we must configure it in a way that it knows where it must authenticate itself. When a request for the microservice arrives, it simply blocks it, after that it goes to the microservice referring to the auth security to validate the user's information, to say whether it can access the resource or not, whether that token is valid or not. access. For that, we must configure this call.

Microservice auth -> application.yml

security:
  oauth2:
    resource:
      user-info-uri: http://localhost:8088/user
  • When we are using an API Gateway we need to pass the access token from the request that arrives at Zuul to the request that Zuul makes for microservices, for this we configure as follows.

Microservice zuul -> application.yml

zuul:
  sensitive-headers:
  - Cookie, Authorization
  • In the loja microservice when we receive an access token to perform a purchase operation, for example, we need to take that same token and forward it to our calls to customers (Feign) from other microservices, because when we use Feign it will perform new requests to customers, but he does not know the header information originating from the request, so we must configure it so that he knows which header he should pass on to his requests to customers, as the other microservices will need to authenticate as well.

  • We have implemented an interceptor to retrieve the request information through the SecurityContextHolder, making a validation whether or not there is authentication information, if it exists, we were able to redeem the access token value. With the token information in hand we use Feign's RestTemplate to add the user's token to the request header, so Feign can pass the token on to his calls.

Microservice loja -> SpringMicroserviceLojaApplication.java

// Add config to intercept Feign requests for when we call another microservices to be passed the authentication token
@Bean
public RequestInterceptor getInterceptorDeAutenticacao() {
    return new RequestInterceptor() {
        @Override
        public void apply(RequestTemplate template) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if(authentication == null) {
                return;
            }
            
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
            template.header("Authorization", "Bearer" + details.getTokenValue());
        }
    };
}
  • It is extremely important to add a configuration to Hystrix so that it can share the security context, if it is disabled it is not possible to forward the token, as Hystrix creates several thread pools.

Microservice loja -> application.yml

hystrix:
  shareSecurityContext: true

Below is the flow of OAuth2. OAuth2

Handling errors in the integration between services

  • To deal with this type of error we made a simple implementation, where each step that the microservice store requests for other services we save the request status in the entity, so that if there is Hystrix treatment we can make another request from that state. Here are the status we use: RECEIVED, ORDER_REQUESTED and RESERVE_DELIVERED.

Spring Cloud with Spring Boot

Building distributed systems don't need to be complicated and error-prone. Spring Cloud offers a simple and accessible programming model to the most common distributed system patterns, helping developers build resilient, reliable, and coordinated applications. Spring Cloud is built on top of Spring Boot, making it easy for developers to get started and become productive quickly.

Spring Cloud

How to run πŸ”§

Follow the instructions below to build and execute the project in a simple and easy way, but feel free to run the way you want.:relaxed:

What you need to have installed

  • Java 8;:heart:
  • Maven;
  • PostgreSQL and MySQL (recommended to use Docker);
  • Postman for testing.

Database

  • We use the PostgreSQL database for the microservice fornecedor and the MySQL database for the microservices loja and transportador. That way we can work with different databases, we use it that way for study and learning reasons.
  • After installation, the respective databases must be created, loja, fornecedor and transportador.
  • Using Docker it is very simple to use the databases, see below:

PostgreSQL

docker run --name my-postgres -e "POSTGRES_PASSWORD=postgres" -e "POSTGRES_USER=postgres" -e "PGDATA=/var/lib/postgresql/data/pgdata" -p 5432:5432 -v /your-volumes:/var/lib/postgresql/data -d postgres:9.5

MySQL

docker run --name my-mysql -v /your-volumes:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root -p 3306:3306 -d mysql:8.0

Build and Run

  • Following the order of the microservices below, execute the command via terminal in their respective microservices:
mvn clean install spring-boot:run -Dmaven.test.skip=true

‡️

Stay free to use your favorite IDE.:relaxed:

Using Spring Tools Suite 4 it is very simple to upload microservices.:heart_eyes: sts4

Postman

  • To perform the services tests, follow the file microservices-murillo-pezzuol.postman_collection.json to be imported into Postman located at the root of the repository loja.

Below are some tests performed on Postman.:heart_eyes: sts4

Projects and repositories πŸ“

Applications πŸ’»

Spring Cloud and Config Server πŸ“”

Spring Security - OAuth2 πŸ”

  • spring-microservice-auth - Microservice related to the application of authentication and authorization between microservices with OAuth2. Tags: OAuth2, Security

Service Registration and Discovery πŸ”Ž

API Gateway πŸš₯

Monitoring πŸ“ˆ

License πŸ“‹

Feel free to contribute, we continue with an MIT license. 😍here

spring-microservice-loja's People

Contributors

mupezzuol avatar stgonzales avatar

Stargazers

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

Watchers

 avatar

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.