zoukankan      html  css  js  c++  java
  • SpringCloud之Eureka注册中心原理及其搭建

    一、Eureka简介

    Eureka是Netflix开发的服务发现框架,本身是一个基于REST的服务,主要用于定位运行在AWS域中的中间层服务,以达到负载均衡和中间层服务故障转移的目的。SpringCloud将它集成在其子项目spring-cloud-netflix中,以实现SpringCloud的服务发现功能。

    1、Eureka组件

    Eureka包含两个组件:Eureka Server和Eureka Client。

    1.1 Eureka Server

    Eureka Server提供服务注册服务,各个节点启动后,会在Eureka Server中进行注册,这样Eureka Server中的服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观的看到。
    Eureka Server本身也是一个服务,默认情况下会自动注册到Eureka注册中心。
    如果搭建单机版的Eureka Server注册中心,则需要配置取消Eureka Server的自动注册逻辑。毕竟当前服务注册到当前服务代表的注册中心中是一个说不通的逻辑。
    Eureka Server通过Register、Get、Renew等接口提供服务的注册、发现和心跳检测等服务。

    2.1 Eureka Client

    Eureka Client是一个java客户端,用于简化与Eureka Server的交互,客户端同时也具备一个内置的、使用轮询(round-robin)负载算法的负载均衡器。在应用启动后,将会向Eureka Server发送心跳,默认周期为30秒,如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,Eureka Server将会从服务注册表中把这个服务节点移除(默认90秒)
    Eureka Client分为两个角色,分别是:Application Service(Service Provider)和Application Client(Service Consumer)

    2.1.1 Application Service

    服务提供方,是注册到Eureka Server中的服务。

    2.1.2 Application Client

    服务消费方,通过Eureka Server发现服务,并消费。

    在这里,Application Service和Application Client不是绝对上的定义,因为Provider在提供服务的同时,也可以消费其他Provider提供的服务;Consumer在消费服务的同时,也可以提供对外服务。

    2、Eureka Server架构原理简介

     

    Register(服务注册):把自己的IP和端口注册给Eureka。
    Renew(服务续约):发送心跳包,每30秒发送一次。告诉Eureka自己还活着。
    Cancel(服务下线):当provider关闭时会向Eureka发送消息,把自己从服务列表中删除。防止consumer调用到不存在的服务。
    Get Registry(获取服务注册列表):获取其他服务列表。
    Replicate(集群中数据同步):eureka集群中的数据复制与同步。
    Make Remote Call(远程调用):完成服务的远程调用。

    服务启动后向Eureka注册,Eureka Server会将注册信息向其他Eureka Server进行同步,当服务消费者要调用服务提供者,则向服务注册中心获取服务提供者地址(即:服务应用名,spring.application.name参数配置),然后会将服务提供者地址缓存在本地,下次再调用时,则直接从本地缓存中取,完成一次调用。

    当服务注册中心Eureka Server检测到服务提供者因为宕机、网络原因不可用时,则在服务注册中心将服务置为DOWN状态,并把当前服务提供者状态向订阅者发布,订阅过的服务消费者更新本地缓存。

    服务提供者在启动后,周期性(默认30秒)向Eureka Server发送心跳,以证明当前服务是可用状态。Eureka Server在一定的时间(默认90秒)未收到客户端的心跳,则认为服务宕机,注销该实例。

    二、Eureka实例

    eclipse

     首先新建一个maven project demo-parent

    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">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.springcloud</groupId>
      <artifactId>demo-parent</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>pom</packaging>
      
      <name>demo-parent</name>
        <description>Demo project for Spring Boot</description>
     
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.3.RELEASE</version>
            <relativePath/>
        </parent>
     
       
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
            <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
        </properties>
     
        <dependencies>
            <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>
     
    	<!-- <dependencyManagement>
          <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.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>
     
     
        <modules>
        	<module>eureka-server</module>
        	<module>eureka-client</module>
        </modules>
    </project>
    

     maven update project下,让demo-parent下jar包

    搭建Eureka服务注册中心

    接着基于demo-parent创建maven module eureka-server,创建maven的时候选择jar   

     

    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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<parent>
    		<groupId>com.springcloud</groupId>
    		<artifactId>demo-parent</artifactId>
    		<version>0.0.1-SNAPSHOT</version>
    		<packaging>jar</packaging>
    	</parent>
    	<artifactId>eureka-server</artifactId>
    
    	<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-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>
    </project>
    

    application.yml

    server:
      port: 8761      #声明端口号
    eureka:
      client:
        register-with-eureka: false    #默认是true,将自己注册到eureka上
        fetch-registry: false    #是否从eureka上获取信息,由于本案例是单机,无需从别的eureka上获取注册信息
        service-url:
          defaultZone: http://localhost:8761/eureka    #设置与eureka交互的地址,查询服务和注册服务都需要依赖这个地址,默认是:http://localhost:8761/eureka
    

    EurekaServerApplication.java

    package com.zk.eurekaserver;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
    
    @EnableEurekaServer
    @SpringBootApplication
    public class EurekaServerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(EurekaServerApplication.class, args);
        }
    }

    使用Eureka编写服务提供者

    接着基于demo-parent创建maven module eureka-client,创建maven的时候选择jar

    pom.xml

    <?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.xuan</groupId>
    	<artifactId>eureka-client</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<name>eureka-client</name>
    	<description>Demo project for Spring Boot</description>
    
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>2.0.3.RELEASE</version>
    		<relativePath /> <!-- lookup parent from repository -->
    	</parent>
    
    	<properties>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    		<java.version>1.8</java.version>
    		<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.cloud</groupId>
    			<artifactId>spring-cloud-starter-netflix-eureka-client</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>
    			<dependency>
    				<groupId>org.springframework.cloud</groupId>
    				<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    			</dependency>
    		</dependencies>
    	</dependencyManagement>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    		</plugins>
    	</build>
    </project>
    

    EurekaClientApplication.java

    package com.xuan.eurekaclient;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    
    @EnableDiscoveryClient
    @SpringBootApplication
    public class EurekaClientApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(EurekaClientApplication.class, args);
        }
    }
    

    ProductController.java

    package com.xuan.eurekaclient;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class ProductController {
    	@GetMapping("/user/hello")
        public String hello() {
            return "hello";
        }
    }
    

    application.yml

    spring:
      application:
        name: product-server
    server:
      port: 7002
    eureka:
      client:
        service-url:
        #defaultZone 这个是不会提示的,此处需要自己写
        #实际上属性应该是service-url,这个属性是个map(key-value)格式;当key是defaultZone的时候才能被解析;所以这里没有提示,
        #但是自己还需要写一个defaultZone;
          defaultZone: http://localhost:8761/eureka/
    

    然后先启动服务器的Application,再启动客户端的application

     可以看到eureka-client的Product-Server已经注册到了eureka-server中。

    访问http://localhost:7002/user/hello

    返回字符串hello。

    使用Eureka编写服务消费者

    本节主要讲解如何使用 Eureka 编写服务消费者。

    1)直接调用接口

    创建服务消费者,消费我们刚刚编写的 user/hello 接口,同样需要先创建一个 Maven 项目 eureka-client-article-service,然后添加依赖,依赖和服务提供者的一样。

     

    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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
     <groupId>com.xuan</groupId>
    	<artifactId>eureka-client-article-service</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<name>eureka-client-article-service</name>
    	<description>Demo project for Spring Boot</description>
    
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>2.0.3.RELEASE</version>
    		<relativePath /> <!-- lookup parent from repository -->
    	</parent>
    
    	<properties>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    		<java.version>1.8</java.version>
    		<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.cloud</groupId>
    			<artifactId>spring-cloud-starter-netflix-eureka-client</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>
    			<dependency>
    				<groupId>org.springframework.cloud</groupId>
    				<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    			</dependency>
    		</dependencies>
    	</dependencyManagement>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    		</plugins>
    	</build>
    
    
    </project>

    ArticleController .java

    package com.zk.springcloudarticleservice;
    
    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 {
        @Autowired
        private RestTemplate restTemplate;
        @GetMapping("/article/callHello")
        public String callHello() {
            return restTemplate.getForObject("http://localhost:8081/user/hello", String.class);
        }
    }
    

    BeanConfiguration.java

    package com.zk.springcloudarticleservice;
    
    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();
        }
    }
    

    EurekaClientApplication.java启动类

    package com.zk.springcloudarticleservice;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    
    @EnableDiscoveryClient
    @SpringBootApplication
    public class EurekaClientApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(EurekaClientApplication.class, args);
        }
    }
    

     启动访问http://localhost:8082/article/callHello,结果如下:

    Eureka注册中心开启密码认证

    在原有的Eureka server中添加如下依赖:

    <dependency>
    	<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    添加WebSecurityConfig类:

    package com.zk.eurekaserver;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // 关闭csrf
            http.csrf().disable();
            // 支持httpBasic
            http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
        }
    }
    

     配置文件如下:

    server:
      port: 8761      #声明端口号
    eureka:
      client:
        register-with-eureka: false    #默认是true,将自己注册到eureka上
        fetch-registry: false    #是否从eureka上获取信息,由于本案例是单机,无需从别的eureka上获取注册信息
        service-url:
          defaultZone: http://localhost:8761/eureka    #设置与eureka交互的地址,查询服务和注册服务都需要依赖这个地址,默认是:http://localhost:8761/eureka
    spring:  
      security:
        basic: 
          enable: true
        user: 
          name: zk
          password: zk19950218
        
    

    访问localhost:8761/login

    输入用户名密码后登录成功。

    Ideal

    一、构建服务注册中心

    2、高可用注册中心

    新搭建一个与eureka-server-one一样的项目eureka-server-two

     修改eureka-server-one项目配置文件,让其注册中心指向eureka-server-two项目

      application.yml

    server:
      port: 1112
    eureka:
      instance:
        hostname: eureka-server2
      client:
        register-with-eureka: true
        fetch-registry: true
        service-url:
          defaultZone: http://eureka-server1:1111/eureka/
          #defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
    
    EurekaServerTwoApplication.java
    package com.example.eurekaservertwo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
    
    @SpringBootApplication
    @EnableEurekaServer
    public class EurekaServerTwoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(EurekaServerTwoApplication.class, args);
        }
    
    }
    

     访问可以localhost:1111

      访问localhost:1112

     由上图可见,访问eureka-server-two,发现已经有了eureka-server2的节点,同样的,访问eureka-server-one,也会存在eureka-server2节点。

     对于单节点的配置,我们设置eureka.client.register-with-eureka和eureka.client.fetch-registry均为false,为了高可用,可以将其设置为true,以达到注册中心相互向对方注册自己的服务,形成一组互相注册的注册中心,以实现服务清单的互相同步。

    二、服务注册与服务发现

    1、单节点注册中心服务注册

    (1)新建springcloud项目,然后添加对eureka-client的依赖

     

    项目结构如下:

    pom.xml

    <?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.5.0</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.zk</groupId>
        <artifactId>springcloudeurekaclient</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>springcloudeurekaclient</name>
        <description>Demo project for Spring Boot</description>
        <properties>
            <java.version>1.8</java.version>
            <spring-cloud.version>2020.0.3</spring-cloud.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</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>
    
    </project>
    

    EurekaClientApplication.java

    package com.example.eurekaclient;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    
    @SpringBootApplication
    @EnableEurekaClient
    public class SpringcloudeurekaclientApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringcloudeurekaclientApplication.class, args);
        }
    
    }

     HelloApi.java

    package com.example.eurekaclient;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/v1")
    @Slf4j
    public class HelloApi {
    
        @GetMapping("/hello")
        public String hello(){
            return "hello......";
        }
    }
    

     application.yml

    spring:
      application:
        name: eureka-client
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:1111/eureka/
      instance:
        hostname: lcl-pc1
    
    server:
      port: 8081
    

     运行起来后可以看到

     访问locahost:8081/v1/hello

    2、高可用注册中心服务注册

    (1)只需要调整配置文件中注册中心地址和eureka.instance.hostname即可,多个注册中心使用逗号分隔,更改eureka-client中的application.yml内容如下:

    application.yml

    spring:
      application:
        name: eureka-client
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:1111/eureka/,http://localhost:1112/eureka/
      instance:
        hostname: lcl-pc1
    
    server:
      port: 8081
    

     启动eureka-client项目,并重新访问注册中心

     3、服务发现与服务消费

    (1)新建一个项目,用于消费该服务,需要依赖eureka-client和ribbon,整体pom文件如下:

    <?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.5.0</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.example</groupId>
        <artifactId>eureka-client_02</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>eureka-client_02</name>
        <description>Demo project for Spring Boot</description>
        <properties>
            <java.version>1.8</java.version>
            <spring-cloud.version>2020.0.3</spring-cloud.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </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>
    
    </project>
    

    (3)配置注册中心地址、项目端口号、项目名称等内容

    server:
      port: 5551
    spring:
      application:
        name: ribbon-concumer
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:1111/eureka/,http://localhost:1112/eureka/
    

     (4)项目主函数添加@EnableDiscoveryClient,同时在主函数中创建RestTemplate实例,并使用@LoadBalanced开启客户端负载均衡

    项目结构如下:

      EurekaClient02Application.java

    package com.example.eurekaclient_02;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.context.annotation.Bean;
    import org.springframework.web.client.RestTemplate;
    
    @EnableDiscoveryClient
    @SpringBootApplication
    public class EurekaClient02Application {
        @Bean
        @LoadBalanced
        RestTemplate restTemplate(){
            return new RestTemplate();
        }
    
        public static void main(String[] args) {
            SpringApplication.run(EurekaClient02Application.class, args);
        }
    
    }
    

     HelloApi.java

    package com.example.eurekaclient_02;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    @RestController
    @RequestMapping("/v1")
    public class HelloApi {
    
        @Autowired
        RestTemplate restTemplate;
    
        @GetMapping("/helloConsumer")
        public String getStr(){
            return restTemplate.getForEntity("http://eureka-client/v1/hello",String.class).getBody();
        }
    }
    

     getForEntity中的参数是eureka-client中的application.yml中的参数

    spring:
      application:
        name: eureka-client
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:1111/eureka/,http://localhost:1112/eureka/
      instance:
        hostname: localhost
    
    server:
      port: 8081

     application.yml

    server:
      port: 5551
    spring:
      application:
        name: ribbon-concumer
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:1111/eureka/,http://localhost:1112/eureka/

    可以发现新增加的项目也注册到注册中心上了

     

  • 相关阅读:
    【解题报告】洛谷P3959 宝藏
    【游记】CSP-S2021 退役记
    【全程NOIP计划】初赛
    【解题报告】luoguP2158 仪仗队
    mysql的索引
    Set集合的所有方法
    字符串数组String[]转换成Long类型数组Long[]
    查询记录时排序问题updateTime和createTime
    VUE中== 与 ===的区别以及!=与!==的区别
    Django 模型(ORM)
  • 原文地址:https://www.cnblogs.com/longlyseul/p/14305550.html
Copyright © 2011-2022 走看看