SpringCloud learning of java microservice architecture

The notes come from madness

1, Overview of microservices

1.1. What is micro service?

Microservice architecture is a popular architecture idea in recent years. It is difficult to sum up its concept.

What exactly is a micro service? We hereby quote Martin Fowler, chief scientist of ThoughtWorks, who put forward a paragraph in 2014:

Original text: https://martinfowler.com/articles/microservices.html

Sinicization: https://www.cnblogs.com/liuning8023/p/4493156.html

  • At present, there is no unified and standard definition of microservices in the industry.
  • But generally speaking, microservice architecture is an architectural mode, or architectural style. Its length divides a single application into a group of small services. Each service runs in its own independent process. Services coordinate and configure with each other to provide final value for users. Services communicate with each other through lightweight communication mechanism (HTTP), Each service is built around a specific business and can be independently deployed to the production environment. In addition, a unified and centralized service management mechanism should be avoided as far as possible. For a specific service, an appropriate language and tool (Maven) should be selected to build it according to the business context, There can be a very lightweight centralized management to coordinate these services. Services can be written in different languages or different data stores.

From the perspective of Technology:

  • The core of microservicing is to divide the traditional one-stop application into one service according to the business and completely decouple it. Each microservice provides a service with a single business function, and one service does one thing. From a technical point of view, it is a small and independent processing process. The concept of similar process can be started or destroyed independently, Have their own independent database.

1.2. Microservices and microservice architecture


It emphasizes the size of the service. It focuses on a certain point. It is a service application that specifically solves a certain problem / provides landing corresponding services. In a narrow sense, it can be regarded as micro service projects in the IDEA or Moudel. In the IDEA tool, independent small Moudel developed by Maven is used. It specifically uses a small module developed by SpringBoot. Professional things are done by professional modules, and each module does one thing. The emphasis is on individuals, and each individual completes a specific task or function.

Microservice architecture

A new form of architecture was proposed by Martin Fowler in 2014.

Microservice architecture is an architecture mode. Its body length divides a single application into a group of small services. Services coordinate and cooperate with each other to provide final value for users. Each service runs in its own independent process. Lightweight communication mechanism (such as HTTP) is adopted between services to cooperate with each other. Each service is built around specific business and can be independently deployed to the production environment. In addition, unified and centralized service management mechanism should be avoided as far as possible. For a specific service, Appropriate languages and tools (such as Maven) should be selected to build it according to the business context.

1.3 advantages and disadvantages of microservices


  • The principle of single responsibility;

  • Each service is cohesive and small enough, and the code is easy to understand, so that it can focus on a specified business function or business requirement;

  • Development is simple and efficient. A service may be dedicated to only one thing;

  • Microservices can be developed independently by a small team, which only needs 2-5 developers;

  • Microservices are loosely coupled and functionally meaningful services, which are independent in both development and deployment stages;

  • Microservices can be developed in different languages;

  • It is easy to integrate with third parties. Microservices allow easy and flexible integration and automatic deployment through continuous integration tools, such as jenkins, Hudson and bamboo;

  • Microservices are easy to be understood, modified and maintained by a developer, so that small teams can pay more attention to their own work results and reflect their value without cooperation;

  • Microservices allow the use and integration of the latest technologies;

  • Microservices are just the code of business logic and will not be mixed with HTML, CSS or other interfaces;

  • Each microservice has its own storage capacity. It can have its own database or a unified database;


  • Developers need to deal with the complexity of distributed systems;
  • Multi service operation and maintenance is difficult. With the increase of services, the pressure of operation and maintenance is also increasing;
  • System deployment dependency;
  • Communication cost between services;
  • Data consistency;
  • System integration test problems;
  • Performance and monitoring issues;

1.4 what are the micro service technology stacks?

1.5 why choose spring cloud as the micro service architecture

Comparison of micro Service Frameworks

