“This is the 16th day of my participation in the First Wenwen Challenge 2022.First challenge in 2022”

SpringCloud microservices distributed

Software Industry Classification:

Traditional software industry Internet software industry

Software Architecture Categories:

Microservices unit architecture

Single application

An archive package (which could be a JAR, WAR, EAR, or other archive format) contains all the functional applications,Often referred to asMonomer application. advantages

  • Ease of sharing: A single archive contains all functionality and is easy to share between teams and different phases of deployment.
  • Easy to test: Once a single application is deployed, all services or features are available, simplifying the testing process. Because there are no additional dependencies, each test can begin as soon as the deployment is complete.
  • Easy to deploy: just copy a single archive to a single directory.

disadvantages

  • High complexity: Because it is a single archive file, one file equals the entire project, and the file contains many modules, resulting in blurred boundaries of modules. Unclear dependencies, uneven quality of code, and jumbled piles made the project complex. So every time you make a change to your code, you’re very careful, adding a simple feature or modifying a Bug will bring a hidden Bug.
  • Technical debt: Over time, requirements change, and technical staff change, an application’s technical debt builds up and accumulates.
  • Limited scalability: A single application can only be expanded as a whole, but cannot be scaled based on service modules. (In order to improve the project performance, you can copy a project to deploy multiple servers ~)
  • Impeding technology innovation: For individual applications, technologies are carefully evaluated and selected prior to development, and every team member must use the same development language, persistent storage, and messaging system.

Micro service

In 2014, Martin Fowler proposed: Microservices Architecture Style. Commonly heard: Distributed microservices

Advantages: An application is split into a set of small services Each service:Runs in its own process, that is, can be independently deployed and upgraded, has its own independent database. Communicate with each other through HTTP. •advantages• Services can be split around business functions • Can be deployed independently by fully automated deployment mechanisms • Microservices can be developed independently by small teams of 2 to 5 developers. • Microservices are loosely coupled, functional services that are independent at both development and deployment stages. •decentralized, service autonomy. Services can use different languages and storage technologies.As long as the function can be ~Microservices are just code for business logic, not mixed with HTML,CSS, or other interface components.Each microservice has its own storage capacity and can have its own database. You can also have a unified database. Above:Micro-service distributed architecture, each point represents a function, use only need to call the required combination of functional modules! Disadvantages:

  • Operations are demanding: more services mean more operations.
  • Inherent complexity of distribution: You build distributed systems with microservices. For a distributed system, system fault tolerance, network latency, distributed transactions and so on all bring huge problems.
  • High cost of interface adjustment: Microservices communicate through interfaces. If you change the API of a microservice, it is possible that all microservices that use this interface will need to be adjusted. Remote invocation, service discovery, load balancing, service fault tolerance, configuration management, service monitoring, link tracing, log management, task scheduling… .

Relevant concepts

The Provider and Consumer

In distributed microservice architecture, an application is divided into multiple functional modules. Each functional module focuses on doing its own thing.. When you need to achieve a certain function, you only need to call each other directly to multiple functional modules…. So each module is both a Provider and a Consumer…

RPC and Restful

What is the RPC

  • Remote Procedure CallRemote procedure callIt is a kind ofInterprocess communication modeIt is a technical idea, not a norm. It allows a program to call a procedure or function in another address space, usually on another machine on a shared network, without the programmer explicitly coding the details of this remote call.That is, programmers write essentially the same calling code whether they call local or remote functions. Network communication

What is the REST

  • REST is a kind ofArchitectural style, refers to a set of architectural constraints and principles.
  • An application or design that satisfies these constraints and principles is RESTful.
  • The REST specification treats everything as a resource, and everything on the web is a resource.
  • REST does not create new technologies, components, or services, but simply uses the existing features and capabilities of the Web.
  • It can be fully implemented through HTTP protocol, using HTTP protocol to handle data communication.
  • The operations performed by REST architecture on resources, including obtaining, creating, modifying, and deleting resources, correspond to the GET, POST, PUT, and DELETE methods provided by HTTP.
  • I learned this in MVC before..

