赞
踩
网关作为流量的入口,常用功能包括路由转发,权限校验,限流控制等。而springcloud Gateway作为SpringCloud官方推出的第二代网关框架,取代了Zuul网关。
主要有三大部分
工作流程如下
Example application.yml
- spring:
- cloud:
- gateway:
- routes:
- - id: after_route
- uri: https://example.org
- predicates:
- - After=2017-01-20T17:42:47.789-07:00[America/Denver]
上面的例子就是设置了一个网关断言规则
现在自己创建并测试一下Api网关
首先创建一个网关模块
pom中添加common模块依赖
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.1.8.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <groupId>com.example.gulimall</groupId>
- <artifactId>gulimall-gateway</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <name>gulimall-gateway</name>
- <description>gulimall-gateway</description>
- <properties>
- <java.version>1.8</java.version>
- <spring-cloud.version>Greenwich.SR3</spring-cloud.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>com.example.gulimall</groupId>
- <artifactId>gulimall-common</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-gateway</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-dependencies</artifactId>
- <version>${spring-cloud.version}</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
- </project>
在nacos中添加配置文件
然后在启动类上加上服务注册发现注解@EnableDiscoveryClient
application.properties
- spring.cloud.nacos.discovery.server-addr=192.168.159.135:8848
- spring.application.name=gulimall-gateway
- server.port=88
bootstrap.properties
- spring.application.name=gulimall-gateway
-
- spring.cloud.nacos.config.server-addr=192.168.159.135:8848
-
- spring.cloud.nacos.config.namespace=72bcbd7a-be8c-48cf-8584-2eeee5d14664
-
- spring.cloud.nacos.config.group=dev
最后再创建
application.yml
- spring:
- cloud:
- gateway:
- routes:
- - id: test_route
- uri: https://www.baidu.com
- predicates:
- - Query=url,baidu
- - id: qq_route
- uri: https://www.qq.com
- predicates:
- - Query=url,qq
表示如果地址带有url头并且为baidu时,跳转至https://www.baidu.com,qq也一样
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。