1.pom.xml:配置文件
spring‐cloud‐starter‐gateway
spring‐cloud‐starter‐netflix‐hystrix
spring‐cloud‐starter‐netflix‐eureka‐ client
2.GatewayApplication:引导类
@SpringBootApplication
@EnableEurekaClient
public class GateWayApplication {
public static void main(String[] args) {
SpringApplication.run(GateWayApplication.class,args);
}
}
3.application.yml:配置文件
spring:
application:
name: sysgateway
cloud:
gateway:
routes: -->路由
- id: goods -->路由id,可以随便写
uri: lb://goods -->代理的服务地址(真实地址);lb表示冲注册中心中获取的服务
predicates: -->路由断言:可以匹配映射路径
- Path=/goods/** -->请求路径
filters:
- StripPrefix= 1 -->去除一个前缀
- id: system
uri: lb://system
predicates:
- Path=/system/**
filters:
- StripPrefix= 1
server:
port: 9101
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:6868/eureka
instance:
prefer-ip-address: true
拓展内容:
PrefixPath=/user http://localhost:10010/8 --》http://localhost:9091/user/8
PrefixPath=/user/abc http://localhost:10010/8 --》http://localhost:9091/user/abc/8
StripPrefix=1 http://localhost:10010/api/user/8 --》http://localhost:9091/user/8
StripPrefix=2 http://localhost:10010/api/user/8 --》http://localhost:9091/8
1.当通过网关访问时的地址,网关的地址localhost:9101
http://localhost:9101/goods/brand/category/手机
2.网关接到请求,并找到需要的goods服务在注册中心的真实地址地址替换
http://localhost:9001/goods/brand/category/手机
3.在根据配置StripPrefix= 1,去掉第一个前缀变为,及变成了真实地址
http://localhost:9001/brand/category/手机
解决微服务网关跨域
改application.yml
globalcors:
cors-configurations:
'[/**]': # 匹配所有请求
allowedOrigins: "*" #跨域处理 允许所有的域
allowedMethods: #支持的方法
- GET
- POST
- PUT
- DELETE
在spring.cloud.gateway节点添加配置(注意层级关系),服务端是可以跨域的.
chain 束缚
filter 过滤
exchange 交换
global 总
GlobalFilter 全局过滤器(接口)
Ordered 过滤优先级(接口)
@Component 组件 spring中的注解,交给spring管理,注册到容器中