spring cloud gateway网关的简单使用
原来springcloud使用的网关是Zuul,但是Zuul1.0性能不太好,而Zuul2.0一开始并没有开源,Spring为了替换Zuul1.0而开发了Spring Cloud Gateway,所以Spring现在推荐使用的网关是Spring Cloud Gateway。
注: Zuul1 设计比较简单,代码不多也比较容易读懂,它本质上就是一个同步 Servlet,采用多线程阻塞模型 Zuul1.0性能慢的原因:同步 Servlet 使用 thread per connection 方式处理请求。简单讲,每来一个请求,Servlet 容器要为该请求分配一个线程专门负责处理这个请求,直到响应返回客户端这个线程才会被释放返回容器线程池。如果后台服务调用比较耗时,那么这个线程就会被阻塞,阻塞期间线程资源被占用,不能干其它事情。我们知道 Servlet 容器线程池的大小是有限制的,当前端请求量大,而后台慢服务比较多时,很容易耗尽容器线程池内的线程,造成容器无法接受新的请求
为什么用网关?
网关还可以解耦合,例如安全方面的权限,每个微服务模块都要自己校验权限、IP黑白名单过滤,如果有网关,这些重复的功能都可以抽到在网关上处理
网关的四个基本功能
API网关的基本功能:统一接入、协议适配、流量管控与容错、安全防护
DEMO
1)引入依赖
<dependencies> <!-- 网关模块不能引入starter-web --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> </dependencies>
2)yaml配置
3)创建Application主类
@SpringBootApplication @EnableDiscoveryClient public class ApiGatewayApplication { public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class, args); } }
4)测试验证
直接访问服务
上一篇:
IDEA上Java项目控制台中文乱码