distributed

When an application is broken down into multiple functional modules,Do different things!

The cluster

A server, can not bear a certain work, in order to reduce the server pressure, do cluster load average price… Multiple devices do the same thing!

Choose SpringCloud as a microservice

Selection on the basis of

  1. Overall solution and framework maturity
  2. Community heat
  3. maintainability
  4. The learning curve

What are the microservices architectures currently in use by IT companies?

  1. Dubbo/HSF ali
  2. Jingdong JSF
  3. Motan on Sina Weibo
  4. Dangdang DubboX

Comparison of microservice frameworks

Distributed basic theory

What is a distributed system?

“Distributed System Principle and Paradigm” defines: “A distributed system is a collection of several independent computers, which are like a single related system for users.” A distributed system is a software system built on the network.

evolution

Single application Architecture — Vertical application Architecture — Distributed services Architecture — Mobile computing architecture

Single application Architecture

When site traffic is low, only one application is needed to deploy all functions together to reduce deployment nodes and costs. At this point, data access frameworks (ORM) that simplify the work of adding, deleting, modifying and reviewing are key.Suitable for small websites, small management systems, all functions are deployed into one function, easy to use.Disadvantages:Performance expansion is difficult. Collaborative development is not conducive to upgrade and maintenance.

Vertical application Architecture

When the number of visits gradually increases, the acceleration caused by the increase of a single application becomes less and less, and the application is split into several unrelated applications to improve efficiency. At this point, a Web framework (MVC) for accelerating front-end page development is key.

Independent deployment of each module is realized by business segmentation:This simplifies maintenance and deployment, makes it easier to manage teams with different roles, and makes performance scaling easier and more targeted.Disadvantages: Common modules can not be reused, wasteful development

Distributed Service Architecture

With the increasing number of vertical applications, the interaction between applications is inevitable. Core businesses are extracted as independent services, gradually forming a stable service center, so that front-end applications can respond to changing market demands more quickly. At this point, the distributed Services framework (RPC) for business reuse and integration is key.

Mobile Computing Architecture

As the number of services increases, problems such as capacity evaluation and waste of small service resources gradually emerge. In this case, a scheduling center needs to be added to manage cluster capacity in real time based on access pressure to improve cluster utilization. Service Oriented Architecture (SOA), which improves machine utilization, is key.

SpringClond starts application development

The difference between SpringBoot and SpringCloud

  • SpringBoot focuses on developing individual microservices quickly and easily.
  • SpringCloud is a global microservices coordination and consolidation governance framework that integrates and manages individual microservices developed by SpringBoot: Provide configuration management, service discovery, circuit breaker, routing, micro proxy, event bus, global lock, decision campaign, distributed session and other integrated services between microservices…
  • SpringBoot can be used independently of SpringCloud development projects, but SpringCloud cannot be separated from SpringBoot, belonging toDependent relation
  • SpringBoot focuses on developing individual microservices quickly and easily
  • SpringCloud focuses on a global service governance framework.

Set up springCloud projectDistributed Service Architecture

Create a normal Maven project

To facilitate the development of advanced applications using Maven… Development projects: Of course, you can also test multiple projects without Using Maven…

Delete SRC from the main project

