Spring Cloud GateWay搭建

文章目录

Spring Cloud GateWay搭建

简单搭建一个,有注册中心,两个微服务,一个网关的组成的微服务架构。
技术选型: Eurake、Spring boot、Spring cloud Gateway、OpenFeign

1.搭建注册中心:

注册中心,常用的有:Eureka、Consul、Zookeeper、Nacos,此处要明白一点是注册中心本身就是一个服务,所以对注册中心而言,不仅仅局限于java编写的,也存在于是其他语言编写,本质是一个server软件,只需要满足注册中心的功能即可。
在这里插入图片描述

1.1添加依赖

在这里插入图片描述

1.2 配置文件及启动类

在这里插入图片描述

server:
  # 端口
  port: 8888
spring:
  application:
    # 实例名称
    name: eureka-server
eureka:
  client:
    # 是否向eureka注册  默认true 单点服务端需要设置为false
    register-with-eureka: false
    # 是否拉取注册的客户端信息 默认true 单点服务端需要设置为false
    fetch-registry: false
    #自我保护默认关闭
    enable-self-preservation: false
    #注册中心地址,由注册中心ip和项目端口号拼接/eurake
    service-url:
      defaultZone: http://${spring.application.name}:${server.port}/eureka/
  instance:
    # 主机地址 (ip)
    hostname: localhost

在这里插入图片描述

1.3 测试

在浏览器地址栏中输入 http://localhost:8888/
在这里插入图片描述
此时证明我们的注册中心服务以启动完毕!

2.启动两个服务

注册中心服务已启动完毕,接下来启动两个微服务作为注册中的client。定名字为 partService,mpnService。引入Spring mvc 、Eurake Client 和 OpenFeign 依赖。

2.1 添加依赖

在这里插入图片描述
在这里插入图片描述

按照上述步骤创建两个微服务。

2.2 配置文件及启动类

在这里插入图片描述

server:
  # 服务的端口
  port: 8081
spring:
  application:
    name: partService
eureka:
  client:
    # 注册中心地址
    service-url:
      defaultZone: http://localhost:8888/eureka

在这里插入图片描述

2.3 测试

去上面的eurake 网页看下服务是否被注册进去了
在这里插入图片描述

3.配置openFeign

3.1 编写代码

针对两个服务各自创建两个控制层接口,顺便在配置文件中定义下服务的请求上下文路径

在这里插入图片描述
开启OpenFeign。
在这里插入图片描述
调用者
在这里插入图片描述
在这里插入图片描述
被调用者
在这里插入图片描述
在这里插入图片描述

3.2 进行测试

在这里插入图片描述

4.开始搭建网关GateWay

4.1 添加依赖

在这里插入图片描述

4.2 配置文件

在这里插入图片描述

server:
  port: 8080
spring:
  application:
    name: gateway
  cloud:
    gateway:
      # 配置路由
      routes:
        - id: partService
          uri: lb://partService
          predicates:
            - Path=/partService/**
        - id: mpnService
          uri: lb://mpnService
          predicates:
            - Path=/mpnService/**
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8888/eureka
4.3 测试

在这里插入图片描述

在这里插入图片描述
这样一个简单的Spring Cloud GateWay 就已经搭建好了。

<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]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值