本篇延续上篇Zuul基础学习,作一个实践测试java
在以前学习的篇章中,一直积累学习,因此这边已经存在注册中心,product服务,order服务,config配置中心等等服务,每次写demo,注册中心和配置中心都是一直先启动,本次学习Zuul也不例外web
新建一个服务 ,第一步利用IDEA建立spring
第二步,选择红框中的组件,通常服务我都会加上Webdocker
第三步开始配置,将application.properties文件改为bootstrap.yml,若是忘了为何这样改,能够回头看看Spring cloud config & Spring cloud bus等内容,内容以下bootstrap
spring: application: name: gateway cloud: config: discovery: service-id: CONFIG enabled: true profile: dev eureka: client: service-url: defaultZone: http://localhost:8761/eureka/
第四步,都是套路,在启动类上添加开启组件注解@EnableZuulProxy浏览器
package com.cloud.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @SpringBootApplication @EnableZuulProxy public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
说明下目前启动相关服务以及端口->eureka server:8761,config:8000,product:9000,order:9001,docker 中rabbitMQ:5672,gateway:7000-->从gateway网关访问product服务中的接口springboot
目前网关服务中未添加任何过滤器,先试试效果,下图是启动后注册中心的3个服务发现cookie
在product服务中,以前写好的简单查询接口: localhost:9000/product/list 返回一个列表app
如今从gateway网关去访问: localhost:7000/product/product/list 就能够访问到了学习
第一个product是注册中心的application的名字,后面product/list是接口
访问config也是没问题的,访问方式:localhost:7000/config/config/product-dev.yml
可是呢,有个性的我每次都根据service-id来写,明显不是那么合我口味,因而能够添加yml配置
zuul: routes: MyProduct: #这个能够自定义 path: /myProduct/** serviceId: product
意思是访问服务中心serviceId是product的服务,访问path方式是/myProduct/**, **表明全部该服务接口,能够浏览器访问试试
若是想要看到全部路由,能够打开actuator监控,在springboot2.0之后,actuator改动比较大,在以前的笔记中有记录相关内容,若是你使用的是2.0以前的版本,配置本身适合的方式就能够,这里以springboot2.0.3版本为例,如下配置,以及监控信息展现,上面是目前的全部路由
management: endpoints: web: exposure: include: ["routes"]
还有一种简洁的路由写法,其中ignored是排除接口,set类型的参数,使用- /path方式配置
zuul: routes: product: /myProduct/** ignored-patterns: - /**/product/hello
另外说个点,Zuul默认是不接收cookie,须要配置才能够,贴上完整的配置
spring: application: name: gateway cloud: config: discovery: service-id: CONFIG enabled: true profile: dev eureka: client: service-url: defaultZone: http://localhost:8761/eureka/ zuul: routes: product: /myProduct/** sensitiveHeaders: #设置空便可,可用于接收cookie ignored-patterns: - /**/product/hello management: endpoints: web: exposure: include: ["routes"]
关于路由,在开发的时候,咱们会加服务,加了服务,就要改动配置,都要从新启动什么的,相信你们都知道,用到以前学过的springcloud bus结合MQ实现配置动态刷新springcloud config
配置刷新了,咱们还要在代码中也作到动态更新到运行中,因此能够在启动类下面加一段:
@SpringBootApplication @EnableZuulProxy public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } @ConfigurationProperties("zuul") @RefreshScope public ZuulProperties zuulProperties(){ return new ZuulProperties(); } }
以上是粗略的路由相关的笔记,下来继续学习过滤器相关的内容
---------------------------------------------