SpringCloud进击 | 一浅出:服务注册与发现(Eureka)【Finchley版本】

1.前言

Spring Cloud 已经帮我们实现了服务注册中心,我们只需要很简单的几个步骤就可以完成。关于理论知识,我想大家都已经有不同程度上的了解和认识,这里,我们最后再进行总结。本系列 Spring Cloud 介绍基于 Spring Boot 2.0.5 版本和 Spring Cloud Finchley.SR1 版本。

Finchley 版与 Spring Boot 2.0.x 兼容,不支持 Spring Boot 1.5.x. 

Spring Cloud 为避免与子项目的发布号混淆,所以没有采用版本号的方式,而是通过命名的方式。这些版本名称的命名方式采用了伦敦地铁站的名称,同时根据字母表的顺序来对应版本时间顺序,比如:最早的Release版本:Angel,第二个Release版本:Brixton,然后是Camden、Dalston、Edgware,目前最新的是Finchley版本。

 

2.准备

我们需要:

JDK 1.8或以上
Maven 3.0或以上
IntelliJ IDEA
另,Spring Cloud 是基于 Spring Boot 的,所以需要我们对 Spring Boot 有一定的了解。如果有需要,可以先去链接过一下:
SpringBoot进击 | 一浅出:Spring Boot简单快速上手书
SpringBoot进击 | 二浅出:Spring Boot配置详解

 

3.进击

Eureka 这个词来源于古希腊语,意为 “我找到了!我发现了!”,据传,阿基米德在洗澡时发现浮力原理,高兴得来不及穿上裤子,跑到街上大喊:“Eureka(我找到了)!”。

 

 

3.1.新建一个Maven工程

为了与后面的演练行成连贯性、系统性,这里我们需要先创建一个Maven主项目。主项目的 pom.xml 文件作用于版本控制、依赖管理,其它子模块都继承于该父 pom.xml。

a) File  >>  New  >>  Project  >>  Maven:Project SDK:1.8  >>  [Next] 
b) 填写Group、ArtifactId等项目信息  >>  [Next] 
c) 项目名称、路径设置  >>  [Finish] 

 

3.2. 服务注册

3.2.1 创建服务注册中心(Eureka Server)


【Spring Initializr】
3.2.1.1 项目名称右键  >>  Model  >>  选择 Spring Initializr  >>  Module SDK:1.8;choose Initializr Service URL:Default  >>  [Next] 
3.2.1.2 填写Group、Artifact等项目信息  >>  [Next] 


【Dependencies 项目依赖选择】
3.2.1.3 Dependencies:项目依赖选择,选择 Cloud Discovery,并钩上 Eureka Server; Spring Boot 版本选择,这里我们使用 2.0.5 版本  >>  [Next] 
3.2.1.4 模块名称、路径设置  >>  [Finish] 

 

如此,一个画风干净的 Spring Cloud Eureka Server (Eureka服务注册中心)就映入眼帘。

因为,它是我们这个项目的一个子模块,它继承了父pom文件(parent标签),并引入了 spring-cloud-starter-netflix-eureka-server 核心依赖,Eureka服务注册中心的 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.wei</groupId>
    <artifactId>wei-eureka-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>wei-eureka-server</name>
    <description>服务注册中心(Eureka Server)</description>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.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.SR1</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-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>
 

3.2.2 配置服务注册中心

在默认设置下,服务注册中心会将自己作为客户端来尝试注册它自己,所以我们需要禁用它的客户端注册行为(默认情况下 Erureka Server 也是一个 Eureka Client,必须要指定一个 Server)。这只需要在 application.yml (如果创建出来的是properties文件,可以直接rename成yml)配置文件中配置以下信息:

server:
  port: 8090                       # 服务注册中心端口号配置
eureka:
  instance:
    hostname: localhost            # 服务注册中心实例的主机名
  client:
    register-with-eureka: false    # 表示是否注册自身到eureka服务器,因为当前这个应用就是eureka服务器,没必要注册自身
    fetch-registry: false          # 表示是否从eureka服务器获取注册信息,同上,这里不需要
    service-url:                   # defaultZone是指定eureka服务器的地址,无论是注册还是发现服务都需要这个地址
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
  server:
    enable-self-preservation: false    # 简单粗暴把自我保护模式关闭
eureka.client.register-with-eureka:表示是否将自己注册到 Eureka Server,默认为 true
eureka.client.fetch-registry:表示是否从 Eureka Server 获取注册信息,默认为 true
eureka.client.service-url.defaultZone:是指定 Eureka Server 的地址,无论是注册还是发现服务都需要这个地址
 

3.2.3 启动服务注册中心

要启动一个服务注册中心,只需要在我们刚刚新建的 Eureka Server 模块的启动类上添加 @EnableEurekaServer 注解即可。

package com.wei;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
 
/**
 * 注解@EnableEurekaServer,开启Eureka服务注册中心功能
 */
@SpringBootApplication
@EnableEurekaServer
public class WeiEurekaServerApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(WeiEurekaServerApplication.class, args);
    }
}
然后,Run 该启动类。

如此,一个 Spring Eureka Server 服务注册中心就被我们建好了。

 

3.2.4 解读服务注册中心

Spring Eureka 服务注册中心提供了可视界面(Eureka信息面板)。

我们可以去刚刚配置的URL地址看一下:http://localhost:8090/


