Spring Cloud 使用 Netflix Eureka作为服务发现和注册

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(775)   2023-03-28 11:29:14

演示项目源码下载:(访问密码:9987)
Spring-Cloud-discovery-server.zip 

了解如何创建微服务的基础上,Spring Cloud,对Netflix的Eureka注册表服务器以及如何等微服务(Eureka客户端)使用它来注册和发现服务来调用其API。
我们将使用基于 Spring Boot 的 Spring Cloud API。我们将使用 Netflix Eureka 服务器来构建服务注册服务器和 Eureka 客户端,这些客户端将自行注册并发现其他服务以调用 REST API。

概述

我们将为这个Netflix Eureka 示例创建三个微服务。
  1. Eureka 服务注册服务器——这个微服务将提供服务注册和发现服务器。
  2. 学生微服务——它将提供一些基于学生实体的功能。它将是一个基于休息的服务,最重要的是它将是一个 eureka 客户端服务,它将与 eureka 服务对话以在服务注册表中注册自己。
  3. 学校微服务 - 与学生服务类型相同 - 唯一增加的功能是它将通过服务查找机制调用学生服务。我们不会使用学生服务的绝对 URL 与该服务进行交互。
这是上面列出的三个服务之间的交互图。
组件交换图
 

技术栈和运行时

  • Java 1.8
  • Eclipse IDE
  • Spring cloud
  • Spring boot
  • Spring Rest
  • Maven

什么是 Netflix Eureka 服务器和客户端?

正如我们现在所知,围绕微服务有很多动力。从单体架构到基于微服务的架构的转变在可维护性、可扩展性、高可用性等方面为未来带来了许多好处。然而,与此同时,在进行这种迁移时也存在许多挑战。其中之一是维护单个微服务地址。这项任务可能非常复杂——取决于服务的数量及其动态性质。如果整个基础设施是分布式的并且还有一些复制,那么维护这个服务地址就会变得更加困难。
为了解决这个问题,在分布式计算中有一个称为“服务注册和发现”的概念,其中一个专用服务器负责维护所有已部署和删除的微服务的注册表。这将充当所有其他应用程序/微服务的电话簿。
将其视为一种查找服务,微服务(客户端)可以在其中注册自己并发现其他已注册的微服务。当客户端微服务向 Eureka 注册时,它会提供元数据,例如主机、端口和健康指标,从而允许其他微服务发现它。发现服务器期望来自每个微服务实例的常规心跳消息。如果实例开始始终无法发送心跳,则发现服务器将从其注册表中删除该实例。这样我们就会有一个非常稳定的微服务生态系统相互协作,而且我们不需要手动维护其他微服务的地址,如果扩容/缩容非常频繁,这几乎是不可能完成的任务,按需,我们使用虚拟主机专门在云环境中托管服务。
 

Eureka服务注册服务器

按照以下步骤创建和运行 Eureka 服务器。

创建Eureka服务器

从Spring Boot 初始值设定项门户创建一个具有两个依赖项的 Spring boot 项目,即Eureka serverActuator。给出其他maven GAV坐标并下载项目。
服务器项目生成
解压缩该项目并将其作为现有的 maven 项目导入 Eclipse。在这一步中,所有必需的依赖项都将从 maven 存储库下载。
现在SpringEurekaServerApplication在下载的项目中打开spring已经生成的类,并@EnableEurekaServer在类上添加注释。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
  
@EnableEurekaServer
@SpringBootApplication
public class SpringEurekaServerApplication {
  
    public static void main(String[] args) {
        SpringApplication.run(SpringEurekaServerApplication.class, args);
    }
}
再次构建项目。有了这个注解,这个工件就会像微服务注册中心和发现服务器一样工作。

服务器配置

创建一个application.ymlsrc\main\resources目录中调用的文件。添加这些属性 -
server:
  port: ${PORT:8761} # Indicate the default PORT where this service will be started
 
eureka:
  client:
    registerWithEureka: false   #telling the server not to register himself in the service registry
    fetchRegistry: false
  server:
    waitTimeInMsWhenSyncEmpty: 0    #wait time for subsequent sync
