Spring Cloud Eureka 实践(一)

Spring Cloud Eureka是Spring Cloud Netflix微服务套件中的一部分,主要在Spring Cloud架构中提供服务注册发现的功能。那么是不是可以尝试在本地搭一个单例Eureka服务来感受一下Spring Cloud是如何将Eureka集成进去的。

网上有很多参考资料可以轻松搜到,不过没有找到一个能从头参考到尾并且没有问题的教程。本篇学习记录因此参考了多位大佬的学习成果,希望能够后面仍有学习需要的朋友提供帮助。

首先,jdk的版本建议不要太高否则可能会遇到很多不兼容的问题,这里选择了1.8。同时Spring Cloud和Spring Boot的版本对应关系,一定也要注意,否则一样会出现版本不匹配导致的不兼容问题。

具体的版本对应关系,可以在官网进行查看,https://spring.io/projects/spring-cloud,具体内容如下图所示:

接下来上目录结构,spring-cloud-test为父工程,具体提供Eureka服务的spring-cloud-eureka-server以Module的形式添加到父工程中,如下图所示:

父工程的pom文件如下所示,这里cloud的Greenwich.RELEASE以及boot的2.1.18.RELEASE就是经过确认后可以匹配的版本:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>Greenwich.RELEASE</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.1.18.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-commons</artifactId>
  </dependency>
</dependencies>

提供Eureka服务的子工程pom如下所示:

<artifactId>spring-cloud-eureka-server</artifactId>
<dependencies>  
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  </dependency>
  <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
  </dependency>
</dependencies>

这里需要注意,如果你的项目在后续的启动过程中,遇到了如下方截图中所示的报错,那么只需要在pom中手动添加gson的依赖即可:

完成pom的依赖添加后,开始创建启动类,需要注意的是启动类不能直接位于src/main/java目录下,否则启动时一样会报错:

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

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

application.yml

server:  # 服务端口
  port: 9090
spring:
  application:  # 应用名字,eureka 会根据它作为服务id
    name: spring-cloud-eureka-server
eureka:
  instance:
    hostname: localhost
  client:
    service-url:   #  eureka server 的地址, 咱们单实例模式就写自己好了
      defaultZone:  http://localhost:9090/eureka
    register-with-eureka: false  # 不向eureka server 注册自己
    fetch-registry: false  # 不向eureka server 获取服务列表

接下来启动应用,并在浏览器中进行验证服务是否启动:

参考资料:

https://blog.csdn.net/yuanshangshenghuo/article/details/106962926

https://blog.csdn.net/jingyu333/article/details/89429679

https://blog.csdn.net/weixin_41020185/article/details/107534179

原文地址:https://www.cnblogs.com/xuzichao/p/15218706.html