• 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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    除了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=/**
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    其中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地址匹配
    • 根据访问路径匹配(和例子中一样)
    • 组合使用,这些断言可以组合起来去使用

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

  • 相关阅读:
    谷歌浏览器HttpOnly跨域请求
    Linux C语言开发-D4数据类型
    拼多多根据ID取商品详情 API 返回值说明
    @Autowired 和 @Resource 的区别(为什么更推荐使用@Resource ?)
    如何实现毫米波波束成形和大规模MiMo?
    【Java基础】23种设计模式介绍
    Nlog&Prism&WPF
    没有 accept,建立 TCP 连接,可以吗?
    在微信公众平台 设置小程序域名白名单
    【Python百日进阶-Web开发-Feffery】Day399 - fac实例:上海疫情地图
  • 原文地址:https://blog.csdn.net/qq_43568790/article/details/125523779