SpringCloud-gateway网关入门使用

依赖

<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>2.2.1.RELEASE</version>
</dependency>

<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.2.1.RELEASE</version>
</dependency>

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
            <version>2.2.5.RELEASE</version>
</dependency>

除了gateway的依赖之外,还要加上nacos的依赖,因为网关服务也是要注册到nacos中的。
注意:这个对应的springboot版本是2.2.5.RELEASE

注解

目前入门需要的注解就是@EnableDiscoveryClient,用于服务被发现

配置文件

server.port=9010
spring.application.name=gateway
spring.cloud.nacos.discovery.server-addr=xxx.xx.xx.xx:8848
spring.cloud.nacos.config.server-addr=xxx.xx.xx.xx:8848
spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.routes[0].id=gateway1
spring.cloud.gateway.routes[0].uri=lb://service-consumer
spring.cloud.gateway.routes[0].predicates[0]= Path=/**

其中spring.cloud.gateway.discovery.locator.enabled=true是为了让网关服务能够被发现,spring.cloud.gateway.routes[0].id=gateway1是设置第一个路由(可以配置多个路由)的id值,这个是自定义的不重复即可,spring.cloud.gateway.routes[0].uri=lb://service-consumer是通过网关要跳转到的地址,lb是用负载均衡的意思,后面是服务名称,spring.cloud.gateway.routes[0].predicates[0]= Path=/**这个是定义路由的断言,这里的意思是任意路径都会跳转到上面的uri中去。

这里的断言也可以配置多种,比如

  • 根据访问时间匹配
  • 根据cookie匹配
  • 根据host匹配
  • 根据请求方式匹配(get、post等)、
  • 根据请求参数匹配
  • 根据请求ip地址匹配
  • 根据访问路径匹配(和例子中一样)
  • 组合使用,这些断言可以组合起来去使用

具体使用到那些,再根据具体情况去查询即可,先了解到有这些用法。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值