Master of engineeringpom.xmlTo add public dependencies

 
      
 <project xmlns="http://maven.apache.org/POM/4.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
 ​
     <groupId>org.example</groupId>
     <artifactId>SpringCloudBJ</artifactId>
     <packaging>pom</packaging>
     <version>1.0 the SNAPSHOT</version>
     
     <! The Maven parent project contains the management child project... -->
     <modules>
         <module>common_api</module>
         <module>common_orderService</module>
         <module>common_userService</module>
     </modules>
 ​
     <! -- SpringBoot parent dependency -->
     <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>2.1.6. RELEASE</version>
     </parent>
 ​
     <! Create Maven JDK environment -->
     <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>
         <! -- Spring-boot web dependency -->
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
         </dependency>
         <! -- Spring-boot application log dependency -->
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-logging</artifactId>
         </dependency>
         <! -- Unit test dependencies for spring-boot -->
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
         </dependency>
         <! Lombok is a plugin for lombok. Don't forget to download Idea Lombok.
         <dependency>
             <groupId>org.projectlombok</groupId>
             <artifactId>lombok</artifactId>
             <version>1.18.4</version>
             <scope>provided</scope>
         </dependency>
     </dependencies>
 ​
     <! -- Specify SpringCloud configuration required!! -->
     <dependencyManagement>
         <dependencies>
             <dependency>
                 <groupId>org.springframework.cloud</groupId>
                 <artifactId>spring-cloud-dependencies</artifactId>
                 <version>Greenwich.RELEASE</version>                <! - version... -->
                 <type>pom</type>
                 <scope>import</scope>
             </dependency>
         </dependencies>
     </dependencyManagement>
 ​
     <! Maven's default download resource.. -->
     <repositories>
         <repository>
             <id>spring-milestones</id>
             <name>Spring Milestones</name>
             <url>https://repo.spring.io/milestone</url>
             <snapshots>
                 <enabled>false</enabled>
             </snapshots>
         </repository>
     </repositories>
 </project>
Copy the code

About SpringCloud version: Greenwich

SpringCloud releases update very quickly! A B C D E F G HSo far it's up to HI gather together!!!!! At the beginning of 2021

Create Maven subproject common_API entity module

The main storage project development needs entity class…

There is only one entity class… Nothing too complicated to do with order.java

 import lombok.AllArgsConstructor;
 import lombok.Data;
 import lombok.RequiredArgsConstructor;
 @Data
 @AllArgsConstructor
 @RequiredArgsConstructor
 // Create an entity class: and produce the corresponding constructor,toString(), according to Lombok and its annotations; get/set...
 public class Order {
     private Integer id;
     private String title;
     private Double price;
     private Integer uid;
 }
Copy the code

Pom.xml does not require any additions or changes.. Take a look at how my other Maven subprojects call;

 
      
 <project xmlns="http://maven.apache.org/POM/4.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <parent>
         <artifactId>SpringCloudBJ</artifactId>
         <groupId>org.example</groupId>
         <version>1.0 the SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>common_api</artifactId>
 </project>
Copy the code

Create Maven subproject common_orderService order module

Write the order module relative to the code… pom.xml

 
      
 <project xmlns="http://maven.apache.org/POM/4.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <parent>
         <artifactId>SpringCloudBJ</artifactId>
         <groupId>org.example</groupId>
         <version>1.0 the SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 ​
     <artifactId>common_orderService</artifactId>
 ​
     <! -- Key!! -->
     <dependencies>
         <! -- common_orderService project introduced common_API -->
         <dependency>
             <groupId>org.example</groupId>
             <version>1.0 the SNAPSHOT</version>
             <artifactId>common_api</artifactId>
         </dependency>
     </dependencies>
 </project>
Copy the code

OrderService.Java

 import com.wsm.entity.Order;
 import org.springframework.stereotype.Service;
 import java.util.ArrayList;
 import java.util.List;
 @Service
 public class OrderService {
     // Simulate fake order set...
     private static List<Order> orders = new ArrayList<>();
     // Class load gets some data by default.. Simulated fake orders..
     static {
         orders.add(new Order(1."The order 11".10.0.1));
         orders.add(new Order(2."Order 21".10.0.2));
         orders.add(new Order(3."Order 31".10.0.1));
         orders.add(new Order(4.41 "order".10.0.2));
     }
     // Get the order set according to the input user ID..
     public List<Order> findOrderByUser(Integer uid) {
         List<Order> myorders = new ArrayList<>();
         // Go through the collection to get uid consistent data stored in the collection returns...
         for (Order order : orders) {
             if(order.getUid() == uid) { myorders.add(order); }}returnmyorders; }}Copy the code

