Spring Cloud 入门教程 - Eureka服务注册与发现
admin
2023-03-11 23:02:50
0

简介

在微服务中,服务注册与发现对管理各个微服务子系统起着关键作用。随着系统水平扩展的越来越多,系统拆分为微服务的数量也会相应增加,那么管理和获取这些微服务的URL就会变得十分棘手,如果我们每新加一个微服务,就要在其它用到此微服务的地方手动加上它的URL地址或者其他通信协议的地址,这样会经常出错,而且工作量巨大,一旦某个微服务的地址发生了变化,就要手动修改所有引用它的微服务的配置文件。所以spring-cloud eureka server就是为了解决这样的问题而出现,经过简单的配置,即可自动注册和发现微服务。

基础环境

  • JDK 1.8
  • Maven 3.3.9
  • IntelliJ 2018.1
  • Git

项目源码

Gitee码云

搭建Eureka Server

上篇博客我们介绍了如何搭建spring-cloud的配置中心,还有一个测试的web client去访问它,这次我们在之前的基础上搭建一个eureka server,并且读取配置中心的配置,然后把web client作为Discovery Client注册到eureka服务。首先在IntelliJ下新建一个Maven项目:

  • groupId: cn.zxuqian
  • artifactId: registry

然后在pom.xml中添加如下代码:



    4.0.0

    cn.zxuqian
    registry
    1.0-SNAPSHOT
    jar

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.1.RELEASE
        
    

    
        UTF-8
        1.8
    

    
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-server
        
        
            org.springframework.cloud
            spring-cloud-starter-config
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                Finchley.M9
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

    
        
            spring-milestones
            Spring Milestones
            https://repo.spring.io/libs-milestone
            
                false
            
        
    

这里用到了spring-cloud-starter-netflix-eureka-server这个eureka-server核心依赖,还有访问配置中心服务的客户端组件spring-cloud-starter-config
然后在src/main/resources下创建bootstrap.yml文件,添加如下配置:

spring:
  application:
    name: eureka-server
  cloud:
    config:
      uri: http://localhost:8888

此文件配置了用以读取配置文件的应用名,即spring.application.name,它的名字对应于服务中心的文件名。另外Eureka的自动注册和发现也是基于这个参数的。然后配置了配置服务中心的uri。
新建一个Java类,cn.zxuqian.Application,使用如下代码:

package cn.zxuqian;

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

@EnableEurekaServer
@SpringBootApplication
public class Application {

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

这里只用@EnableEurekaServer一条注解即把该应用配置为Eureka Server。然后在配置中心的git仓库中创建eureka-server.yml文件,添加如下配置:

server:
  port: 8761

eureka: 
 client: 
  register-with-eureka: false
  fetch-registry: false

此文件配置了eureka-server的端口,以及关闭eureka自我注册和发现,因为如果不关闭的话,eureka在启动过程中就会去尝试注册自己,然而发现服务并没有启动就会报错。到此,eureka server就配置完了。

更新Web Client

现在我们要更新web client,使之可以被eureka自动注册和发现。首页在pom.xml中添加eureka client的依赖:


