首页 > 文章列表 > 使用Spring Boot实现微服务架构下的服务注册与发现

使用Spring Boot实现微服务架构下的服务注册与发现

springboot 微服务架构 服务注册
473 2023-06-23

随着互联网的快速发展,微服务架构正在逐渐成为主流架构之一,这种架构的优势在于将一个大而复杂的应用拆分成多个小而独立的服务,这样可以方便的维护、快速部署和灵活扩展。而在微服务架构中,服务注册与发现是非常重要的一部分,本文将介绍如何使用Spring Boot实现微服务架构下的服务注册与发现。

一、服务注册

服务注册是指将微服务注册到服务注册中心,以便其他服务可以发现并调用它。在Spring Boot中,可以使用Eureka作为服务注册中心。下面是通过Spring Boot和Eureka实现服务注册的步骤:

  1. 引入Eureka依赖

首先需要在pom.xml文件中引入Eureka的依赖:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
  1. 编写配置文件

然后需要在application.yml或application.properties文件中配置相关属性:

server:
  port: 8761

spring:
  application:
    name: eureka-server

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

这里的属性意义如下:

  • server.port: Eureka服务注册中心的端口号
  • spring.application.name: Eureka服务注册中心的名称,这里设为eureka-server
  • eureka.instance.hostname: 服务注册中心的主机名,这里设为localhost,也可以设置为IP地址
  • eureka.client.registerWithEureka: 是否将本服务注册到Eureka服务注册中心,这里设为false,表示不注册
  • eureka.client.fetchRegistry: 是否获取Eureka服务注册中心的服务,这里设为false,表示不获取
  • eureka.client.serviceUrl.defaultZone: Eureka服务注册中心的地址,这里设置为http://${eureka.instance.hostname}:${server.port}/eureka/
  1. 添加@EnableEurekaServer注解

最后,在Spring Boot启动类上添加@EnableEurekaServer注解,启用Eureka服务注册中心:

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

这样就完成了服务注册中心的搭建,可以通过http://localhost:8761访问Eureka服务注册中心的控制台。

二、服务发现

服务发现是指在微服务架构中,服务可以通过服务注册中心的地址和名称,自动发现和调用其它微服务。为了实现服务发现,可以在Spring Boot中使用Eureka客户端。

  1. 引入Eureka客户端依赖

同样需要在pom.xml文件中引入Eureka客户端依赖:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  1. 编写配置文件

然后需要在application.yml或application.properties文件中配置相关属性:

server:
  port: 8080

spring:
  application:
    name: demo-service

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

这里的属性意义如下:

  • server.port: 服务端口号
  • spring.application.name: 服务注册的名称,在Eureka服务注册中心中将使用该名称来查找服务
  • eureka.client.serviceUrl.defaultZone: Eureka服务注册中心的地址,这里设置为http://localhost:8761/eureka/
  1. 添加@EnableDiscoveryClient注解

最后,在Spring Boot启动类上添加@EnableDiscoveryClient注解,启用Eureka客户端:

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

这样就完成了使用Spring Boot和Eureka实现微服务架构下的服务注册与发现。

总结

本文介绍了如何使用Spring Boot和Eureka实现微服务架构下的服务注册与发现。服务注册与发现在微服务架构中非常重要,通过Eureka可以简单、方便地实现服务的注册和发现,使得不同的微服务之间可以快速地互相调用和交互。