微服务框架——SpringCloud(三)
1.Zuul服务网关
作用:路由转发和过滤,将请求转发到微服务或拦截请求。Zuul默认集成了负载均衡功能。
2.Zuul实现路由
a.新建springboot项目,依赖选择 Eureka Discovery 、Web 以及 Zuul。
b.pom文件关键依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> ...... </dependencies> ......
c.application.yml文件
spring: application: name: zuul-server server: port: 8090 eureka: client: service-url: defaultZone: http://localhost:8081/eureka/ zuul: routes: #自定义名称,建议使用微服务名称 eurekaClientConsumer: #路径 path: /ribbon/** #微服务名称 serviceId: eureka-client-consumer #自定义名称,建议使用微服务名称 eurekaClientFeign: #路径 path: /feign/** #微服务名称 serviceId: eureka-client-feign
d.启动类添加注解 @EnableEurekaClient 和 @EnableZuulProxy
@SpringBootApplication @EnableEurekaClient @EnableZuulProxy public class ZuulServerApplication { public static void main(String[] args) { SpringApplication.run(ZuulServerApplication.class, args); } }
3.Zuul实现过滤
a.创建拦截器
@Component public class TokenFilter extends ZuulFilter { /** * 表示过滤类型(pre表示路由之前; routing表示路由当中;post表示路由之后;error表示路由发生错误) */ @Override public String filterType() { return "pre"; } /** * 表示执行时序(0的优先级最高) */ @Override public int filterOrder() { return 0; } /** * 是否需要执行过滤 */ @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { System.out.println("[TokenFilter]进入过滤器"); RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); String token = request.getParameter("token"); if(StringUtils.isEmpty(token)) { ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(401); return null; } return null; } }