Build Spring Cloud service from scratch

1. What is SpringCloud?

SpringCloud official website: https://spring.io/projects/spring-cloud (personal suggestion is to use Google Chrome to visit the official website to open the Chinese translation and read the official website roughly)

Organize the Spring Family Bucket related articles into PDF, pay attention to the WeChat public account Java backend, reply 666 to download this technology stack manual.

Personal understanding:

The previous server was like an all-around teacher who could speak a lot of words, providing services to students. If this teacher is sick, the whole school will be suspended. Now that microservices become popular, the school has a mathematics teaching and research group, a Chinese teaching and research group, and a foreign language teaching and research group. Each teaching and research group has a group of teachers who are specifically responsible for the teaching of a certain subject. If it is missing, the school will still operate.

In this change, those programmers who change history are to classify and decouple many services in one server, or many services in several servers, and give their similar functions to the same cluster. The functions that are coupled with each other are separated, and they are placed on the server as microservices according to business and function, and this server only provides one service, or fewer services.

Let a large service logic decouple into a small service, evenly distributed in each server. Microservices are here. Each teaching and research group is a microservice cluster. They provide the same service, and the registration center Eureka is the place where the teacher list of the teaching and research group is stored. Students want to visit the registration center to get the list of teachers, and then visit their teachers according to the corresponding load method. It will not let a teacher in the cluster be exhausted or let a teacher die idle.

The Zuul gateway is the guard of the school. Some students come to the school to find someone. It is responsible for guiding (routing), and through some very simple configurations, it can block some people from entering (identity verification), or control people who want to learn mathematics. You can only go to the mathematics teaching and research group, not the nuclear energy teaching and research group to learn how to build an atomic bomb (authority verification).

The Hystrix fuse can be regarded as a school volunteer. When a teaching and research group strikes collectively, students can’t find a teacher. These volunteers tell the visiting students in time, the corresponding results, abnormal information, etc., so as to avoid a lot of Of students are waiting at school. These volunteers hurriedly sort out the waiting students. Students have been waiting at the school. Other schools that need students will also wait for students, which will eventually paralyze a large area of ​​the school. Here we treat students as requests one by one. The fuse is to prevent the spread of an accident even if it is blown.

Of course, these components are also microservices that need to be registered in the Eureka registry

Then  Spring Cloud  can be regarded as this school. Many of the above-mentioned components are equivalent to various functional departments of the school.

ps: The blogger is based on Maven+idea. In addition, SpringCloud needs to be built based on springboot.

2.1 Introduce Spring Boot related dependenciesHere springboot uses version 1.5.7

Introduce Spring Cloud related dependencies here as  Edgware.SR5

2.1 Project initial configuration

Create a project in Idea: File -> New ->Project

 Click Empty Project -> Next

 Project Naming -> Project Location

 Select modules ->next

 After entering the new window, start to configure Maven, open the settings

 Because I have done the configuration before, so I only need to change the path of box 1. For example, the first configuration needs to find the location of your maven, as well as the location of settings.xml , repository . Baidu maven integration idea is really not

Click ok after selecting the 3 boxes

Next, create a new module

There may be a problem that the archetype list cannot be loaded

 After using all the solutions on the Internet, it took 3 hours to solve it and it was useless. After restarting, it will work. Do you believe it? ? ? ? ? When I was young, I forgot the most logical sayings of Internet cafes and web managers! ! Restart it! !

After coming out, select quickstart -> next

After thinking about the name for yourself, copy the ArtifactId you want and click Next. If groupId is the name of the organization, you also think of one yourself, usually the company website is reversed.

 Next step after pasting

 The pom.xml configuration of the server that provides registration services is as follows:

<?xml version="1.0" encoding="UTF-8"?>
 
<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>com.yun</groupId>
  <artifactId>springcloud-eureka-server</artifactId>
  <version>1.0-SNAPSHOT</version>
 
  <name>springcloud-eureka-server</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
 
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
 
  <!--引入springboot-parent父项目-->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.7.RELEASE</version>
  </parent>
 
  <dependencies>
    <!--引入springcloud的euekea server依赖-->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
 
  </dependencies>
 
 
  <!--指定下载源和使用springcloud的版本-->
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Edgware.SR5</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
</project>

 Click Import Changes 

Wait for the springcloud dependency to load in the lower right corner

 2.2  The construction of Springboot and the service configuration to provide registration services

Create resources folder

 And set it as the resource root directory, then the file becomes like this

After that, the folder becomes a yellow bar

 Create a new file under resources, the file name is application.yml (yml is not xml, when the blogger first learned, he thought it was other bloggers who made a mistake and stepped on a small hole) 

 Configure yml, note: if you only configure the first two lines of port number information, an error will be reported

server:
  port: 8700 # 端口自己决定
  
