一.什么是zuul网关
zuul 是netflix开源的一个API Gateway 服务器,Zuul 相当于是设备和 Netflix 流应用的 Web 网站后端所有请求的前门。Zuul 可以适当的对多个 Amazon Auto Scaling Groups 进行路由请求。
按我的理解,他就是一系列的filters,web应用
zuul网关的作用
Zuul 包含多个组件:
- zuul-core
- zuul-simple-webapp
- zuul-netflix
- zuul-netflix-webapp
Zuul提供了动态路由、弹性负载、监控和安全等功能,对接口请求进行鉴权、登录判断等操作.
代码简单实现
1.创建项目
2.依赖包
<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>
3.自定义路由规则
zuul:
# 自定义路由
routes:
order-service: /gateway/order/**
product-service: /gateway/product/**
# 过滤路由
ignored-services: /*-service/**
# 设置 Http请求头过滤 为空
sensitive-headers:
4 .访问接口
http://localhost:9000/gateway/order/api/v1/order/save?userId=123&productId=1
http://localhost:网关端口/网关配置的目标服务的路由/**
5.创建filter类-loginFilter
/**
* @description: 过滤器
* @author: ※狗尾巴草
* @date: 2020-10-16 21:54
**/
@Component
public class loginFilter extends ZuulFilter {
/**
* @description: 过滤类型
* @params:
* @author: 狗尾巴草
* @time:
*/
@Override
public String filterType() {
return PRE_TYPE;
}
/**
* @description: 过滤器的顺序,越小越先执行
* @params:
* @author: 狗尾巴草
* @time:
*/
@Override
public int filterOrder() {
return 4;
}
/**
* @description: 拦截是否生效
* @params:
* @author: 狗尾巴草
* @time:
*/
@Override
public boolean shouldFilter() {
HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
String regEx = ".*/gateway/order/.*";
Pattern pattern = Pattern.compile(regEx,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(request.getRequestURI());
if(matcher.find()){ //被拦截
return true;
}
return false;
}
/**
* @description: 业务逻辑
* @params:
* @author: 狗尾巴草
* @time:
*/
@Override
public Object run() throws ZuulException {
System.out.println("拦截了");
return null;
}
}
6.访问接口
http://localhost:9000/gateway/order/api/v1/order/save?userId=123&productId=1&token=123
7.添加返回JSON数据
修改拦截的业务逻辑方法
/**
* @description: 业务逻辑
* @params:
* @author: 狗尾巴草
* @time:
*/
@Override
public Object run() throws ZuulException {
System.out.println("拦截了");
RequestContext requestContext= RequestContext.getCurrentContext();
HttpServletRequest request = requestContext.getRequest();
requestContext.getResponse().setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); //设置编码
requestContext.getResponse().setCharacterEncoding("UTF-8");
String token = request.getHeader("token");
if(StringUtils.isBlank(token)){
token=request.getParameter("token");
}
JSONObject object = new JSONObject();
//判断token有效性
if(StringUtils.isBlank(token)){
object.put("status","401");
requestContext.setSendZuulResponse(false); // 不再向下执行
requestContext.setResponseBody(object.toString());
requestContext.setResponseStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); //设置http状态码
}
return null;
}
写的太随意,粗制烂叶的,有错误地地方还望路过的老铁指出,谢谢
最后附上项目地址:https://github.com/xt962464/Eureka_demo