preface

SpringCloud is a complete framework for implementing microservices based on SpringBoot. It provides configuration management, service discovery, circuit breakers, intelligent routing, microproxy, control bus, global locking, decision campaign, distributed session, and cluster state management components required for microservice development. Most importantly, working with the Spring Boot framework makes it very convenient for you to develop cloud services with microservices architecture. SpringBoot is designed to simplify the creation of production-grade Spring applications and services, simplifies configuration files, uses an embedded Web server, and has many out-of-the-box microservices capabilities. (Above content from Baidu)

In plain English, SpringCloud is a set of tools that can be integrated with SpringBoot to help developers implement desired functionality. There are many sub-projects included in SpringCloud, so I take this opportunity to share with you my experience of learning each sub-project. Without further ado, let’s start with Eureka.

What is the Eureka

Eureka is a REST-based service primarily used for location services in the AWS Cloud for load balancing and failover of mid-tier servers. It is commonly used as a registry in the Spring Cloud microservices architecture. We call this service Eureka Server. There is also a Client that interacts with it called the Eureka Client.

This may be a bit abstract, the following directly on the code, listen to the xiao Di explain (xiao di use IDEA)…

Eureka-server Service registry

Here we need to use the Eureka module of Spring-Cloud, which is a service registration and discovery module. We will create a new Project (File==>new==>Project). Fill in the corresponding Group, artifactId and other information and click NextSelect Spring Cloud Discovery, then Eureka Server, and click Next ==>Finish. At this point, take a look at the POM.xml file in the new project

<? 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">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.32..RELEASE</version> <relativePath/> <! -- lookup parent from repository --> </parent> <modelVersion>4.0. 0</modelVersion>
    <groupId>com.springcloud</groupId>
    <artifactId>eureka</artifactId>
    <version>0.01.-SNAPSHOT</version>
    <name>eureka</name>
    <description>Demo project for Eureka</description>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring-cloud.version>Hoxton.SR10</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</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>
    <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

The eureka-Server package is not the same as the normal SpringBoot project pom. XML file. So how do we use the eureka-server package? It’s as simple as adding an @enableeurekaserver annotation to the startup class, as shown in the following code:

package com.springcloud.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

