一、实现方法
1.模块结构
2.pom文件引入网关依赖和注册中心依赖
<!--引入gateway依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--gateway也是需要注册到服务中心的-->
<!--注入eureka client 依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
3.创建启动类
package com.cxstar.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
4.创建application配置文件
server:
port: 10086 # 网关端口
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:9999/eureka/
spring:
application:
name: gateway # 服务名称
cloud:
gateway:
globalcors:
add-to-simple-url-handler-mapping: true # 接收浏览器询问是否允许跨域的请求
cors-configurations:
# 仅在开发环境设置为*
'[/**]':
allowedOrigins: # 允许哪些网站的ajax跨域请求
- "http://192.168.0.46:8080"
allowedHeaders: # 允许的ajax跨域请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedMethods: "*" # 允许在请求中携带的头信息
allowCredentials: true # 是否允许携带cookie
maxAge: 36000 # 跨域请求有效期
discovery:
locator:
enabled: true # 开启从注册中心动态创建路由的功能,利用微服务名进行路由
routes:
- id: order-service
uri: lb://order-service # 匹配后提供服务的路由地址-------这里用的动态路由格式统一为 lb://注册进eureka服务中心的名字
predicates:
- Path=/order/** # 断言,路径相匹配的进行路由--------断言也就是匹配方式,当识别到/servero1/**时就会跳转上面的uri
# filters:
# - StripPrefix=1 # 例如,请求/name/bar/foo,去除掉前面两个前缀之后,最后转发到目标服务的路径为/foo-----这里写的是只去掉一个,多了自然会导致路径错误,不同的访问url配置也不同
# 配置Gateway日志等级,输出转发细节信息
logging:
level:
org.springframework.cloud.gateway: debug
二、测试结果