OrderController.Java

 import com.wsm.entity.Order;
 import com.wsm.service.OrderService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RestController;
 import java.util.List;
 @RestController
 public class OrderController {
     @Autowired
     private OrderService os;
     //REST style request..
     @GetMapping("/findOrderByUser/{uid}")   // Parameters are accessed with/request name /{parameter 1}/{parameter 2}...
     public List<Order> findOrderByUser(@PathVariable Integer uid){
         //REST style parameters need to be retrieved using @pathVariable!!
         returnos.findOrderByUser(uid); }}Copy the code

The main project class of SpringBoot:MyOrderServer.Java

 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 @SpringBootApplication
 public class MyOrderServer {
     public static void main(String[] args) { SpringApplication.run(MyOrderServer.class, args); }}Copy the code

SpringBoot application.ymlThe configuration file

 server:
   port: 6001            # set port 6001 to 6001
 spring:
   application:
     name: order-server  # set the name of the micro service, the following registration/call service is based on this;
Copy the code

Create the Maven subproject common_userService user module

Write the user module relative to the code…

pom.xml

 
      
 <project xmlns="http://maven.apache.org/POM/4.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <parent>
         <artifactId>SpringCloudBJ</artifactId>
         <groupId>org.example</groupId>
         <version>1.0 the SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>common_userService</artifactId>
 ​
     <dependencies>
         <! -- common_userService -->
         <dependency>
             <groupId>org.example</groupId>
             <version>1.0 the SNAPSHOT</version>
             <artifactId>common_api</artifactId>
         </dependency>
     </dependencies>
 </project>
Copy the code

UserService.Java

@service @slf4j // Load lo4g using... public class UserService { @Autowired private RestTemplate restTemplate; // Network communication via restTemplate returns.. Data from other remote modules (although now all local but emulated) Public List<Order> currentUserOrder(Integer uid) {log.info(" user service calling Order service "); // Hard coded call!! All the requests here are dead... This good? This is bad... Modify later; String myurl = "http://localhost:6001/findOrderByUser/" + uid; log.info(myurl ); List<Order> list = restTemplate.getForObject(myurl, List.class); return list; }}Copy the code

