spring gateway 的搭建与配置

本文详细介绍了如何使用Spring Cloud Gateway创建一个微服务网关,包括项目搭建、依赖配置、注解使用及YAML配置,实现服务注册、路由转发等功能。

步骤:

  1. 建项目
  2. 给主启动类添加Eureka的注解:@EnableEurekaClient
  3. 添加并配置application.yml

第一步:新建gateway的项目:gateway-8205

需要用到的组件:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

第二步:给主启动类添加Eureka的注解:@EnableEurekaClient

package com.example;

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

@SpringBootApplication
@EnableEurekaClient
public class Gateway8205Application {

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

}

第三步:添加并配置 application.yml

server:
  port: 8205
spring:
  application:
    name: api-gateway
  cloud:
    # 网关配置
    gateway:
      # 配置路由规则
      routes:
        # 路由ID(一个路由配置一个ID)
        - id: product-service

          # 通过注册中心来查找服务(lb代表从注册中心获取服务,并且负载均衡)
          uri: lb://PRODUCT-SERVICE

          # 匹配到的以/product开头的路径都转发到product的服务,相当于访问 lb://PRODUCT-SERVICE/**
          predicates:
            - Path=/product/**

          # 去掉匹配到的路径的第一段
          filters:
             - StripPrefix=1

# 把网关注册到注册中心(从注册中心获取服务地址)
eureka:
  instance:
    instance_id: gateway-${server.port}
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://localhost:8201/eureka

启动,访问:http://localhost:8205/product/index

成功。

<think>我们正在搭建SpringCloud Gateway微服务网关,根据引用内容,以下是关键步骤和代码示例:1.创建SpringBoot项目并添加依赖:-引入`spring-cloud-starter-gateway`-引入服务发现依赖(如Nacos:`spring-cloud-starter-alibaba-nacos-discovery`或 Eureka:`spring-cloud-starter-netflix-eureka-client`)2.创建启动类,并启用服务发现客户端(`@EnableDiscoveryClient`)3.配置application.yml(或application.properties)文件,设置路由规则、服务发现等具体步骤:步骤1:创建项目并添加依赖(以Maven为例)在pom.xml中添加以下依赖(根据引用[3]和[4]): ```xml<dependencies><!--Spring CloudGateway --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!--服务发现:这里以Nacos为例,如果使用Eureka则替换为对应的依赖--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!--如果需要熔断,可以添加hystrix依赖(引用[4]中提到) --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency></dependencies>```步骤2:创建启动类在启动类上添加`@SpringBootApplication`和`@EnableDiscoveryClient`注解(引用[3]): ```javapackage com.example.gateway; importorg.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication@EnableDiscoveryClientpublicclass GatewayApplication {publicstatic voidmain(String[] args) {SpringApplication.run(GatewayApplication.class,args);}} ```步骤3:配置application.yml配置网关路由规则和服务注册中心地址(以Nacos为例): ```yamlserver:port:8080 #网关端口spring:application:name:gateway-service#服务名cloud:nacos:discovery:server-addr:127.0.0.1:8848# Nacos服务器地址gateway:routes:- id: user-service-route #路由ID,唯一uri: lb://user-service #使用服务名进行负载均衡predicates:-Path=/user/**#匹配路径filters:- StripPrefix=1 #去掉第一层前缀(例如请求/user/xxx,转发到user-service时变为/xxx)#可以配置多个路由```以上配置中:- `routes`定义了路由规则,每个路由包括:id:唯一标识uri:目标服务地址,`lb://`表示负载均衡到该服务predicates:断言条件,这里使用路径匹配(Path)filters:过滤器,`StripPrefix=1`表示去掉请求路径中的第一个前缀(即去掉/user)注意:如果使用Eureka作为服务发现,则配置Eureka的地址,例如:```yamleureka:client:service-url:defaultZone:http://localhost:8761/eureka/ ```步骤4:启动网关服务,访问网关的端口,根据配置的路由规则,请求将被转发到相应的微服务。关于跨域配置(引用[4]中提到):可以在application.yml中配置全局跨域:```yamlspring:cloud:gateway:globalcors:cors-configurations:'[/**]':allowedOrigins: "*"#允许所有来源allowedMethods:#允许的方法-GET-POST-PUT-DELETE```或者通过Java配置配置(更灵活): ```java@Configurationpublicclass CorsConfig {@BeanpublicCorsWebFilter corsWebFilter(){CorsConfigurationcorsConfig= newCorsConfiguration();corsConfig.addAllowedOrigin("*");corsConfig.addAllowedMethod("*");corsConfig.addAllowedHeader("*");UrlBasedCorsConfigurationSource source= newUrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**",corsConfig);return newCorsWebFilter(source);} }```至此,SpringCloud Gateway网关的基本搭建就完成了。引用说明:-引用[3]提供了使用Nacos作为服务发现时网关的依赖和启动类配置。-引用[4]提供了使用Eureka作为服务发现以及跨域配置的参考。注意:实际项目中,请根据使用的服务注册中心选择相应的依赖和配置。§§相关问题§§1. SpringCloud Gateway和Zuul有什么区别?2.如何在Spring CloudGateway中实现限流?3.Spring CloudGateway的过滤器有哪些类型?如何自定义过滤器?</think>### Spring Cloud Gateway 微服务网关搭建指南 Spring Cloud GatewaySpring 官方推出的 API 网关,基于 Spring 5 + WebFlux + Reactor 技术栈开发,提供路由转发、安全控制、限流熔断等核心功能。以下是详细搭建步骤: --- #### 一、环境准备 1. **基础环境**: - JDK 1.8+ - Spring Boot 2.x - Spring Cloud 2020.0.x 或更高版本 - 服务注册中心(Nacos/Eureka) 2. **项目依赖**(`pom.xml`): ```xml <dependencies> <!-- 网关核心依赖 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!-- 服务发现(以Nacos为例) --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!-- 熔断支持(可选) --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> </dependencies> ``` --- #### 二、核心代码实现 1. **启动类配置**(`GatewayApplication.java`): ```java @SpringBootApplication @EnableDiscoveryClient // 启用服务发现 public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } } ``` 2. **路由配置**(`application.yml`): ```yaml server: port: 8080 # 网关端口 spring: application: name: api-gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848 # Nacos地址 gateway: routes: - id: user-service-route uri: lb://user-service # 服务名负载均衡 predicates: - Path=/user/** # 路径匹配规则 filters: - StripPrefix=1 # 移除路径前缀 - AddRequestHeader=X-Request-Red, Blue - id: order-service-route uri: lb://order-service predicates: - Method=GET,POST # 请求方法匹配 ``` --- #### 三、关键配置说明 1. **路由规则**: - `id`:路由唯一标识 - `uri`:目标服务地址,`lb://`表示负载均衡 - `predicates`:匹配条件(路径、方法、Header等) - `filters`:请求处理过滤器 2. **跨域配置**: ```yaml spring: cloud: gateway: globalcors: cors-configurations: '[/**]': allowedOrigins: "*" allowedMethods: "GET,POST,PUT,DELETE" ``` --- #### 四、验证网关功能 1. **测试路由**: - 访问 `http://localhost:8080/user/1` - 网关将请求转发至 `user-service` 服务的 `/1` 接口 2. **查看路由状态**: - 访问 `/actuator/gateway/routes`(需开启Actuator) - 返回所有已配置路由信息 --- #### 五、高级特性扩展 1. **自定义过滤器**: ```java @Component public class AuthFilter implements GlobalFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { if (!exchange.getRequest().getHeaders().containsKey("Authorization")) { exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); return exchange.getResponse().setComplete(); } return chain.filter(exchange); } } ``` 2. **集成限流**(使用Redis): ```yaml spring: cloud: gateway: routes: - id: rate-limit-route uri: lb://service filters: - name: RequestRateLimiter args: redis-rate-limiter.replenishRate: 10 # 每秒令牌数 redis-rate-limiter.burstCapacity: 20 # 最大令牌数 ``` --- ### 常见问题解决 1. **服务无法发现**: - 检查注册中心地址是否正确 - 确保目标服务已注册到Nacos/Eureka 2. **路由不生效**: - 验证 `predicates` 路径匹配规则 - 检查服务名是否注册中心一致 3. **跨域问题**: - 确认全局跨域配置已启用 - 检查前端请求是否携带必要Header > 引用说明:Spring Cloud Gateway 作为 Spring Cloud 生态中的网关组件,替代了早期的 Zuul,提供基于 Filter 链的统一路由管理能力,支持动态路由配置和丰富的过滤器扩展[^1][^2]。具体实现中需结合服务注册中心(如 Nacos)完成服务发现[^3][^4]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值