Zuul的主要功能是路由转发和过滤器。路由功能是微服务的一部分,比如/api/user转发到到user服务,/api/shop转发到到shop服务。zuul默认和Ribbon结合实现了负载均衡的功能。
Authentication
Insights
Stress Testing
Canary Testing
Dynamic Routing
Service Migration
Load Shedding
Security
Static Response handling
Active/Active traffic management
新建一个project为zuul_demo
<!--因为是eureka的注册中心所以需要引入一个客户端的依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--zuul主要依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
修改启动类
package com.tg.servicezuul;
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;
@SpringBootApplication
@EnableEurekaClient//开启一个eureka的客户端
@EnableZuulProxy //开启zuulProxy
public class ServiceZuulApplication {
public static void main(String[] args) {
SpringApplication.run( ServiceZuulApplication.class, args );
}
}
#1.给这个应用服务起名字spring:
spring:
application:
name: server-zuul
server:
port: 8766
zuul:
routes:
api-a: #api-a 这个是自定义的 serviceId对应注册中心的服务 这里的配置解释:通过
#localhost:8766/api-a/**访问 交由 Eureka-RIBBON 去处理
#localhost:8766/api-b/**访问 交由 SERVICE-FEIGN 去处理
path: /api-a/**
serviceId: EUREKA-RIBBON
api-b:
path: /api-b/**
serviceId: SERVICE-FEIGN
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/eureka
启动服务端 客户端 启动 ribbon 和 feign
采用浏览器访问
借用大佬的api网段地址 大家有兴趣可以去看一下
自定义过滤
package com.tg.servicezuul;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
//不打上注解是扫描不到的
@Component
public class MyZuulFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogger(MyZuulFilter.class);
//返回值可以为 pre路由之前 post路由之后 error发送错误时候处理 route时候处理
//分别对应的class大家可以去看一下
//DebugFilter SendResponseFilter SendErrorFilter RibbonRoutingFilter
@Override
public String filterType() {
return "pre";
}
//过滤的顺序 可以理解 多个过滤器排序
@Override
public int filterOrder() {
return 0;
}
//false 是否过滤 true 永久过滤
@Override
public boolean shouldFilter() {
return true;
}
//执行的方法
@Override
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
Object accessToken = request.getParameter( "token" );
if (accessToken == null) {
ctx.setSendZuulResponse( false );
ctx.setResponseStatusCode( 401 );
try {
ctx.getResponse().getWriter().write( "token is empty" );
} catch (Exception e) {
}
return null;
}
return null;
}
}