创建另一个bootstrap.ymlsrc\main\resources目录中调用的文件。添加这些属性 -
spring:
  application:
    name: eureka
  cloud:
    config:
      uri: ${CONFIG_SERVER_URL:http://localhost:8888}

测试Eureka服务器

将应用程序作为 Spring Boot 应用程序启动。打开浏览器并转到http://localhost:8761/,您应该会看到如下所示的 eureka 服务器主页
没有任何服务注册进来

请注意,此时此处没有注册服务,这是预期的,一旦我们启动客户端服务,该服务器将自动更新客户端服务的详细信息。
 

Eureka客户 - 学生服务

按照以下步骤创建和运行运行学生服务的 Eureka 客户端。

创建 Eureka 客户端项目

从具有四个依赖项的初始化程序门户创建一个 Spring boot 项目,即ActuatorWebRest RepositoriesEureka Discovery。给出其他maven GAV坐标并下载项目。

解压缩该项目并将其作为现有的 maven 项目导入 Eclipse。
现在@EnableEurekaClientsrc文件夹中存在的 Spring boot 应用程序类上添加注释。有了这个注解,这个工件将像一个 spring 发现客户端一样,并将在附加到这个服务的Eureka服务器中注册自己。
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  
@SpringBootApplication
@EnableEurekaClient
public class SpringEurekaClientStudentServiceApplication {
  
    public static void main(String[] args) {
        SpringApplication.run(SpringEurekaClientStudentServiceApplication.class, args);
    }
}

客户端配置

创建一个application.ymlsrc\main\resources目录中调用的文件并添加以下行。
server:
  port: 8098    #default port where the service will be started
 
eureka:         #tells about the Eureka server details and its refresh time
  instance:
    leaseRenewalIntervalInSeconds: 1
    leaseExpirationDurationInSeconds: 2
  client:
    serviceUrl:
      defaultZone: http://127.0.0.1:8761/eureka/
    healthcheck:
      enabled: true
    lease:
      duration: 5
 
spring:     
  application:
    name: student-service   #current service name to be used by the eureka server
     
management:
  security:
    enabled: false  #disable the spring security on the management endpoints like /env, /refresh etc. 
 
logging:
  level:
    com.example.howtodoinjava: DEBUG

添加 REST API

现在添加一个RestController并公开一个 rest 端点,用于获取特定学校的所有学生详细信息。在这里,我们公开/getStudentDetailsForSchool/{schoolname}端点以服务于业务目的。为简单起见,我们对学生的详细信息进行了硬编码。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
 
import com.example.howtodoinjava.springeurekaclientstudentservice.domain.Student;
 
@RestController
public class StudentServiceController {
 
    private static Map<String, List<Student>> schooDB = new HashMap<String, List<Student>>();
 
    static {
        schooDB = new HashMap<String, List<Student>>();
 
        List<Student> lst = new ArrayList<Student>();
        Student std = new Student("Sajal", "Class IV");
        lst.add(std);
        std = new Student("Lokesh", "Class V");
        lst.add(std);
 
        schooDB.put("abcschool", lst);
 
        lst = new ArrayList<Student>();
        std = new Student("Kajal", "Class III");
        lst.add(std);
        std = new Student("Sukesh", "Class VI");
        lst.add(std);
 
        schooDB.put("xyzschool", lst);
 
    }
 
    @RequestMapping(value = "/getStudentDetailsForSchool/{schoolname}", method = RequestMethod.GET)
    public List<Student> getStudents(@PathVariable String schoolname) {
        System.out.println("Getting Student details for " + schoolname);
 
        List<Student> studentList = schooDB.get(schoolname);
        if (studentList == null) {
            studentList = new ArrayList<Student>();
            Student std = new Student("Not Found", "N/A");
            studentList.add(std);
        }
        return studentList;
    }
}
Student class 是一个简单的 POJO。
public class Student 
{
    private String name;
    private String className;
     
    public Student(String name, String className) {
        super();
        this.name = name;
        this.className = className;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getClassName() {
        return className;
    }
 
    public void setClassName(String className) {
        this.className = className;
    }
}

测试Eureka客户端

将此项目作为 Spring Boot 应用程序启动。现在验证该服务是否已自动注册到 Eureka 服务器中。转到 Eureka 服务控制台并刷新页面。现在如果一切顺利,我们将在 eureka 服务控制台中看到一个关于student-service 的条目。这表明 Eureka 服务器和客户端都知道彼此。
学生服务已经注册进来

我们现在将验证/getStudentDetailsForSchool/{schoolname}端点是否已启动并正在运行。转到浏览器并转到http://localhost:8098/getStudentDetailsForSchool/abcschool,它将提供特定学校的学生详细信息abcschool学生服务响应

Eureka客户 – 学校服务

现在我们将创建学校服务,它将自己注册到Eureka服务器——它将发现和调用学生服务,而无需硬编码的 URL 路径。
按照创建学生服务的确切步骤,创建和运行运行学校服务的 Eureka 客户端。

创建 Eureka 客户端项目

从具有四个依赖项的初始化程序门户创建一个 Spring boot 项目,即ActuatorWebRest RepositoriesEureka Discovery。给出其他maven GAV坐标并下载项目。
解压缩该项目并将其作为现有的 maven 项目导入 Eclipse。
现在@EnableEurekaClientsrc文件夹中存在的 Spring boot 应用程序类上添加注释。有了这个注解,这个工件将像一个 spring 发现客户端一样,并将在附加到这个服务的Eureka服务器中注册自己。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
 
@SpringBootApplication
@EnableEurekaClient
public class SpringEurekaClientSchoolServiceApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringEurekaClientSchoolServiceApplication.class, args);
    }
}

