SpringCloud学习之Zuul路由转发
API网关
在微服务架构中,通常会有多个服务提供者。每个服务提供者的服务数量也会随着整个系统体量的增大也会随之增长和变更。为了更好的调用微服务,可以通过网关对微服务的调用进行管理,使得效率更高和更易维护,达到对外暴露聚合API,屏蔽内部微服务的微小变动,保持整个系统的稳定性的效果。
同时网关还能提供负载均衡,统一鉴权,协议转换,监控监测等一系列功能。详细了解可以阅读下文,这里贴上该文的一张关于网关的流程图
Pattern: API Gateway / Backends for Frontends
Zuul路由转发
Zuul是Spring Cloud全家桶中的微服务API网关。
所有从设备或网站来的请求都会经过Zuul到达后端的Netflix应用程序。作为一个边界性质的应用程序,Zuul提供了动态路由、监控、弹性负载和安全功能。Zuul底层利用各种filter实现如下功能:
1、认证和安全
2、性能监测
3、动态路由。
4、负载卸载
5、静态资源处理
Service-Consumer中添加Zuul路由转发功能
添加依赖
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-zuul -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
主启动类添加注解@EnableZuulProxy
@EnableZuulProxy
:开启Zuul路由功能
package com.rui;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* @author WangRui
* @date 2020/10/20 16:26
*/
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableZuulProxy
public class ServiceConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceConsumerApplication.class,args);
}
}
配置Zuul路由
usermanage:
路由别名
path: /userInfo/**
:访问路径
serviceId: service-provider
:微服务名称
# zuul路由配置
zuul:
routes:
usermanage:
path: /userInfo/**
serviceId: service-provider
配置完成后启动项目,通过访问路径localhost:8083/userInfo/user/selectAll
访问服务,成功完成调用。