目录
一、添加pom依赖
二、配置yml文件
三、自定义过滤器
四、跨域统一配置
五、 gateway整合sentinel服务保护
(1)添加sentinel依赖
(2)开启你的sentinel服务
(3)添加sentinel配置
一、添加pom依赖
在gateway服务里添加依赖
org.springframework.cloud spring-cloud-starter-gateway
二、配置yml文件
server:
port: 8088
spring:
application:
name: api-gateway
cloud:
nacos:
server-addr: localhost:8848 # nacos的服务配置
discovery:
cluster-name: Service_cluster_1 #集群
group: Service_group_1 # 分组名
username: nacos # 用户名
password: nacos # 密码
namespace: public # 环境分类
#gateway的配置
gateway:
# 路由规则
routes:
- id: server3_route # 路由的唯一标识,路由到对应的服务
# uri: http://localhost:8003/ #需要转发的地址
uri: lb://SERVICE-3 #注册到nacos后,这里直接写路由服务的服务名
# lb load balance nacos里的本地负载均衡策略
#断言规则,用于路由规则的匹配
predicates:
- Path=/server3_serv/**
#localhost:8088/server3_serv/order/add 路由到如下路径
#localhost:8003/server3_serv/order/add
#由于server1的访问路径里没有/server3_serv/路径,所以这里需要过滤掉该路径
filters:
- StripPrefix=1 #转发之前去掉第一层的路径,过滤调用附加路径
#localhost:8003/order/add
# - id: server1_route
这里注意配置到nacos里和直接使用在uri的写法上有些区别,nacos里的只需要lb://服务名即可。
要注意gateway服务里不能添加web的开启依赖,不然会报错!
访问服务localhost:8088/server3_serv/test,相当于访问了localhost:8003/test的路径,效果如下:
三、自定义过滤器
Gateway 自定义过滤器的实现_简单随风的博客-CSDN博客_gateway自定义过滤器
四、跨域统一配置
也可以通过配置类的方式来解决:
五、 gateway整合sentinel服务保护
(1)添加sentinel依赖
com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel
com.alibaba.cloud
spring-cloud-alibaba-sentinel-gateway
(2)开启你的sentinel服务
com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel
com.alibaba.cloud
spring-cloud-alibaba-sentinel-gateway
(2)开启你的sentinel服务
(3)添加sentinel配置
spring:
cloud:
# sentinel配置
sentinel:
transport:
dashboard: 127.0.0.1:8080
访问后可以看到已监控到该网关了。