客户端配置

创建一个application.ymlsrc\main\resources目录中调用的文件并添加以下行。除了端口号和服务名称外,这些配置与学生服务非常相似。
server:
  port: 9098    #port number
 
eureka:
  instance:
    leaseRenewalIntervalInSeconds: 1
    leaseExpirationDurationInSeconds: 2
  client:
    serviceUrl:
      defaultZone: http://127.0.0.1:8761/eureka/
    healthcheck:
      enabled: true
    lease:
      duration: 5
 
spring:
  application:
    name: school-service    #service name
 
logging:
  level:
    com.example.howtodoinjava: DEBUG

添加使用学生服务的 REST API 的 REST API

现在添加一个RestController并公开一个休息端点以获取学校详细信息。此端点将使用使用应用程序名称的服务发现样式 URL,而不是带有 host:port 的完整 URL。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
 
@RestController
public class SchoolServiceController {
    @Autowired
    RestTemplate restTemplate;
 
    @RequestMapping(value = "/getSchoolDetails/{schoolname}", method = RequestMethod.GET)
    public String getStudents(@PathVariable String schoolname) 
    {
        System.out.println("Getting School details for " + schoolname);
 
        String response = restTemplate.exchange("http://student-service/getStudentDetailsForSchool/{schoolname}",
                                HttpMethod.GET, null, new ParameterizedTypeReference<String>() {}, schoolname).getBody();
 
        System.out.println("Response Received as " + response);
 
        return "School Name -  " + schoolname + " \n Student Details " + response;
    }
 
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
这样我们就可以摆脱特定的服务配置,我们可以将服务查找责任交给Eureka服务器和这里提供的休息模板。@LoadBalanced如果多个实例正在为同一服务运行,我们也可以在此处应用负载平衡(请参阅注释)。
我们使用的 URL 是http://student-service/getStudentDetailsForSchool/{schoolname}. 显然,我们只使用服务名称student-service来代替host:port. 这将由 spring 框架、eureka 服务器和 rest 模板一起在内部处理。
 

服务发现和调用演示

现在也开始学校服务。所有三个服务都已启动。检查Eureka服务器控制台。学生和学校服务都必须在那里注册。
已经注册2个服务的
转到浏览器并转到 http://localhost:9098//getSchoolDetails/abcschool,它将提供特定学校abcschool详细信息的学校详细信息。我们在内部调用了学生服务。响应在浏览器中将如下所示:学生响应

如果遇到任何错误要检查的事项

  1. 注释@EnableEurekaServer@EnableEurekaClient是应用生态系统的心脏。没有这两件事就根本行不通。
  2. 确保在启动配置客户端服务时,eureka 服务器服务已经在运行,否则可能需要一些时间来注册,这可能会在测试时造成混乱。

总结

我们看到了可以轻松高效地部署服务注册中心和发现服务器以及客户端。Spring 框架在内部维护了很多东西。在这里,我们只是使用几个注释和非常少的配置来快速完成整个事情。
 

演示项目源码下载:(访问密码:9987)
Spring-Cloud-discovery-server.zip 

地址:https://www.leftso.com/article/861.html

相关阅读

演示项目源码下载:(访问密码:9987)Spring-Cloud-discovery-server.zip 了解如何创建微服务的基础上,Spring Cloud,对Netflix的Eureka注...
演示项目源码下载:(访问密码:9987)Spring-Cloud-Consoul.zip了解如何创建微服务的基础上Spring cloud,对登记HashiCorp Consul注册服务器,以及...
随着Spring Cloud 的越来越流行,国内很多公司也在开始使用该框架了
在这个 Spring cloud 教程中,学习在 spring boot/cloud 项目中使用 Netflix Ribbon 使用客户端负载平衡
项目源码下载:(访问密码:9987)spring-cloud-apigateway_zuul.zip学习使用Netflix Zuul及其与Spring Cloud 的牢固结合来创建负载均衡器
在spring cloud项目中配置配置服务的地址spring.cloud.config.uri不生效的解决办法,spring cloud
项目源码下载:(访问密码:9987)spring-cloud-dashboards.zip在交付基于微服务的应用程序时,广泛使用 Spring Boot 和 Spring Cloud
项目源码下载:(访问密码:9987)Spring-Cloud-Circuit-Breaker.zip学习在调用底层微服务的同时利用调用的Spring Cloud Netflix堆栈组件之一Hys...
演示项目源码下载:(访问密码:9987)spring-cloud-zipkin.zipZipkin是非常有效的工具分布追踪在微服务生态系统
演示项目源码下载:(访问密码:9987)spring-cloud-config-server-git.zip微服务方法现在已经成为任何新 API 开发的行业标准,几乎所有组织都在推广它