Function point / service frameworkNetflix/SpringCloudMotangRPCThri tDubbo/DubboX
Functional positioningComplete microservice frameworkRPC framework, but it integrates ZK or consult to realize basic service registration and discovery in cluster environmentRPC frameworkRPC frameworkService Framework
Support RestYes, Ribbon supports a variety of pluggable serial number choicesnononono
Support RPCnoYes (Hession2)yesyesyes
Support multiple languagesYes (Rest form)noyesyesno
load balancing Yes (server zuul + client Ribbon), zuul service, dynamic routing, cloud load balancing, Eureka (for middle tier servers)Yes (client)nonoYes (client)
Configure servicesNetfix Archaius, Spring Cloud Config Server, centralized configurationYes (provided by Zookeeper)nonono
Service call chain monitoringYes (zuul). Zuul provides edge services and API gatewaysnononono
High availability / fault toleranceYes (server side Hystrix + client Ribbon)Yes (client)nonoYes (client)
Typical application casesNetflixSinaGoogleFacebook
Community activityhighcommonlyhighcommonlyMaintenance resumed after 2017, after 5 years of interruption
Learning difficultysecondarylowhighhighlow
Document richnesshighcommonlycommonlycommonlyhigh
otherSpring bus brings more endpoints to our application managementSupport downgradeNetflix is developing and integrating gRPC internallyIDL definitionThere are many companies practicing

2, Spring cloud getting started overview

2.1 what is spring cloud?

spring official website: https://spring.io/

SpringCloud, based on SpringBoot, provides a set of microservice solutions, including service registration and discovery, configuration center, full link monitoring, service gateway, load balancing, fuse and other components. In addition to the highly abstract encapsulation of open-source components based on NetFlix, there are also some selection neutral open-source components.

Taking advantage of the development convenience of SpringBoot, SpringCloud cleverly simplifies the development of distributed system infrastructure. SpringCloud provides developers with some tools to quickly build distributed systems, including configuration management, service discovery, circuit breaker, routing, micro agent, event bus, global lock, decision-making campaign, distributed session, etc, They can all use the development style of SpringBoot to achieve one click Startup and deployment.

SpringBoot does not make wheels repeatedly. It just integrates the relatively mature service framework developed by various companies and can stand the actual postgraduate entrance examination. It is repackaged through the SpringBoot style, shielding the complex configuration and implementation principles. Finally, it leaves a set of distributed system development kit that is easy to understand, easy to deploy and easy to maintain for developers

SpringCloud is a one-stop solution under the distributed micro service architecture. It is a collection of landing technologies of various micro service architectures, commonly known as micro service platform

