点击关注公众号,Java干货及时送达![](https://img-blog.csdnimg.cn/img_convert/dd3f788c78999c63ff1ef2fbb3f79c07.png)
Spring Cloud Gateway是Spring Cloud官方推出的第二代网关框架,取代Zuul网关。网关作为流量的,在微服务系统中有着非常作用,网关常见的功能有路由转发、权限校验、限流控制等作用。
在上一节的案例中,我们讲述了如何使用nacos作为服务注册中心和配置中心,使用feign和sc loadbalancer作为服务调用。本小节将讲述如何使用spring cloud gateway作为服务网关。
工程构建
新建一个gateway的工程,工程目录如下:
![](https://img-blog.csdnimg.cn/img_convert/dc556738e9a03464e0cfa10d9efe1fad.png)
gateway需要注册到nacos中去,需要引入以下的依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
在配置文件application.pom文件:
server:
port: 5000
spring:
application:
name: gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
gateway:
discovery:
locator:
enabled: false
lowerCaseServiceId: true
routes:
- id: provider
uri: lb://provider
predicates:
- Path=/provider/**
filters:
- StripPrefix=1
- id: consumer
uri: lb://consumer
predicates:
- Path=/consumer/**
filters:
- StripPrefix=1
配置的解释请阅读文末的相关教程,在这里不再重复。
在工程的启动文件加上相关注解:
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
依次启动gateway\consumer\provider三个工程,在nacos中已经成功注册:
![](https://img-blog.csdnimg.cn/img_convert/7d013ab8c0b128733d10199d88f1b159.png)
在浏览器上输入http://localhost:5000/consumer/hi-feign,浏览器返回响应:
hello feign, i'm provider ,my port:8762
gateway还有其他很多强大的功能在这里就不再讲述。
相关教程
Spring Cloud Gateway 初体验:https://www.fangzhipeng.com/springcloud/2018/11/06/sc-f-gateway1.html
Spring Cloud Gateway 之Predict篇:https://www.fangzhipeng.com/springcloud/2018/12/05/sc-f-gateway2.html
spring cloud gateway之filter篇:https://www.fangzhipeng.com/springcloud/2018/12/21/sc-f-gatway3.html
spring cloud gateway 之限流篇:https://www.fangzhipeng.com/springcloud/2018/12/22/sc-f-gatway4.html
spring cloud gateway之服务注册与发现:https://www.fangzhipeng.com/springcloud/2018/12/23/sc-f-gateway5.html
源码下载
https://github.com/forezp/SpringCloudLearning/tree/master/sc-2020-chapter2
热门内容:服务端如何防止订单重复支付!
拜托!不要用“ ! = null " 做判空了
道友自诉:入职中软一个月(外包华为)就离职了!
23 种设计模式的通俗解释,看完秒懂
token多平台身份认证架构设计思路
最近面试BAT,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。
明天见(。・ω・。)ノ♡