[Spring cloud series tutorials] basic knowledge of microservices, simulated microservices and service registration

1. Basic knowledge of microservices

Architecture evolution process

  • SOA

    • advantage:

    • A service can be called by multiple systems

    • Services can be deployed in clusters to solve the pressure

    • Reducing system coupling based on ESB/Dubbo

    • Disadvantages:

    • The granularity of extracting services is large

    • Service callers and providers are highly coupled

  • Microservice architecture


-Disadvantages: there are too many micro services and the cost of service governance is high, which is not conducive to system maintenance
-High cost of distributed system development technology (fault-tolerant distributed transaction)

  • Microservices and SOA

Some core concepts of Architecture

Remote call technology: http rpc

  • RPC (Remote Procedure Call)
  • http
    • Restful

CAP principle

  • CAP principle, also known as CAP theorem, refers to distributed system In, Consistency, Availability and Partition tolerance cannot be combined.

    • C onsistency: in distributed system Whether all data in the backup have the same value at the same time. (equivalent to all nodes accessing the same latest data copy)

    • Availability (A): after some nodes in the cluster fail, colony Whether the whole can respond client Read and write requests. (high availability for data updates)

    • Partition tolerance (P): in terms of practical effect, partition is equivalent to the time limit requirement for communication. If the system cannot reach data consistency within the time limit, it means that partition occurs, and the current operation must be selected between C and A.

    The essence of CAP principle is either AP, Cp or AC, but there is no CAP. If there is no copy of data in a distributed system, the system must meet the strong consistency condition, because there is only one data, and there will be no data inconsistency. At this time, C and P elements are available. However, if the system has network partition or downtime, some data will not be accessible. At this time, the availability condition cannot be met, that is, the Cp system is obtained, However, CAP cannot be satisfied at the same time. Cp (zookeeper is not available externally when synchronizing data)

    Therefore, in the design of distributed architecture, we must make trade-offs. At present, the performance of the system is generally improved by the final consistency of each node in the distributed cache, and the clustered data consistency is realized by using the data asynchronous replication technology between multiple nodes. NOSQL such as memcached is usually used as an implementation means. Although memcached can also be in a distributed cluster environment, for a piece of data, it is always stored on a memcached server. In case of network failure or server crash, all data stored on this server will be inaccessible. Since the data is stored in memory, restart The server , will result in all data loss. Of course, you can also implement a set of mechanisms to synchronize and persist data between distributed memcached, but the implementation is very difficult.

2. spring cloud overview

  • 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.
    SpringCloud makes use of the development convenience of SpringBoot to skillfully simplify 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 competition, distributed session and so on. They can use the development style of SpringBoot to achieve one click Startup and deployment.
    SpringBoot doesn't build wheels repeatedly. It just combines the relatively mature service frameworks developed by various companies and can stand the actual test, re encapsulates them through the SpringBoot style, shields the complex configuration and implementation principles * *, and finally leaves a set of distributed system development kit that is easy to understand, deploy and maintain for developers*

  • What is the relationship between SpringCloud and SpringBoot?

    • Focus on the rapid development of individual SpringBoot services.
      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, such as configuration management, service discovery, circuit breaker, routing, micro agent, event bus, global lock, decision-making campaign, distributed session and so on
      SpringBoot can use development projects independently of SpringCloud, but SpringCloud is inseparable 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.
  • Core components

    • Service Registry - Netflix Eureka

      Client load balancing - Netflix Ribbon

      Client load balancing - Feign

      Fuse - Netflix Hystrix

      Service gateway - Netflix Gateway(Zuul)

