天天看点

zuul网关_Spring Cloud第五章:服务网关Zuul

在微服务架构中,需要几个关键的组件,服务注册与发现、服务消费、负载均衡、断路器、智能路由、配置管理等,由这几个组件可以组建一个简单的微服务架构,如下图:

zuul网关_Spring Cloud第五章:服务网关Zuul

客户端的请求首先经过负载均衡(zuul、Ngnix),再到达服务网关(zuul集群),然后再到具体的服务,服务统一注册到高可用的服务注册中心集群,服务的所有的配置文件由配置服务管理(下一篇文章讲述),配置服务的配置文件放在git仓库,方便开发人员随时改配置。

一、Zuul简介

Zuul的主要功能是路由和过滤器。路由功能是微服务的一部分,比如/api/user映射到user服务,/api/shop映射到shop服务。zuul实现了负载均衡。

zuul有以下功能:

  • Authentication
  • Insights
  • Stress Testing
  • Canary Testing
  • Dynamic Routing
  • Service Migration
  • Load Shedding
  • Security
  • Static Response handling
  • Active/Active traffic management

二、准备工作

继续使用上一节的工程。在原有的工程上,创建一个新的工程。

三、创建service-zuul工程

其pom.xml文件如下:

org.springframework.cloudspring-cloud-starter-eurekaorg.springframework.cloudspring-cloud-starter-zuul
           

在其入口applicaton类加上注解@EnableZuulProxy,开启zuul:

@[email protected]@SpringBootApplicationpublic class ServiceZuulApplication {public static void main(String[] args) {SpringApplication.run(ServiceZuulApplication.class, args);}}
           

加上配置文件:

eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/server: port: 8769spring: application: name: service-zuulzuul: routes: api-a: path: /api-a/** serviceId: service-ribbon api-b: path: /api-b/** serviceId: service-feign
           

首先向eureka注册自己,端口为8769,服务名为service-zuul;以/api-a/ 开头的请求都指向service-ribbon;以/api-b/开头的请求都指向service-feign;

依次运行这五个工程;打开浏览器访问:http://localhost:8769/api-a/hi?name=forezp ;浏览器显示:

hi forezp,i am from port:8762

打开浏览器访问:http://localhost:8769/api-b/hi?name=forezp ;浏览器显示:

hi forezp,i am from port:8762

这说明zuul起到了路由的作用;

四、服务过滤

zuul不仅只是路由,并且还能过滤,做一些安全验证。继续改造工程;

@Componentpublic class MyFilter extends ZuulFilter{ private static Logger log = LoggerFactory.getLogger(MyFilter.class); @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info(String.format("%s >>> %s
           

继续阅读