一、项目搭建
1.引入jar包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
springCloud 项目需要和springboot 的版本对应上,要不然会经常出现,项目启动找不到类或者找不到方法。springcloud和springboot的版本对应关系可以在springCloud官网或者spring官网进行查询
https://docs.spring.io/spring-cloud/docs/Hoxton.SR8/reference/html/
或者在spring官网
https://spring.io/
2. 启动类配置
如果配合配置中心使用,加上配置服务发现注解 @EnableDiscoveryClient
@SpringBootApplication
@EnableDiscoveryClient
public class ZhangGetwayApplication {
public static void main(String[] args) {
SpringApplication.run(ZhangGetwayApplication.class, args);
}
}
3.配置文件
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
instance-id: gateway #主机名称修改
prefer-ip-address: true #访问路径可以显示ip
hostname: cloud-gateway-service
server:
port: 8070
spring:
application:
name: zhang-getway
main:
# 标记以显式请求特定类型的Web应用程序。如果未设置,则基于类路径自动检测。 设置getway 项目启动的web类型为 reactive
web-application-type: reactive
cloud:
gateway:
routes:
- id: payment_routh #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
uri: http://localhost:8001 #匹配后提供服务的路由地址
predicates:
- Path=/payment/timeout/** # 断言,路径相匹配的进行路由
- id: payment_routh2 #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
uri: http://localhost:8001 #匹配后提供服务的路由地址
predicates:
- Path=/payment/ok/** # 断言,路径相匹配的进行路由
在应用为reactive 类型的时候需要移除掉 的依赖, 移除spring-boot-starer-web依赖即,
类似这样的