/** * Service Registry */
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {

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

Next, take a look at the appication. Yml file

server:
  port: 8081Eureka: instance: hostname:127.0. 01.Client: registerWithEureka:falseWhether to register yourself with the service registryfalseIf you want to retrieve the serviceUrl service registry configuration content, specify the location of the service registry.//${eureka.instance.hostname}:${server.port}/eureka/
Copy the code

It is important to note that Eureka is a highly available component that has no back-end cache and sends a heartbeat to the registry after each instance is registered (so it can be done in memory). By default, erureka Server is also a Eureka client and an Erureka server must be specified.

Let’s start the project directly and access it in a browserhttp://127.0.0.1:8081 At this time, we will find No instances available in the Application. This is because we have not registered yet, so we have not found any services. Let’s create another client.

Eureka – the Client to the Client

In a nutshell, clients provide metadata such as host, port, URL, and so on when registering with the registry. The registry (Eureka Server) also receives heartbeats from each Client (Eureka Client), and if the heartbeat times out, it is usually removed from the registry. The creation of Eureka Client is similar to that of Eureka Server, except that annotations and appication. Yml in the class file are started slightly differently.

eureka:
  client:
    serviceUrl: 
      defaultZone: http://127.0.0.1:8081/eureka/ # registry address
server:
  port: 8082Spring: Application: name: service-provider spring: application: name: service-providerCopy the code

Add the @enableeurekaclient annotation to the startup class to indicate that this is a client

package com.eurekaclient.eurekaclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/** * client */
@RestController
@EnableEurekaClient
@SpringBootApplication
public class EurekaclientApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaclientApplication.class, args);
    }

    /** * if the client wants to provide a getUser method *@return* /
    @GetMapping(value = "/getUser")
    @ResponseBody
    public Map<String,Object> getUser(@RequestParam Integer id){
        Map<String,Object> data = new HashMap<>();
        data.put("id",id);
        data.put("name"."liziye");
        data.put("date"."2021-05-18");
        returndata; }}Copy the code

At this point we can start the client project. At this point we need to ensure that the registry (server) is started, otherwise the client will fail to access the registry address during registration and will report an error.The successful startup of the client means that the client has successfully registered with the server. At this time, we will look at the page of the server and find that there is an extra registration information in the Application, that is, the information we just registered.If you are sharp-eyed, you will notice that there are two lines of red characters on this page. The red characters remind us that Eureka registered services are highly available. There is only one service detected here, so it does not have any impact.

We just defined a getUser method in the client startup class. Let’s access this addresshttp://127.0.0.1:8082/getUser?id=911 Obviously we’ve succeeded, and at this point some people might ask, who’s going to pay for all the services we’re providing? So let’s create a new consumer project.

Eureka – Consumer customers

Consumer projects and service center, client new way is the same, here we do not introduce the project establishment process, directly on the code.

<? 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0. 0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId>  <version>2.32..RELEASE</version> <relativePath/> <! -- lookup parent from repository --> </parent> <groupId>com.consumer1</groupId> <artifactId>consumer1</artifactId> <version>0.01.-SNAPSHOT</version>
    <name>consumer1</name>
    <description>Demo project for consumer1</description>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring-cloud.version>Hoxton.SR10</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</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>
    <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
package com.consumer1.consumer1;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;

import java.util.Map;

@RestController
@EnableEurekaClient
@SpringBootApplication
public class Consumer1Application {

    @Autowired
    RestTemplate restTemplate;

    public static void main(String[] args) {
        SpringApplication.run(Consumer1Application.class, args);
    }

    /** * Instantiate RestTemplate *@return* /
    @LoadBalanced
    @Bean
    public RestTemplate rest(a) {
        return new RestTemplate();
    }

    /** * Use RestTemplate to make an HTTP request and get the data back to the front end *@param id
     * @return* /
    @GetMapping(value = "/request")
    @ResponseBody
    public Map<String,Object> getUser(@RequestParam Integer id){ 
    	Map<String,Object> data = new HashMap<>();
        RestTemplate restTemplate = rest();
        data = restTemplate.getForObject("http://service-provider/getUser? id="+id,Map.class);
        returndata; }}Copy the code

Let’s start the consumer side to see how it works.After successful startup, let’s go to the registry to see if there is a new message.We can see that a new registration message has been added to the Application, which means that our consumer registered successfully. Now let’s implement the request method in the consumer again.It is clear that the implementation of Eureka is successful, the following key to the implementation of load balancing?

Eureka load balancing

We made a copy of the Eureka-Client, made a few minor changes (modifying the startup class and the appication. Yml file) and went straight to the code.

In the startup class we changed the name value in the getUser method to differentiate.

package com.client1.client1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@EnableEurekaClient
@SpringBootApplication
public class Client1Application {

    public static void main(String[] args) {
        SpringApplication.run(Client1Application.class, args);
    }

    /** * if the client wants to provide a getUser method *@return* /
    @GetMapping(value = "/getUser")
    @ResponseBody
    public Map<String,Object> getUser(@RequestParam Integer id){
        Map<String,Object> data = new HashMap<>();
        data.put("id",id);
        data.put("name"."yangyawang");
        data.put("date"."2021-05-18");
        returndata; }}Copy the code
Eureka: client: serviceUrl: #/ / 127.0.0.1:8081 / eureka
server:
  port: 8088Spring: Application: name: service-provider spring: application: name: service-provider spring: application: name: service-provider spring: application: name: service-providerCopy the code

After the modification is complete, we start the new project, and when it is complete, we find two instances of this piece of information in the registry.So let’s visit two instances of service-provider and see what happens. Port 8082, name is liziye; Port 8088, name is Yangyawang at this time may be a lot of friends to curious, then we visit the address of the consumer will be a situation? Here’s the answer… We can see the beginning of the visitThe value of the name of http://127.0.0.1:8083/request?id=911, a yangyawang, when we refresh after a name value becomes liziye, this also means that the two service providers in alternate work, so as to achieve a balanced load.

Here is a diagram of the Eureka architecture for you. After reading the above explanation, it will be better to look at this diagram

Finally attach himself on video address: www.ixigua.com/69650945555… (brother a little ugly, please forgive me ๐Ÿ˜)

conclusion

Spring Cloud is a boon for small and medium-sized Internet companies that often do not have the resources or financial resources to develop their own distributed system infrastructure. Using Spring Cloud’s one-stop solution can significantly reduce development costs while taking their business in stride. With the popularity of microservices architecture and Docker container concepts in recent years, Spring Cloud will also have a neutral place in the future of software development style that is gradually “Cloud”.

The above are some of my experiences in learning Eureka. I will share them with you after sorting them out. I will continue to share other Spring Cloud service applications with you from time to time.

My experience is limited, some places may not be particularly in place, if you think of any questions when reading, welcome to leave a message in the comments section, we will discuss one by one ๐Ÿ™‡

Please take a thumbs up and a follow (โœฟโ—กโ€ฟโ—ก) for this article ~ a crab (โ—’โ—ก’โ—)

If there are mistakes in the article, welcome to comment correction; If you have a better, more unique understanding, you are welcome to leave your valuable ideas in the comments area.

Love what you love, do what you do, listen to your heart and ask nothing