GuLi商城-SpringCloud-Gateway网关核心概念、测试API网关

网关作为流量的入口,功能包括路由转发、权限校验、限流控制等

  • Route(路由):包含独一无二的路由id、目的地的URL、断言集合、过滤器集合,断言用来判断

  • 路由是否能到达目的地URL

  • Predicats(断言):用来判断路由是否能到达目的地URL

  • Filter(过滤器):在请求访问成功之前、响应成功之后,都能进行修改


1、注册“gulimall-gateway”到Nacos

1)创建gulimall-gateway微服务

引入common依赖,common里面有 

2)添加“gulimall-common”依赖和“spring-cloud-starter-gateway”依赖,上图所示

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

3)GulimallGatewayApplication类上加上@EnableDiscoveryClient注解 

4)在Nacos中创建“gateway”命名空间,同时在该命名空间中创建gulimall-gateway.yml”

我这里没有这么做,我还是用dev作为命名空间,在dev下创建gulimall-gateway

5)创建“bootstrap.properties”文件,添加如下配置,指明配置中心地址和所属命名空间

6)创建“application.properties”文件,指定服务名和注册中心地址

spring.application.name=gulimall-gateway
spring.cloud.nacos.discovery.server-addr=192.168.137.14:8848
server.port=88

7)启动“gulimall-gateway”

启动报错:

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

因为我们在common模块里配置了mybatis相关的依赖,所以默认spring会扫描我们的数据库配置,

为了防止找不到数据库配置报错,我们要排除掉数据库配置

解决方法:在GulimallGatewayApplication中排除和数据源相关的配置 

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

重新启动网关微服务:

访问Nacos,查看到该服务已经注册到了Nacos中


过程中出现的问题记录: 

解决办法:增加依赖

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


发现网关服务注册到nacos,是在public的命名空间中,不是我们希望的dev中

解决办法:


2、案例,测试网关的路由功能:

配置路由规则

修改层级:

测试:

http://localhost:88/?uri=baidu

 

http://localhost:88/?uri=qq 

参考:

gulimall-learning/谷粒商城—分布式基础.md at master · OYCodeSite/gulimall-learning · GitHub

spring-cloud-gateway官网:https://spring.io/projects/spring-cloud-gateway

spring-cloud-gateway文档:https://docs.spring.io/spring-cloud-

gateway/docs/current/reference/html/

spring-cloud 中文网:https://www.springcloud.cc/

原文链接:https://blog.csdn.net/qq_51998352/article/details/121916920

https://blog.csdn.net/qq_52476654/category_11866407.html

猜你喜欢

转载自blog.csdn.net/ZHOU_VIP/article/details/129714768