Five components of Spring Cloud

  • Service registration and discovery - Netflix Eureka

  • Load balancing:

    • Client load balancing - Netflix Ribbon
    • Server load balancing: - feign (which also depends on the Ribbon, but will call
  • (change the mode from resttemplet to Service interface)
    Circuit breaker - Netflix Hystrix

  • Service gateway - Netflix Zuul

  • Distributed configuration - Spring Cloud Config

Common interview questions:

3.2. Relationship between SpringCloud and SpringBoot

  • SpringBoot focuses on developing individual micro services quickly and easily-- jar
  • SpringCloud is a microservice coordination and management framework that focuses on the overall situation. It integrates and manages individual microservices developed by SpringBoot, and provides integrated services between microservices: configuration management, service discovery, broken routing, routing, micro agent, event bus, global lock, decision-making campaign, distributed session and so on
  • SpringBoot can be used independently of SpringCloud to develop projects, but SpringCloud cannot be separated from SpringBoot and belongs to dependency
  • SpringBoot focuses on the rapid and convenient development of individual micro services, and SpringCloud focuses on the overall service governance framework

3.3. Dubbo and SpringCloud technology selection

1. Distributed + service governance Dubbo
The current mature Internet architecture, application service splitting + message middleware
2. Comparison between Dubbo and spring cloud
Take a look at community activity:

The biggest difference: Spring Cloud abandons Dubbo's RPC communication and adopts HTTP based REST

Strictly speaking, these two methods have their own advantages and disadvantages. Although to some extent, the latter sacrifices the performance of service invocation, it also avoids the problems caused by the above-mentioned native RPC. Moreover, REST is more flexible than RPC. The dependence of service providers and callers only depends on one contract, and there is no strong dependence at the code level. This advantage is more appropriate in the current microservice environment that emphasizes rapid evolution.

Difference between brand machine and assembly machine

The difference between community support and renewal

**Summary: * * the two solve different problem domains: Dubbo is positioned as an RPC framework, while spring cloud aims at a one-stop solution under the microservice architecture.

3.4 what can spring cloud do?

  • Distributed/versioned configuration
  • Service registration and discovery
  • Routing
  • Service to service calls
  • Load balancing configuration
  • Circuit Breakers
  • Distributed messaging
  • ...

3.5 spring cloud Download

Official website: http://projects.spring.io/spring-cloud/
The version number is a little special:

Instead of naming the version number by numerical number, SpringCloud uses the name of London underground station, and corresponds to the chronological order of the version according to the alphabet. For example, the earliest real version is Angel, the second real version is Brixton, followed by Camden, Dalston and Edgware. At present, the latest is the general stable version of Hoxton SR4 CURRENT GA.

Self study reference books:

3, Spring cloud rest learning environment construction: Service Provider

3.1 introduction

  • We will use a Dept Department module as a general case of microservices. The Consumer consumer (Client) calls the services provided by the Provider (Server) through REST.
  • Review the previous knowledge of Spring, Spring MVC, Mybatis, etc.
  • Review of Maven's subcontracting module architecture.
A simple Maven The module structure is as follows:

-- app-parent: A parent item(app-parent)Aggregated many sub projects
  |-- pom.xml
  |-- app-core
  ||---- pom.xml
  |-- app-web
  ||---- pom.xml

A parent project has multiple Moudule sub modules

MicroServiceCloud has three sub modules under its parent project for the first time

  • Microservicecloud API [encapsulated overall entity / interface / public configuration, etc.]
  • microservicecloud-consumer-dept-80 [service provider]
  • microservicecloud-provider-dept-8001 [serving consumers]

3.2. Spring cloud version selection

Use the last two

3.3. Create parent project


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


    <!--Packaging method  pom-->


            <!--springCloud Dependence of-->
            <!--SpringBoot starter-->
            <!--Log test~-->


Such as deptconsumercontroller java

public class DeptConsumerController {

     * Understanding: consumers should not have a service layer~
     * RestTemplate .... For us to call directly! Register in Spring
     * (Address: url, entity: map, class < T > responsetype)
     * <p>
     * Provide a variety of convenient methods to access remote http services and a simple Restful service template~
    private RestTemplate restTemplate;

     * Service provider address prefix
     * <p>
     * Ribbon:The address here should be a variable accessed by the service name
    private static final String REST_URL_PREFIX = "http://localhost:8001";
    //private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";

     * Add department information to the consumer
     * @param dept
     * @return
    public boolean add(Dept dept) {
        // Postforobject (service provider address (Interface), parameter entity, return type class)
        return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class);

     * The consumer queries the Department information according to the id
     * @param id
     * @return
    public Dept get(@PathVariable("id") Long id) {
        // Getforobject (service provider address (Interface), return type class)
        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class);

     * Consumer query department information list
     * @return
    public List<Dept> list() {
        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class);

Before using resttemplet, you need to put it into the Spring container

public class ConfigBean {//@Configuration -- spring  applicationContext.xml

    //Configure load balancing to implement RestTemplate
    // IRule
    // Roundrobin rule polling
    // RandomRule random
    // Availability filtering rule: it will filter out, trip, access the failed service ~, and poll the rest~
    // RetryRule: the service will be obtained according to the polling ~, and if the service acquisition fails, it will be carried out within the specified time and try again
    public RestTemplate getRestTemplate(){
        return new RestTemplate();

The dao interface of springcloud-provider-dept-8001 calls pojo under the springcloud API module. You can use the pom file in springcloud-provider-dept-8001 to import the methods that the springcloud API module depends on:

 <!--We need to get the entity class, so we need to configure it api module-->

POM of springcloud-consumer-dept-80 and springcloud-provider-dept-8001 XML has basically the same dependencies as the parent project.

Keywords: Java architecture Microservices

Added by dougmcc1 on Thu, 03 Feb 2022 08:50:45 +0200