1、导入依赖 (其中还是用了注册中心eureka和配置中心config,不用可以不导入)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<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-config</artifactId>
</dependency>
2、启动类添加注解(如果不用eureka和config的话可以不加)
@EnableEurekaClient
@EnableDiscoveryClient
3、YAML配置
spring:
application:
name: spring-cloud-gateway
cloud:
config:
discovery:
service-id: config-server
enabled: true
# 指定分支
label: master
# 如果使用了eureka就不需要配置config-server地址
# uri: http://localhost:10021/
name: config-server
profile: gateway
gateway:
routes:
- id: gateway1
uri: lb://config-client
predicates:
- Path=/test/**
filters:
- RewritePath=/test/(?<segment>.*), /test/$\{segment}
eureka:
client:
service-url:
defaultZone: http://{ip}:{port}/eureka/
server:
port: 10031
management:
endpoints:
web:
exposure:
include: "*"
说明:id可以不用配置,默认是uuid,如果没有注册中心的话gateway.routes.uri应该修改成转发的地址例如:http://ip:port, 根据predicates中的配置匹配访问uri,然后根据filters修改访问条件,转发到uri上,这里就是如果访问的地址是http://ip:10031/test/any,转发后的地址就是http://{lb://config-client}/test/any
注意: 这里需要注意的是如果用了配置中心,别把配置中心需要覆盖的内容写到bootstrap.yml中,因为bootstrap.yml的优先级高于application.yml,而配置中心是与application进行合并生成一个Environment,所以会导致配置不生效问题