SpringCloud H版 EureKa使用及集群讲解

一、SpringCloud

SpringCloud也是一个我们现在基本开发必备的框架之一了,他提供了整个微服务的解决方案,早在很早以前我就写了详细的SpringCloud的博客,但一直没写系列的教程,现在就准备讲解下SpringCloud全家桶的系列教程,我们都知道Cloud全家桶中很多组件已经停更了,比如eureka、zuul等,在我们的教程中依旧会对这些组件进行讲解,一些老项目中不乏依然使用这些组件,但是我也会讲解新的解决方案,包括alibabb cloud的生态组件。不多说了,开干吧!今天就先从古老而经典的eureka开篇。

二、EureKa

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

  • Eureka Server提供服务注册服务
    各个微服务节点通过配置启动后,会在EurekaServer中进行注册,这样EurekaServer中的服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观看到。

  • EurekaClient通过注册中心进行访问
    是一个Java客户端,用于简化Eureka Server的交互,客户端同时也具备一个内置的、使用轮询(round-robin)负载算法的负载均衡器。在应用启动后,将会向Eureka Server发送心跳(默认周期为30秒)。如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,EurekaServer将会从服务注册表中把这个服务节点移除(默认90秒)

三、开始搭建基础框架

创建父工程,并修改POM配制文件,我们使用了Cloud H版的SR9的版本,也是一个比较新的版本。

<?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>
    <groupId>com.bxc</groupId>
    <artifactId>cloud-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>cloud-parent</name>
    <packaging>pom</packaging>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
        <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
        <model.version>0.0.1-SNAPSHOT</model.version>
    </properties>


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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <!--spring cloud Hoxton.SR9-->
            <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.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.bxc.clouddemo.CloudDemoApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

创建公共模块,主要编写一些工具类,大家共同使用:
这里我主要封装了,统一接口返回对象:

public interface ResponseTemplate {
    public Integer getCode();

    public String getMessage();

    public Object getData();
}
@Builder
@Data
public class ResFailTemplate implements ResponseTemplate {
    @Builder.Default
    public Integer code =400;
    @Builder.Default
    public String message = "fail";
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public Object data;
}
Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResSuccessTemplate implements ResponseTemplate {
    @Builder.Default
    public Integer code =200;
    @Builder.Default
    public String message = "success";
    @JsonInclude(JsonInclude.Include.NON_NULL)
    public Object data;
}

在这里插入图片描述

下面就就进入正题,Eureka的搭建。

三、EureKa Server端集群搭建

现在都大数据的时代了,我们直接搭建EureKa Server端的集群模式,对于单机班,也就无非少写个地址,但是这里需要注意的是在部署EureKa Server端集群时 ip 或者 主机名相同时,无法形成副本。所以将其中一台迁移到了另外的服务器上了。这里我们直接修改本机的host文件

127.0.0.1 eureka1
127.0.0.1 eureka2

下面就开始搭建集群了,首先创建两个SpringBoot项目module,作为eureka1和eureka2,当然也可以创建一个项目通过修改端口启动多个实例。这里为了便于大家的理解,直接选择创建了两个项目的方式,并且两者相互注册,互为集群。
在这里插入图片描述

首先在两个module都引入依赖:

<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-server</artifactId>
</dependency>

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

eureka1 的配制文件:

server:
  port: 8010
spring:
  application:
    name: eureka

eureka:
  instance:
    hostname: eureka1 #eureka服务端的实例名称
  client:
    register-with-eureka: false     #false表示不向注册中心注册自己。
    fetch-registry: false     #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    service-url:
      #单机就是指向自己
      # defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
      #集群
      defaultZone: http://eureka1:8010/eureka/,http://eureka2:8011/eureka/

eureka2 的配制文件:

server:
  port: 8011
spring:
  application:
    name: eureka

eureka:
  instance:
    hostname: eureka2 #eureka服务端的实例名称
  client:
    register-with-eureka: false     #false表示不向注册中心注册自己。
    fetch-registry: false     #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    service-url:
      #单机就是指向自己
      #defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
      #集群
      defaultZone: http://eureka1:8010/eureka/,http://eureka2:8011/eureka/

修改两个项目的启动类,添加 @EnableEurekaServer ,开启eureka服务

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

启动两个项目后,在浏览器输入http://eureka1:8010http://eureka1:8011 就可以看到eureka提供的可视化页面,并且可以看到副本集中出现了eureka2,说明我们的eureka集群已经搭建成功。
在这里插入图片描述

四、服务提供者搭建

现在有了注册中心了,我们就搭建个消费者请求提供者的场景,还是同样的套路,直接搭建两个相同的提供者,以演示出负载均衡的效果。创建两个SpringCloud的module:

在pom文件中引入依赖:

<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-actuator</artifactId>
</dependency>

<dependency>
    <groupId>com.bxc</groupId>
    <artifactId>common</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

common就是上面创建的公共的module。

配制文件修改:

server:
  port: 8091
spring:
  application:
    name: provider
eureka:
  client:
    #表示是否将自己注册进EurekaServer默认为true。
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetchRegistry: true
    service-url:
      #单机版
