Detailed use of SpringCloudEureka (code implementation)

1. What is Spring Cloud Eureka?

Spring Cloud Eureka is part of the Spring Cloud Netflix microservice suite. It is encapsulated twice based on Netflix Eureka and is mainly responsible for implementing the service governance function in the microservice architecture.

Spring Cloud Eureka is a REST-based service and provides Java-based client components, which can easily register services in Spring Cloud Eureka for unified management.

2. What is the application principle of Spring Cloud Eureka?

insert image description here
To illustrate with examples from our lives :

First of all, the 12306 website is like a registration center, and customers (service consumption) are like the calling client. When they need to take a train, they will log in to the 12306 website to check the remaining tickets. If they have tickets, they can buy them, and then get the number of trains. , time, etc., and finally depart.

The same is true for the program. When you need to call a service, you will first go to Eureka to pull the service list to see if the service you are calling is in it. If it is, you will get the service address, port and other information, and then call it.

The advantage of the registration center is that you don't need to know how many providers there are, you just need to pay attention to the registration center, just like customers don't need to care how many trains are running, just go to the 12306 website to see if there are tickets.
insert image description here

3. About the Eureka version and SpringBoot version in SpringCloud.

Note : The version used here should be the same, the version of Eureka on the left is the version of springboot on the right! ! !
insert image description here

4. Code implementation

Project structure : maven parent project + 3 spring boot submodule projects
insert image description here

(1) Use Eureka to write a registry service:

Step 1: Create an empty Springboot project (without importing any default dependencies) and name iteureka-server .
Step 2: Import dependencies.

<!-- springboot 版本2.0.6.RELEASE -->
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
 <!-- eureka注册中心服务 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
          
 <!-- Spring Cloud Eureka 版本 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Step 3: Configure application.properties.

spring.application.name=eureka-server
server.port=8761
# 由于该应用为注册中心, 所以设置为false, 代表不向注册中心注册自己,(生产者配置为true)
eureka.client.register-with-eureka=false
# 由于注册中心的职责就是维护服务实例, 它并不需要去检索服务, 所以也设置为 false(消费者配置为true)
eureka.client.fetch-registry=false

Step 4: Start the class to add @EnableEurekaServerannotations .

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

Step 5: Start the registration service.
Use a browser to access: http://localhost:8761The port number here is configured in the configuration file in the third step.
insert image description here
The above picture appears, indicating that the registration center configuration is successful!

(2) Write a producer service using Eureka:

Step 1: Create an empty Springboot project and name iteureka-client-user-service .
Step 2: Import dependencies.

<!-- springboot 版本2.0.6.RELEASE -->
 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <!-- springboot web依赖 -->
     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
         <!-- eureka客户端 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
<!-- Spring Cloud Eureka 版本 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Step 3: Configure application.properties.

spring.application.name= eureka-client-user-service
server.port=8085
#eureka.client.serviceUrl.defaultZone 的地址就是我们之前启动的 Eureka 服务的地址,
# 在启动的时候需要将自身的信息注册到 Eureka 中去。
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
# 采用IP注册
eureka.instance.preferIpAddress=true
# 定义实例ID格式
eureka.instance.instance-id=${
    
    spring.application.name}:${
    
    spring.cloud.client.ip-address}:${
    
    server.port}

Step 4: Start the class to add @EnableEurekaServerannotations.

package com.hdit.eurekaclientuserservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class EurekaClientUserServiceApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(EurekaClientUserServiceApplication.class, args);
    }
}

Step 5: Write Controller tests.

package com.hdit.eurekaclientuserservice.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    
    
    @GetMapping("/user/hello")
    public String hello() {
    
    
        return "hello,我是生产服务!!!!";
    }
}

Step 6: Start the test class, use the browser to access the producer service, testhttp://localhost:8085/user/hello !

The results are as follows:
insert image description here
At this time, we visit the Web management page that comes with Eureka, which is convenient for us to query the instance information registered above, and we can see one more client.
insert image description here

The producer service has been written successfully so far!

(3) Write a consumer service using Eureka:

Step 1: Create an empty Springboot project and name iteureka-client-article-service .
Step 2: Import dependencies.

<!-- springboot 版本2.0.6.RELEASE -->
 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <!-- springboot web依赖 -->
     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
         <!-- eureka客户端 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
<!-- Spring Cloud Eureka 版本 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Step 3: Configure application.properties.

spring.application.name=eureka-client-article-service
server.port=8086

Step 4: Create a configuration class to instantiate onerestTemplate .

package com.hdit.eurekaclientarticleservice.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class BeanConfiguration {
    
    
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
    
    
        return  new RestTemplate();
    }
}

Step 5: Write Controller tests.

package com.hdit.eurekaclientarticleservice.controller;

import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
public class ArticleController {
    
    
    //注入配置的restTemplate
    @Autowired
    private RestTemplate restTemplate;

    //服务消费者
    @GetMapping("/article/callHello")
    public String callHello() {
    
    
        // 1)直接调用接口
        return restTemplate.getForObject("http://localhost:8085/user/hello", String.class);
    }

    //服务消费者
    @GetMapping("/article/callHello2")
    public String callHello2() {
    
    
        // 2)通过 Eureka 来消费接口,restTemplate配置类前面需要添加 @LoadBalanced
        return restTemplate.getForObject("http://eureka-client-user-service/user/hello", String.class);
    }
}

Step 6: Start the test class, use the browser to access the consumer service, test http://localhost:8086/article/callHello2!

The result is as follows: The
insert image description here
consumer service has been written successfully!

Looking at the Eureka service registry again, you will find two more clients, one service consumer and one service producer!
insert image description here

Guess you like

Origin blog.csdn.net/weixin_43605266/article/details/116018252