UserController.Java

 // The programming control layer accepts the request response result
 @RestController
 public class UserController {
     @Autowired
     private UserService userService;
 ​
     @GetMapping("/showUserOrder")
     public List<Order> showUserOrder(Integer uid){
         return userService.currentUserOrder(uid);   // Invoke the Service layer
         //Service is the result of calling the order module through the network, so the order module is running.}}Copy the code

The main project class of SpringBoot:MyUserServer.java

 @SpringBootApplication
 public class MyUserServer {
     public static void main(String[] args) {
         SpringApplication.run(MyUserServer.class, args);
     }
 ​
     @Bean
     // Instantiate RestTemplate to facilitate Service
     // Don't forget the @SpringBootApplication composite annotation can have @SpringBootConfiguration, which is also a Spring configuration class!
     public RestTemplate createRestTemplate(a) {
         return newRestTemplate(); }}Copy the code

SpringBoot application.ymlThe configuration file

 server:
   port: 6002            # set port 6002 for multiple microservices
 spring:
   application:
     name: user-server   # set the name of the micro service, the following registration/call service is based on this;
Copy the code

The service call

Three basic microservices have been written above. When users place an order, they need to call the commodity microservice to obtain commodity data. Commodity microservices provide HTTP interfaces for people to call

  • You can place orders using HTTP request classes, such as HttpClient, OkHttp, or Spring’s RestTemplate

RestTemplate introduction

Spring framework provides RestTemplate class that can be used to invoke REST services in applications. It simplifies communication with HTTP services, harmonizes RESTful standards, and encapsulates HTTP links

  • We just pass in the URL and the return value type. Compared to the usual HttpClient,
  • RestTemplate is a more elegant way to invoke RESTful services.
  • The RestTemplate class is designed with the same principles as many other Spring template classes (such as JdbcTemplate, JmsTemplate) to provide a simplified method with default behavior for performing complex tasks.
  • RestTemplate relies on the JDK’s ability to provide HTTP connections by default (HttpURLConnection) or, if needed, replace it with, for example, Apache via the setRequestFactory method Other HTTP libraries such as HttpComponents, Netty, or OkHttp.
  • Given that the RestTemplate class is designed to invoke REST services, it is not surprising that its main methods are closely tied to the REST foundationThe latter are HTTP protocol methods :HEAD, GET, POST, PUT, DELETE, and OPTIONS. The RestTemplate class has methods such as headForHeaders(), getForObject(), postForObject(), PUT (), and DELETE ().

Problems with hard coding

At this point, you can invoke the RESTFul API of the commodity microservice from the RestTemplate. However, we hardcoded the provider’s network address (IP, port) into the code, which has many problems:

  • Application scenarios are limited
  • Unable to adjust dynamically
  • . So how to solve it, we need to: registry dynamic service registration and service discovery

conclusion

Down ↓↓↓ Because it is the user module – reference – order module the order module is the provider provide the user is the caller Consumer

  • If the order module service is not opened, it will affect the use of the user module! Attention!
  • And corresponding to a large number of calls between modules, with the expansion of the project business… References between modules will also become more complex!!
  • For module A service is stopped, module B service is affected… What if it intensifies? Module C, module D… B depends on AC depends on BD depends on C and at this time A does not cause the collapse of the service between!

To solve this problem,The registryarise

Service registration Eureka base

The registry can be said to be the “address book” in the microservice architecture, which records the service and service address mapping relationship. In the distributed architecture, the service will be registered here. When the service needs to call other services, it will find the address of the service here and call it.

The main role of the registry

The service registry is a very important component of the microservice architecture and plays a role of coordinator in the microservice architecture. Registries generally contain the following functions:

  • Service discovery: Providers/callers need registration declarations in the registry to use each other. Service registration/unregistration: Saves the information of service providers and service callers. Service subscription/unsubscription: Service callers subscribe to the information of service providers, preferably with real-time push function. Service Routing (optional) : has the ability to filter and consolidate service providers.
  • Service configuration: Code, the service provider/scheduler needs to configure the registry configuration subscription: service providers and service callers subscribe to microservices-related configurations Configuration delivery: actively push configurations to service providers and service callers
  • Service health inspection services to provide regular heart ♥ to the registry tell the registry I still can work, of course, the registry generally have self-protection mechanism… Monitor the health of the service provider

A common registry

  • Zookeeper Zookeeper is a distributed service framework. It is a subproject of Apache Hadoop. Zookeeper is used to solve data management problems frequently encountered in distributed applications, such as unified naming service, status synchronization service, cluster management, and distributed application configuration item management. Zookeeper = file system + listener notification mechanism.
  • Eureka Eureka is an important component of Springcloud Netflflix, which is a service registration and discovery component developed based on Restful Api in Java language
  • Consul is a multi-data center distributed and highly available service publishing and registration software developed by HashiCorp based on the Go language, which uses Raft algorithm to ensure service consistency and supports health checks
  • Nacos is a new open source project launched by Alibaba. Nacos is a dynamic service discovery, configuration management and service management platform that makes it easier to build cloud native applications. To put it simply, Nacos is a combination of registry and configuration center, providing easy-to-use feature set to help us solve the problems of service registration and discovery, service configuration, service management, etc., which will be involved in micro-service development. Nacos is also one of the Spring Cloud Alibaba components responsible for service registration and discovery.

The basic architecture of Eureka

Spring Cloud encapsulates Netflix’s Eureka, which uses c-S design architecture. Eureka Server serves as the Server for the service registry function. It is the service registry.

  • Clients using Eureka connect to Eureka Server and maintain a heartbeat connection.
  • In this way, the maintenance personnel of the system can monitor the normal operation of each micro-service in the system through Eureka Server.
  • Eureka consists of two components:Eureka ServerandEureka Client
  • EurekaServer provides service registration service. After each node is started, it registers in EurekaServer. In this way, the service registry in EurekaServer stores information about all available service nodes
  • EurekaClient is a Java client that simplifies Eureka Server’s interaction client and also has a built-in load balancer that uses round-robin load algorithms. After the application is started, the heartbeat is sent to the Eureka Server (default interval is 30 seconds). If EurekaServer does not receive a heartbeat from a node within multiple heartbeat cycles, EurekaServer will remove the node from the service registry (default: 90 seconds).

The three roles

  1. Eureka Server provides service registration and discovery
  2. Service Providers register their services with Eureka so that Service consumers can find them
  3. A Service Consumer obtains a list of registered services from Eureka and is able to consume services

To use, start the registry -- Provider Provider -- Consumer caller

Refactoring the SpringCloud projectMobile Computing Architecture

Based onSpringCloud's distributed services architectureThe development of

Create Maven subproject Eureka-ServerThe registry

pom.xml

 
      
 <project xmlns="http://maven.apache.org/POM/4.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <parent>
         <artifactId>SpringCloudBJ</artifactId>
         <groupId>org.example</groupId>
         <version>1.0 the SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>eureka-server</artifactId>
     <! -- Eureka-server service dependency, must! -->
     <dependencies>
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
         </dependency>
     </dependencies>
 </project>
Copy the code

application.yml

 server:
   port: 7001                Set the port of the registry.
 spring:
   application:
     name: eureka-server     # registry application name;
 # Configure the registry....
 eureka:
   client:
     service-url:
       defaultZone: http://localhost:7001/eureka/   # Registered address leaked from registry...
     # Do you want to go to the registry to get the addresses of other services, default to true (currently there is only one registry and currently the registry..)
     fetch-registry: false
     # will allow you to inject yourself into the registry, default is true (currently there is only one registry and currently the registry.. Register yourself?)
     register-with-eureka: false        # If an application has two registries that can be enabled for the purpose of cluster registries...
Copy the code

The main application classMyEurekaServer.Java

 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
 @SpringBootApplication
 @EnableEurekaServer            // Comments main program to start Eureka service
 public class MyEurekaServer {
     public static void main(String[] args) { SpringApplication.run(MyEurekaServer.class, args); }}Copy the code

@EnableEurekaServer

Start the registry’s services, indicating that the current project serves as the registry in SpringCloud

Now the launcher can access the current registry…

Modify the above SpringBoot microservice registration to the registry!

Common_orderService /userService Register to the registry:

Load the registry service dependency

pom.xml

     <! -- Registration service dependency.. -->
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
         </dependency>
Copy the code

Add the @enableeurekaclient injection center to the main program

Take the main program for the order as an example, and do the same for everything else myOrderServer.java

 @SpringBootApplication
 @EnableEurekaClient
 public class MyOrderServer {
     public static void main(String[] args) { SpringApplication.run(MyOrderServer.class, args); }}Copy the code

@enableeurekaclient Starting the registry client indicates that the current main program is registered to the registry…

@enableDiscoveryClient is different from @enableeurekaclient

@enableDiscoveryClient: @enableeurekaclient is basically the same.

  • @enableEurekaclient is a dedicated startup registration for the Eureka registryannotations
  • @enableDiscoveryClient includes @enableeurekaclient, which is a unified EnableEurekaClient annotation for all registries…

Springboot. yml file for Eureka configuration

The configuration file configures the registry Eureka (for example, business Order) application.yml

 server:
   port: 6001            # set port 6001 to 6001
 spring:
   application:
     name: order-server  # set the name of the micro service, the following registration/call service is based on this;
 eureka:
   client:
     service-url:          # Change the IP address of the registry to the IP address of the wireless network to achieve multi-device connection...
       defaultZone: http://localhost:7001/eureka/    # specify a registry for service registration;
   instance:
     prefer-ip-address: true                         # use IP number on Eureka..
     instance-id: ${spring.cloud.client.ip-address}:${server.port}   # display IP number on Eureka..
Copy the code

Finally, don’t forget to add common_userServiceHard coding worked out

UserService.Java

 import com.wsm.entity.Order;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.cloud.client.ServiceInstance;
 import org.springframework.cloud.client.discovery.DiscoveryClient;      // DiscoveryClient
 import org.springframework.stereotype.Service;
 import org.springframework.web.client.RestTemplate;
 import java.util.List;
 @Service
 @Slf4j                  // Load lo4g using...
 public class UserService {
     @Autowired
     private RestTemplate restTemplate;
     // Network communication via restTemplate returns.. Data from other remote modules (although now all local but emulated)
 ​
     @Autowired              // Implement dynamic call...
     private DiscoveryClient discoveryClient;
 ​
     public List<Order> currentUserOrder(Integer uid) {
         // Get the microserver module instance on the registry according to the service name;
         // Return a collection: it is possible that the service exists on multiple registries, 'load balancing ~' is therefore a collection;
         List<ServiceInstance> instances = discoveryClient.getInstances("order-server");
         ServiceInstance serviceInstance = instances.get(0); // This time there is only one...
         log.info("User service invokes order service");
         // The service controller requests its parameter uid
         String myurl = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/findOrderByUser/" + uid;
 ​
         log.info(myurl);
         List<Order> list = restTemplate.getForObject(myurl, List.class);
         returnlist; }}Copy the code

Dynamically get IP from registry Eureka Check IP 192.168.1.1 here

  • windows+r
  • cmd
  • Enter ipconfig
  • If it is in the same network segment, different computers can be used through the same registry..But I don't have a WLAN configurator yet...
  • Change the code’s Eureka service configuration local to the wireless IP address under the same network. Services written by multiple devices connect to the same registry.. Can implement A, C computer – connect to B registry – A can go to B registry to call C services…
  • Try ~

Eureka’s service culling problem

~ configured on the service Client Default 30 seconds heartbeat 💓 90 seconds Renewal time..Service Client Configured on the Client.yml

 eureka:
   client:
     service-url:
       defaultZone: http://localhost:7001/eureka/    # specify a registry for service registration;
   instance:
     prefer-ip-address: true                         # display IP number on Eureka..
     instance-id: ${spring.cloud.client.ip-address}:${server.port}   # display IP number on Eureka..
     lease-renewal-interval-in-seconds: 5            The client sends heartbeat time to the registry
     lease-expiration-duration-in-seconds: 10        If there is no delayed renewal time for sending heartbeats...
Copy the code

If the client service is shut down for some reason. Eureka will remove your service based on heartbeat detection that you are gone…

  • Client timing directionThe registrySend heartbeat if over time no sendThe default 30 seconds
  • There will be a delayed wait time.The default 90 secondsTwo minutes ~If the service is not started, Eureka will remove the service.
  • But, becauseEureka self-protection mechanismThe service does not actually remove… Instead, you will be given a time if you have not come back ~ error!

Eureka self-protection mechanism

Self-protection is generally not turned off, because if the service is good and can be registered immediately to use it… Turn off protection on the server, in the registry… .yML for the registry

 # Configure the registry....
 eureka:
   client:
     service-url:            
       defaultZone: http://localhost:7001/eureka/   # Registered address leaked from registry... Follow the registry as provided ~
     # Do you want to go to the registry to get the addresses of other services, default to true (currently there is only one registry and currently the registry..)
     fetch-registry: false
     # will allow you to inject yourself into the registry, default is true (currently there is only one registry and currently the registry.. Register yourself?)
     register-with-eureka: false        # If an application has two registries that can be enabled for the purpose of cluster registries...
   server:
     enable-self-preservation: false      This is true by default
     eviction-interval-timer-in-ms: 4000  # default is 0 never cull!
Copy the code

The protection mechanism will report an error whenever it is turned off! And it will be removed whenever the service fails…

Nice finally finished, suggested triptych!!