【Spring Eureka】
当前因为还没有服务被注册,所以没服务可以被发现。

 

各项备注一下:

System Status  

Environment    指定环境,默认为test, 实际使用过程中,可以不用更改
Data center    数据中心
Current time    当前系统时间
Uptime    已运行时长
Lease expiration enabled    是否启用租约过期, 自我保护机制关闭时,该值默认是true, 自我保护机制开启之后为false
Renews threshold    server 期望在每分钟中收到的心跳次数
Renews (last min)    上一分钟内收到的心跳次数
DS Replicas  

Instances currently registered with Eureka    当前注册到服务注册中心内的服务
No instances available    没有服务被发现
General Info  

total-avail-memory    
总共可用的内存
environment    环境名称,默认test
num-of-cpus    CPU个数
current-memory-usage    当前已经使用内存的百分比
server-uptime    服务在线时间
registered-replicas    相邻集群复制节点
unavailable-replicas    不可用的集群复制节点
available-replicas    可用的相邻集群复制节点
Instance Info  

ipAddr    实例IP地址
status    实例状态
 

Eureka信息面板的红字提醒

Spring Eureka 服务注册中心在三种情况下会出现红色加粗的字体提示:

1)自我保护机制开启时(enable-self-preservation: true):
EMERGENCY! EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY'RE NOT. RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEING EXPIRED JUST TO BE SAFE.

2)自我保护机制关闭时(enable-self-preservation: false):
RENEWALS ARE LESSER THAN THE THRESHOLD. THE SELF PRESERVATION MODE IS TURNED OFF.THIS MAY NOT PROTECT INSTANCE EXPIRY IN CASE OF NETWORK/OTHER PROBLEMS.

3)自我保护机制关闭了,但是一分钟内的续约数没有达到85%,可能发生了网络分区,会有如下提示:
THE SELF PRESERVATION MODE IS TURNED OFF.THIS MAY NOT PROTECT INSTANCE EXPIRY IN CASE OF NETWORK/OTHER PROBLEMS.

 

3.3. 服务发现

3.3.1 创建一个服务提供者(Eureka Client)

服务提供者,也就是 Service Provider,做为一个 Eureka Client,向 Eureka Server 做服务注册、续约和下线等操作,注册的主要数据包括服务名、机器IP、端口号、域名等等。

创建步骤与上面的 Eureka Server 创建过程类似,但在Dependencies选择依赖时,
a) 选择左侧的 Cloud Discovery 后,这里需要钩上 Eureka Discovery 项
b) 选择左侧的 Web 后,这里需要钩上 Web 项

创建完后的 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.wei</groupId>
    <artifactId>wei-service-provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>wei-service-provider</name>
    <description>服务提供者(Eureka Client)</description>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.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.SR1</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>
 

3.3.2 配置服务提供者

修改配置文件,如下:

server:
  port: 8010
spring:
  application:
    name: wei-service-provider    # 指定进行服务注册时该服务的名称,服务与服务之间相互调用一般都是根据这个name
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8090/eureka/    # 指定进行服务注册地址
创建服务提供者的服务接口:

package com.wei.controller.demo;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class DemoServiceController {
 
    @Value("${spring.application.name}")
    private String serviceName;
 
    @Value("${server.port}")
    private String port;
 
    @RequestMapping(value = "/demo/info")
    public String getDemoInfo(@RequestParam String name) {
        String result = "Hi," + name + ",我是服务,我被调用了,服务名为:" + serviceName + ",端口为:" + port;
        System.out.println(result);
        return result;
    }
}
 

3.3.3 启动服务提供者

要启动一个服务提供者,只需要在我们刚刚新建的 Eureka Clinet 模块的启动类上添加 @EnableEurekaClient 注解即可。

package com.wei;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
 
/**
 * 注解@EnableEurekaClient,表明自己是一个Eureka Client
 */
@SpringBootApplication
@EnableEurekaClient
public class WeiServiceProviderApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(WeiServiceProviderApplication.class, args);
    }
}
然后,Run 该启动类。

如此,一个 Spring Eureka Client 服务提供者就被我们建好了。

 

4.测试

去验证一下吧:http://localhost:8090/


【Spring Eureka & 服务提供者】
如你所想,一个服务已经注册在服务中心了,服务名为 WEI-SERVICE-PROVIDER,端口号为8010

再来看看接口:http://localhost:8010/demo/info?name=tester

浏览器打印:

Hi,tester,我是服务,我被调用了,服务名为:wei-service-provider,端口为:8010

 

到此,简单易用的 Eureka Server 服务注册中心就创建完成了。当然,还实现了一个 Eureka Client 服务提供者小样。

 

下一节,请继续关注:SpringCloud进击 | 二浅出:服务消费者(Ribbon+REST)【Finchley版本】

 

5.总结

Finchley版本的官方文档: http://cloud.spring.io/spring-cloud-static/Finchley.RELEASE/single/spring-cloud.html

官方参考文档:https://springcloud.cc/spring-cloud-config.html

源码:https://github.com/itanping/wei-springcloud/tree/master/chapter01-eureka

 
--------------------- 
作者:魏风物语 
来源:CSDN 
原文:https://blog.csdn.net/itanping/article/details/82429509 
版权声明:本文为博主原创文章,转载请附上博文链接!

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值