#      defaultZone: http://eureka1:8010/eureka
      # 集群版
      defaultZone: http://eureka1:8010/eureka,http://eureka2:8011/eureka
  instance:
#    instance-id: provider
#    #访问路径可以显示IP地址
    prefer-ip-address: true
    #Eureka客户端向服务端发送心跳的时间间隔,单位为秒(默认是30秒)
    lease-renewal-interval-in-seconds: 1
    #Eureka服务端在收到最后一次心跳后等待时间上限,单位为秒(默认是90秒),超时将剔除服务
    lease-expiration-duration-in-seconds: 2

另一个也是相同的配制,将端口修改味8092,以表示集群形式。

修改主启动类,添加 @EnableEurekaClient ,声明为eureka客户端:

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

下面编写我们具体提供的入口,也就是写一个controller:

@RestController
public class ProviderController {

    @Value("${server.port}")
    private String port;

    @GetMapping("/getData")
    public ResponseTemplate providerData() {

        return ResSuccessTemplate.builder().data("come from : " + port).build();
    }

    @GetMapping("/getTimeData")
    public ResponseTemplate getTimeData() throws InterruptedException {
        TimeUnit.SECONDS.sleep(5);
        return ResSuccessTemplate.builder().data("come from : " + port).build();
    }

}

启动两个提供者,然后再刷新下,eureka的页面,就会看到已经有两个服务注册进来:

在这里插入图片描述

五、服务消费者搭建

服务消费者和服务提供者,相对于eureka都是客户端,所以配制都是相同的,但在客户端我们需要调用工具,这里我们先使用RestTemplate来做请求,但 RestTemplate 只是一个网络请求框架,并没有负载均衡,并没有负载均衡,那怎么进行负载呢,那就要引入ribbon 了,这里我们就体验ribbon+RestTemplate 的负载效果,包括后面我们也会详细对ribbon 讲解以及feign 客户端。对于ribbon的引入其实在我们引入eureka的依赖时,就已经引入了ribbon的依赖:
在这里插入图片描述
ribbon已经做了和 RestTemplate 的集成优化,我们只需在创建 RestTemplate 对象时使用@LoadBalanced 即可使用ribbon的负载功能。

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

下面我们在客户端写个例子测试一下:

@RestController
@RequestMapping("/rest/consumer")
public class ConsumerController {
    @Autowired
    RestTemplate restTemplate;

    @GetMapping("/getData")
    public ResponseTemplate getData() {
        ResponseTemplate responseTemplate = restTemplate.getForObject("http://PROVIDER/getData", ResSuccessTemplate.class);
        return responseTemplate;
    }

    @GetMapping("/getTimeData")
    public ResponseTemplate getTimeData() {
        ResponseTemplate responseTemplate = restTemplate.getForObject("http://PROVIDER/getTimeData", ResSuccessTemplate.class);
        return responseTemplate;
    }
}

启动消费者服务:
在这里插入图片描述消费者提供者都已启动:下面调用接口 http://localhost:8080/rest/consumer/getData

在这里插入图片描述

在这里插入图片描述
已经达到负载均衡的效果。

六、Eureka的自我保护机制

Eureka所属的模式为AP模式,以可用为主要点,而服务端和客户端有以心跳来判断是否存活,因此假如由于网络震荡,导致新挑没有发出,从而将该服务做为无效服务剔除,其实该服务正常,为防止这种情况,eureka引入了自我保护机制,并不会第一时间将服务剔除,而是保留一段时间。因此在有些情况下,我们可能不需要这样的设定,我们可以选择性的关闭该功能。

eureka server端的配制文件修改:

server:
  port: 8011
spring:
  application:
    name: eureka

eureka:
  instance:
    hostname: eureka2 #eureka服务端的实例名称
  client:
    register-with-eureka: false     #false表示不向注册中心注册自己。
    fetch-registry: false     #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
    service-url:
      #单机就是指向自己
      #defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
      #集群
      defaultZone: http://eureka1:8010/eureka/,http://eureka2:8011/eureka/
  server:
    #关闭自我保护机制,保证不可用服务被及时踢除
    enable-self-preservation: false
    eviction-interval-timer-in-ms: 2000

client端的配制修改:

server:
  port: 8091
spring:
  application:
    name: provider
eureka:
  client:
    #表示是否将自己注册进EurekaServer默认为true。
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetchRegistry: true
    service-url:
      #单机版
#      defaultZone: http://eureka1:8010/eureka
      # 集群版
      defaultZone: http://eureka1:8010/eureka,http://eureka2:8011/eureka
  instance:
#    instance-id: provider
#    #访问路径可以显示IP地址
    prefer-ip-address: true
    #Eureka客户端向服务端发送心跳的时间间隔,单位为秒(默认是30秒)
    lease-renewal-interval-in-seconds: 1
    #Eureka服务端在收到最后一次心跳后等待时间上限,单位为秒(默认是90秒),超时将剔除服务
    lease-expiration-duration-in-seconds: 2

在这里插入图片描述
喜欢的小伙伴可以关注我的个人微信公众号,获取更多学习资料!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小毕超

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值