# 指定当前eureka客户端的注册地址,也就是eureka服务的提供方,当前配置的服务的注册服务方
eureka:
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka
    register-with-eureka: false #自身 不在向eureka注册
    fetch-registry: false #启动时禁用client的注册
  instance:
    hostname: localhost
 
#指定应用名称
spring:
  application:
    name: eureka-server

Knowledge supplement:

 Develop the entry class EurekaServerApplication.java for spring boot

 EurekaServerApplication.java

package com.yun;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
 
@SpringBootApplication
@EnableEurekaServer //当前使用eureka的server
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class,args);
    }
}

Right-click to run the current class:

Successfully run console screen

 Try to enter the eureka management interface. The port number is configured in yml (the port number needs to be greater than the public and reserved port number) 1024~65535

Generally I like to set it between 8700 and 8800

The following management interface can already log in

 2.3 The configuration of the role that the client provides the real service , it provides the service to register with the service registrant server (registration center)

Also create a new module, select quickstart and click Next

Two positions left blank

 Name the next step

 Note that the module must be created under the root directory springcloud. The content root will create the module under the previous module by default. This will cause problems and errors when creating the module.

This configuration method is recommended. Change the name after springcloud under the content root. Click Next to configure as shown below. The red box generally defaults to the file directory name of the previous module, and you need to change your module name

 After success, it will be in a parallel state. If it is not in parallel or an error, please reconfigure

 Configure the servicesupport pom, which is the same as the server pom configuration, only need to change the server in the box 1 of the first pom to client

Similar to the first microservice, we need to configure the entry class  pom.xml   application.yml, because it is a service provider, here we need to write a service class controller

application.yml

server:
  port: 8701 # 服务提供方
 
# 指定当前eureka客户端的注册地址,
eureka:
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:8700/eureka
  instance:
    hostname: localhost
 
#当前服务名称
spring:
  application:
    name: eureka-service

pom.xml:

Write the provided service controller :

@RestController
@RequestMapping("/Hello")
public class Controller {
    @RequestMapping("/World")
    public String helloWorld(String s){
        System.out.println("传入的值为:"+s);
        return "传入的值为:"+s;
    }
}

Entry class  and run this microservice:

@SpringBootApplication
@EnableDiscoveryClient//代表自己是一个服务提供方
public class EurekaServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServiceApplication.class,args);
    }
}

 Right-click the entry class name and click run (Of course, you need to open the server service first when you open this service, which is the first microservice we wrote)

 At this point, enter the service registration page http://localhost:8700/

You can see that the service provider has been registered as the  service registrar

 Directly visit the network location of the service provider http://localhost:8701/Hello/World?s=小沛

We have seen that it is accessible, proving that this microservice is available.

 

 However, we generally do not directly call the required microservices, but obtain a list of required service providers (a list, this list contains servers that can provide corresponding services) through the server server that provides registered services . They may be a Cluster, so the server will return a table of ip+port numbers. Service consumers access different servers on this table through the corresponding algorithm. These servers provide the same service. This way of choosing servers to serve themselves on the service consumer side It is a client-side load balancing.

At present, bloggers know that there are two ways to access these servers:  polling and random . Polling means looping. If there are 3 servers, the access method is 1, 2, 3, 1, 2, 3, 1, 2, 3···· Random is random. Recall the random method, an irregular method. Both of these methods are for the same possibility of accessing each server. There is also a weighted load algorithm, which means that the corresponding service is allocated according to the server load capacity. The more capable ones do much. Little ability does less.

2.4 How to call the service

The first calling method: restTemplate+ribbon     

 The second calling method: feign 

 2.4.1 restTemplate + ribbon   

ribbon is a load balancing client. What is it? Please read https://www.jianshu.com/p/1bd66db5dc46

You can see the following paragraph:

The biggest difference between client-side load balancing and server-side load balancing is the location where the service list mentioned above is stored . In client load balancing, all client nodes maintain a list of servers they want to access, and these server lists come from the service registry , such as the Eureka server we introduced in the previous chapter.

Similar to the architecture of server-side load balancing, in client-side load balancing, a heartbeat is also required to maintain the health of the server-side list . By default, Ribbon automatic integration configuration for each service governance framework is created, such as org.springframework.cloud in Eureka. .netflix.ribbon.eureka.RibbonEurekaAutoConfiguration, org.springframework.cloud.consul.discovery.RibbonConsulAutoConfiguration in Consul. In actual use, we can help us use it better by looking at the implementation of these two classes to find their configuration details.

Next we will build a ribbon-based client, which is used for consumer services.

In the same way, first build the springboot environment

The difference from the previous servicesupport build is:

The first step: now need to add ribbon dependency in dependencies in pom

<dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>

 

Step 2: yml is configured as follows:

server:
  port: 8702 # 服务消费方
 
# 指定当前eureka客户端的注册地址,
eureka:
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:8700/eureka
  instance:
    hostname: localhost
 
#当前服务名称
spring:
  application:
    name: eureka-consumer

 The consumer of the service still needs to register on port 8700 of the registrant. Configure the port 8072 of the current service consumer , named eureka-consumer

The third step: still need to start the class, because it is a springboot architecture:

@SpringBootApplication
@EnableDiscoveryClient //当前使用eureka的server
public class EurekaConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaConsumerApplication.class,args);
    }
}

 As shown above:

We need a controller class to write ribbon code.

@RestController
@RequestMapping("/Hello")
class ConsumerController {
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;
    @RequestMapping("/Consumer")
    public String helloWorld(String s){
        System.out.println("传入的值为:"+s);
        //第一种调用方式
        //String forObject = new RestTemplate().getForObject("http://localhost:8071/Hello/World?s=" + s, String.class);
 
        //第二种调用方式
        //根据服务名 获取服务列表 根据算法选取某个服务 并访问某个服务的网络位置。
        //ServiceInstance serviceInstance = loadBalancerClient.choose("EUREKA-SERVICE");
        //String forObject = new RestTemplate().getForObject("http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/Hello/World?s="+s,String.class);
 
        //第三种调用方式 需要restTemplate注入的方式
        String forObject = restTemplate.getForObject("http://EUREKA-SERVICE/Hello/World?s=" + s, String.class);
        return forObject;
    }
}

We often use the third calling method.

The first is to call directly: servicesupport that is directly accessed without going through the service list of the registration center

The second type: select the call based on the service name, as shown in the figure above, you need to do the following injection   

    @Autowired
    private LoadBalancerClient loadBalancerClient;

As shown in the code of the second calling method in the code above.

Use the service name to go to the registry to get the service list, and the current bottom layer of the client will do a random algorithm selection to get the service and access it.

The third type requires a @Bean annotation to be automatically injected and directly call the restTemplate object to call the service. The bottom call mode is the same as the second call mode. as follows:

@Configuration
public class Beans {
    //管理简单对象
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

The @Bean annotation tells the factory that this method needs to be injected automatically.

@LoadBalanced means that load balancing is required.

Then inject restTemplate like the controller, and use it, the difference is that you can directly use the service name to access

String forObject = 

restTemplate.getForObject("http://EUREKA-SERVICE/Hello/World?s=" + s, String.class);

 start testing:

1. Run the server startup class:

 2. Run the startup class of servicesupport:

 3. Run the startup class of serviceconsume:

 Browser access:

 8072 is the port of the service consumer

 Access method analysis:

  • Access the path specified by the service consumer @RequestMapping and the consumer's port to access the consumer's controller

  • The controller obtains the service list from the server according to the service name. After obtaining the service list, the load balances according to the random pattern and then selects the service address to access servicesupport: as shown below

 

2.5 High availability configuration of Eureka server

Click the figure below to configure

Next, configure three virtual machine parameters of 01, 02, 03

01:8699

 02:8698

 03:8697 

 Then click ok to save, you can see three more startup items

 Next, change the registered port number separately, defaultZone starts three startup items respectively

Open the yml configuration of the server and delete the first two lines of port number configuration (there is an error in the figure, please delete the two lines of instance and hostname)

 Click start after configuring yml 

 In the same way, after we change the port number to 8699 and 8697 again, we change the startup item to 02, and then start (there is an error in the figure, please delete the two lines of instance and hostname)

 Similarly, after changing the yml port to 8699 and 8698, change the startup item to 03, and then start (there is an error in the figure, please delete the two lines instance and hostname) 

 After starting, visit the three ports 01, 02, and 03 respectively, and you can see and visit them.

 Open the yml configuration of the service provider as follows, and change the port number to one of the three.

 After starting the service provider, visit the three 01, 02, and 03 again and we will find

Important: Even if the service provider only registers one port number 8699, but the other two port numbers can still sense the existence of the service provider 8701. As shown below:

 Next, add the port number of the service registrant to the service consumer, so that when any server hangs up, other servers can also get the service list

 Visit the following service consumer and find that you can call the server service list through the consumer and access the service

 We just shut down two copies of the server, restart serviceconsume, and then visit. You must restart serviceconsume to clear the cache and clear the list of services in the consume.

 The above figure shows that even if the two servers are closed, it can still be accessed. As shown in the figure below, the service list is still obtained from the server, and it can be seen that there is no need to obtain the service list afterwards.

 But when we shut down all servers. The access is still okay because the service list is cached.

 But let's restart serviceconsume, it won't work again.

In summary, we have completed the high availability configuration of the server in springcloud

Guess you like

Origin blog.csdn.net/baidu_39322753/article/details/110237488