3. Analog microservice

  1. maven create parent project spring_cloud_demo

      <groupId>com.zdc</groupId>
        <artifactId>spring_cloud_demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <parent>
            <artifactId>spring-boot-starter-parent</artifactId>
            <groupId>org.springframework.boot</groupId>
            <version>2.1.6.RELEASE</version>
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.4</version>
                <scope>provided</scope>
            </dependency>
        </dependencies>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>Greenwich.RELEASE</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
  2. Create sub module product_service

     <dependencies>
             <dependency>
                 <groupId>mysql</groupId>
                 <artifactId>mysql-connector-java</artifactId>
                 <version>8.0.18</version>
             </dependency>
             <dependency>
                 <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-starter-data-jpa</artifactId>
             </dependency>
         </dependencies>
    

    Database table

    create table shop
    (
        id           int auto_increment
            primary key,
        product_name varchar(40)    null comment 'name',
        status       int            null comment 'state',
        price        decimal(10, 2) null comment 'Unit Price',
        product_desc varchar(255)   null comment 'describe',
        caption      varchar(255)   null comment 'title',
        inventory    int            null comment 'stock'
    )engine=InnoDB auto_increment=3;
    

    Create application yml

    server:
      port: 9001
    spring:
      application:
        name: service-product
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/zdc
        username: root
        password: zdc200816
      jpa:
        database: mysql
        show-sql: true
        open-in-view: true
    

    Create entity, dao, service and controller

    @RestController
    @RequestMapping("/product")
    public class ProductController {
        @Autowired
        private ProductService productService;
    
        @RequestMapping(value = "/{id}",method = RequestMethod.GET)
        public Product findById(@PathVariable Long id){
            Product product = productService.findByID(id);
            return product;
        }
    
        @RequestMapping(value = "",method = RequestMethod.POST)
        public String save(@RequestBody Product product){
            productService.save(product);
            return "Saved successfully";
        }
    }
    
  3. Create sub module order_service is the same as above (Name: service consumer)

    @RestController
    @RequestMapping("/order")
    public class OrderController {
        /*1.Commodity entity class required
         * 2.How to call Commodity services?
         * Using urlconnection httpclient okhttp
         * spring restTemplate is provided: a getRestTemplate object is created in the startup class and managed by the container.
         * */
        @Autowired
        private RestTemplate restTemplate;
    
        @RequestMapping(value = "/buy/{id}", method = RequestMethod.GET)
        public Product findById(@PathVariable Long id) {
            Product product = restTemplate.getForObject("http://127.0.0.1:9001/product/1", Product.class);
            return product;
        }
    }
    
    
  4. RestTemplate

    • Using urlconnection httpclient okhttp

    • Spring is used to synchronize the core classes of the client side, simplify the communication with HTTP services, and meet the RestFul principle. The program code can provide it with a URL and extract the results. By default, RestTemplate depends on the HTTP connection tool of jdk by default. Of course, you can also switch to different HTTP sources through the setRequestFactory property, such as Apache HttpComponents, Netty and OkHttp.

  5. Disadvantages:

    • Hard code the microservice request path into java code.
    • The same service can have multiple servers, and load balancing is required Gateway required.
    • Configuration information can be managed in the same.
    • Link tracking

4. Service registration

  • Also known as service center, it manages various service functions, including service registration, discovery, fusing, load, degradation, etc.
  • "Address book" manages the mapping relationship between service and service address. Any service cannot be directly removed from use, and it needs to be called through the registry. Get the service through the service center. You don't need to pay attention to the IP address of the project you call. It is composed of several servers. You can directly go to the service center to get the available service each time.
  • effect:
    • Service discovery: each micro service will register its own information with Eureka Server.
      • Service registration / de registration: save the information of service providers and service callers
      • Service subscription / unsubscribe: the service caller subscribes to the information of the service provider
      • Service Routing: it has the ability to filter and integrate service providers
    • Service configuration
      • Configure subscription: service providers and callers subscribe to micro service related configurations.
      • Configuration distribution: actively push the configuration to the provider and caller
    • Service health check
      • Check the health of the service provider.

The registry also checks service providers at intervals.

  • Common registry
    • zookeeper
      • Zoomeeper is a distributed file system. Every time a service provider deploys, it must register its service to a path of zoomeeper: / {service}/{version}/{ip:port}. For example, if our HelloWorldService is deployed to two machines, two directories will be created on zoomeeper: HelloWorldService / 1.0.0/100.19.20.01:16888 / HelloWorldService / 1.0.0/100.19.02:16888.
      • To register a service in zookeeper is actually to create a znode node in zookeeper, which stores the IP, port, calling mode (protocol, serialization mode) of the service. This node bears the most important responsibility. It is created by the service provider (when publishing the service) for the service consumer to obtain the information in the node, so as to locate the real network topology location of the service provider and know how to call it.
    • Eureka
    • Consul based on go
    • Nacos (developed by ALI)

Tags: Java Database Distribution Zookeeper Spring Cloud Spring Boot

Posted by srihari3d2010 on Thu, 14 Apr 2022 09:07:29 +0930