如何实现spring cloud getway路由配置

发布时间:2021-10-12 10:01:51 作者:iii
来源:亿速云 阅读:289

这篇文章主要介绍“如何实现spring cloud getway路由配置”,在日常操作中,相信很多人在如何实现spring cloud getway路由配置问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何实现spring cloud getway路由配置”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

1.创建工程getway-server

2.添加pom依赖:

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

3.添加启动类

如何实现spring cloud getway路由配置

4.添加配置文件:

#端口server:  port: 8080#服务名称spring:  application:name: getway-service  cloud:gateway:      routes:
       - id: product-service         uri: lb://product-service     #根据服务名称从注册中心拉取服务请求路径 predicates:
         - Path=/product/**

id:我们自定义的路由 ID,保持唯一
uri:目标服务地址
predicates:路由条件,Predicate 接受一个输入参数,返回一个布尔值结果。该接口包含多种默
认方法来将 Predicate 组合成其他复杂的逻辑(比如:与,或,非)
 

5.启动getway服务报错如下:

如何实现spring cloud getway路由配置

这个错误是因为getway内部是通过netty + webflux实现,webflux实现和springmvc冲突

解决办法:将父工程配置的如下依赖添加到需要的工程中:

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId></dependency>

对应在product和order服务中添加依赖,再次启动getway服务就成功了。

访问 http://localhost:8080/product/1

如何实现spring cloud getway路由配置

重写转发路径

在SpringCloud Gateway中,路由转发是直接将匹配的路由path直接拼接到映射路径(URI)之后,那
么在微服务开发中往往没有那么便利。这里就可以通过RewritePath机制来进行路径重写。
(1) 案例改造
修改 application.yml ,将匹配路径改为 /product-service/**

如何实现spring cloud getway路由配置

重新启动网关,我们在浏览器访问http://127.0.0.1:8080/product-service/product/1,会抛出404。这
是由于路由转发规则默认转发到商品微服务( http://127.0.0.1:9002/productservice/product/1 )路径上,而商品微服务又没有 product-service 对应的映射配置。
(2) 添加RewritePath重写转发路径
修改 application.yml ,添加重写规则

#服务名称spring:  application:name: getway-service  cloud:gateway:      routes:
      - id: product-service#        uri: http://127.0.0.1:9001        uri: lb://product-service     #根据服务名称从注册中心拉取服务请求路径        predicates:#          - Path=/product/**        - Path=/product-service/**filters:
        - RewritePath=/product-service/(?<segment>.*), /$\{segment}#根据服务名称配置路由转发    discovery:      locator:enabled: true   #开启服务名称自动转发        lower-case-service-id: true   #名称小写形式

通过RewritePath配置重写转发的url,将/product-service/(?.*),重写为{segment},然后转发到订单
微服务。比如在网页上请求http://localhost:8080/product-service/product,此时会将请求转发到htt
p://127.0.0.1:9002/product/1

如何实现spring cloud getway路由配置

                                                                            网关限流 

1.pom文件添加如下依赖:

<!--redis的依赖--><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-redis-reactive</artifactId></dependency><!--监控依赖--><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-actuator</artifactId></dependency> 2.修改配置文件
server:  port: 8080 #端口spring:  application:name: gateway-service #服务名称  redis:host: localhostpool: 6379database: 0  cloud: #配置SpringCloudGateway的路由    gateway:      routes:
      - id: order-serviceuri: lb://order-servicepredicates:
        - Path=/order-service/**filters:
        - RewritePath=/order-service/(?<segment>.*), /$\{segment}
      - id: product-serviceuri: lb://product-servicepredicates:
        - Path=/product-service/**filters:
        - name: RequestRateLimiter          args:#            # 使用SpEL从容器中获取对象            key-resolver: '#{@pathKeyResolver}'#            # 令牌桶每秒填充平均速率            redis-rate-limiter.replenishRate: 1#            # 令牌桶的上限            redis-rate-limiter.burstCapacity: 3
        - RewritePath=/product-service/(?<segment>.*), /$\{segment}

3.新建KeyResolverConfiguration类

@Configurationpublic class KeyResolverConfiguration {/**     * 请求路径的限流规则     * @return     */    @Bean    public KeyResolver pathKeyResolver() {return new KeyResolver(){public Mono<String> resolve(ServerWebExchange exchange) {return Mono.just(exchange.getRequest().getPath().toString());            }
        };    }
}

访问 http://localhost:8080/product-service/product/1

如何实现spring cloud getway路由配置

如果连续刷新请求就会出现如下界面

如何实现spring cloud getway路由配置

通过reids的MONITOR可以监听redis的执行过程。这时候Redis中会有对应的数据

如何实现spring cloud getway路由配置

大括号中就是我们的限流Key,这边是IP,本地的就是localhost
timestamp:存储的是当前时间的秒数,也就是System.currentTimeMillis() / 1000或者
Instant.now().getEpochSecond()
tokens:存储的是当前这秒钟的对应的可用的令牌数量
 

根据参数限流   

1.在KeyResolverConfiguration类中添加如下代码

/** * 请求参数限流 * @return */@Beanpublic KeyResolver userKeyResolver() {return exchange -> Mono.just(
            exchange.getRequest().getQueryParams().getFirst("userId")//exchange.getRequest().getHeaders().getFirst("X-Forwarded-For") 基于请求ip的限流    );}

2.修改配置文件:

如何实现spring cloud getway路由配置

访问同上,如果访问频率过高也是出现同样的效果

访问地址: http://localhost:8080/product-service/product/1?userId=1

需要带上参数。

到此,关于“如何实现spring cloud getway路由配置”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. 基于Nacos如何通过Spring Cloud Gateway实现动态路由?
  2. Spring Cloud 网关服务 zuul  动态路由的实现方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

getway

上一篇:怎么解决Eureka中Jersey 1.x版本过旧的问题

下一篇:docker容器基本的命令有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》