    org.springframework.cloud
    spring-cloud-starter-netflix-eureka-client

然后在Application类中加上@EnableDiscoveryClient注解:

@EnableDiscoveryClient
@SpringBootApplication
public class Application {

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

最后我们创建一个类用以测试服务是不是已成功注册和发现。新建一个Java类cn.zxuqian.controllers.ServiceInstanceController,添加如下代码:

package cn.zxuqian.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ServiceInstanceController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/service-instances/{applicationName}")
    public List serviceInstancesByApplicationName(
            @PathVariable String applicationName) {
        return this.discoveryClient.getInstances(applicationName);
    }

}

这是一个普通的RestController, 定义了一个DiscoveryClient类型的变量并添加了@Autowire注解。此注解是Spring框架提供的依赖注入功能,在Spring的context下,它会自动寻找DiscoveryClient的实现类,此处是eureka client。关于Spring的一些特性和原理,将在以后的博文中讲到。
此类还定义了serviceInstancesByApplicationName方法,用以处理/service-instances/{applicationName}请求。这里的{applicationName}匹配url路径中/service-instances/以后的部分,然后用@PathVariable注解赋值给方法的applicationName参数。例如访问http://localhost:8080/service-instances/web-client,那么applicationName的值就是web-client。方法的作用是从discoveryClient中根据spring.application.name的值来取出对应的实例信息,返回的是一个list,会自动转换为json数组的形式返回给浏览器。

测试

因为eureka server和web client都需要从配置服务中读取配置,所以先启动config-server,然后再启动eureka-server,最后启动web-client,在启动成功后可能需要稍等十几秒让eureka-server发现和注册web-client。完成之后访问http://localhost:8080/service-instances/web-client,会得到如下结果:

[{"host":"xuqians-imac","port":8080,"instanceInfo":{"instanceId":"xuqians-imac:web-client","app":"WEB-CLIENT","appGroupName":null,"ipAddr":"192.168.72.31","sid":"na","homePageUrl":"http://xuqians-imac:8080/","statusPageUrl":"http://xuqians-imac:8080/actuator/info","healthCheckUrl":"http://xuqians-imac:8080/actuator/health","secureHealthCheckUrl":null,"vipAddress":"web-client","secureVipAddress":"web-client","countryId":1,"dataCenterInfo":{"@class":"com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo","name":"MyOwn"},"hostName":"xuqians-imac","status":"UP","leaseInfo":{"renewalIntervalInSecs":30,"durationInSecs":90,"registrationTimestamp":1525319124967,"lastRenewalTimestamp":1525319124967,"evictionTimestamp":0,"serviceUpTimestamp":1525319124363},"isCoordinatingDiscoveryServer":false,"metadata":{"management.port":"8080"},"lastUpdatedTimestamp":1525319124967,"lastDirtyTimestamp":1525319124297,"actionType":"ADDED","asgName":null,"overriddenStatus":"UNKNOWN"},"metadata":{"management.port":"8080"},"uri":"http://xuqians-imac:8080","serviceId":"WEB-CLIENT","secure":false,"scheme":null}]

注意一下,这里并没有把配置中心服务设置为可以被eureka server注册和发现,因为这里把配置文件都放到了config-server中,它和eureka server有着鸡生蛋,蛋生鸡的问题,所以如果要让config-server被自动注册和发现,那么就需要单独配置eureka server,然后在config server中配置eureka的uri,以及设置spring.cloud.config.discovery.enabled为true。具体以后需要用的时候再详细说明。

总结

配置eureka server相当简单,只需要加一条@EnableEurekaServer注解,并在配置中关闭自我注册和发现即可。然后在客户端应用的Application类中加上@EnableDiscoveryClient注解即可。

欢迎访问我的博客

相关内容

热门资讯

【第一财经】“八闽掌上麻将.有... 有 亲,根据资深记者爆料八闽掌上麻将是可以开挂的,确实有挂(咨询软件无需...
玩家最新攻略“来来麻将.怎么装... 有 亲,根据资深记者爆料来来麻将是可以开挂的,确实有挂(咨询软件无需打开...
玩家分享攻略“圣盛晃晃麻将.是... 家人们!今天小编来为大家解答圣盛晃晃麻将透视挂怎么安装这个问题咨询软件客服徽9784099的挂在哪里...
【今日要闻】“新青鸟拼三张.究... 【今日要闻】“新青鸟拼三张.究竟有挂吗?”确实真的有挂您好,新青鸟拼三张这个游戏其实有挂的,确实是有...
玩家分享攻略“麻友圈2挪来挪去... 您好:麻友圈2挪来挪去这款游戏可以开挂,确实是有挂的,需要了解加客服微信【4282891】很多玩家在...
终于明白“新版悟空牛牛.到底有... 终于明白“新版悟空牛牛.到底有挂吗?”果然有透视挂您好,新版悟空牛牛这个游戏其实有挂的,确实是有挂的...
玩家分享攻略“微乐四川麻将.辅... 家人们!今天小编来为大家解答微乐四川麻将透视挂怎么安装这个问题咨询软件客服徽4282891的挂在哪里...
终于明白“凑局麻将.辅助器?”... 家人们!今天小编来为大家解答凑局麻将透视挂怎么安装这个问题咨询软件客服徽9784099的挂在哪里买很...
今日重大发现“天天福建十三张.... 有 亲,根据资深记者爆料天天福建十三张是可以开挂的,确实有挂(咨询软件无...
今日重大通报“聚友.怎么装挂?... 网上科普关于“聚友有没有挂”话题很是火热,小编也是针对聚友作*弊开挂的方法以及开挂对应的知识点,寻找...