微服务网关介绍和使用

81 阅读1分钟

1 基本信息

微服务网关是一个用于管理和路由微服务的入口点,它负责处理客户端请求并将其路由到适当的微服务。Spring Cloud提供了一些工具,其中最常用的是Spring Cloud Gateway。

2 使用

  1. 首先,确保你的项目中包含了Spring Cloud Gateway的依赖。可以在 pom.xml 文件中添加以下依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
  1. 接下来,创建一个Spring Boot应用程序,并使用 @EnableEurekaClient 注解将其注册到服务注册中心(如果你正在使用Eureka)。这个示例中假设你正在使用Eureka作为服务注册中心。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class GatewayServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayServiceApplication.class, args);
    }
}
  1. 然后,配置一个简单的网关路由。在 application.yml 文件中添加以下配置

以下配置中,service1-routeservice2-route 是两个路由的标识符,uri 指定了对应微服务的地址,predicates 则定义了匹配规则。在这个示例中,根据请求路径进行路由,分别将 /service1/** 的请求路由到 service1 微服务,将 /service2/** 的请求路由到 service2 微服务。

spring:
  cloud:
    gateway:
      routes:
        - id: service1-route
          uri: lb://service1   # 这里的 service1 是微服务的名称
          predicates:
            - Path=/service1/**
        - id: service2-route
          uri: lb://service2   # 这里的 service2 是另一个微服务的名称
          predicates:
            - Path=/service2/**
  1. 最后,启动你的网关应用程序

网关将会注册到Eureka服务器,并开始监听来自客户端的请求,按照配置的路由规则进行转发。