你好,这里是codetrend专栏“SpringCloud2023实战”。
本文主要简单介绍SpringCloud2023实战中SpringCoudGateway的搭建。
后续的文章将会介绍在微服务中使用熔断Sentinel、鉴权OAuth2、SSO等技术。
网关的选型不多,目前spring支持和维护的项目是 Spring Cloud Gateway。
Spring Cloud Gateway作为一个轻量级、高性能、可定制的网关服务,具有与Spring生态系统的紧密集成、负载均衡、断路器等丰富的功能,适用于构建微服务架构中的网关层,提供统一的访问控制、路由转发和过滤处理等功能。
Gateway 具有以下优点:

这张图大概说明了网关如何工作的。
客户端向 Spring Cloud Gateway 发送请求。如果网关处理器映射确定请求匹配某个路由,则将其发送到网关 Web 处理器。该处理器将请求通过特定于请求的过滤器链。
过滤器被分为前后两部分,原因是过滤器可以在代理请求发送之前和之后运行逻辑。
所有前置过滤器逻辑都会被执行。然后发出代理请求。代理请求发出后,将运行后置过滤器逻辑。
spring-cloud-starter-gateway 。
io.rainforest
banana
1.0
4.0.0
banana-gateway
spring cloud gateway
jar
org.springframework.cloud
spring-cloud-starter-gateway
org.springframework.boot
spring-boot-starter-data-redis-reactive
org.springframework.cloud
spring-cloud-starter-zookeeper-discovery
org.springframework.cloud
spring-cloud-starter-loadbalancer
io.rainforest
banana-common-core
org.springdoc
springdoc-openapi-starter-webflux-ui
org.springframework.boot
spring-boot-maven-plugin
application.yml,网关配置主要是 spring.cloud.gateway 下面的配置。spring.application.name: gateway
spring:
cloud:
zookeeper:
connect-string: localhost:2181
gateway:
discovery:
locator:
enabled: false
lowerCaseServiceId: true
routes:
- id: client1
uri: lb://client1
predicates:
- Path=/client1/**
# filters:
# - StripPrefix=0
- id: client2
uri: lb://client2
predicates:
- Path=/client2/**
filters:
- StripPrefix=0
- id: client3
uri: lb://client3
predicates:
- Path=/client3/**
filters:
- StripPrefix=0
server:
port: 10100
servlet:
context-path: /gateway
spring.cloud.gateway.routes 配置不同的服务路由。package io.rainforest.banana.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
不需要修改代码就可以开箱即用Gateway。此处仅展示如何调用。
实际情况中网关还需要使用它强大的Filter来实现各种功能。
在这里Gateway就相当于一个更加强大的Nginx。只做了路由分发。
localhost:10100/client3/** 可以访问注册中心服务编码为client3的所有接口。完整源码信息查看可以在gitee或者github上搜索r0ad。
来自一线全栈程序员nine的探索与实践,持续迭代中。
欢迎关注或者点个小红心~
登录查看全部
参与评论
手机查看
返回顶部