📅  最后修改于: 2021-01-07 03:46:22             🧑  作者: Mango
在上一节中,我们讨论了在API网关中实现的常见功能。我们已经准备好充当API网关的Zuul服务器。
在本节中,我们将在Zuul API网关中实现日志记录功能。
让我们在Zuul API网关中实现日志记录。
步骤1:在netflix-zuul-api-gateway-server项目中,创建一个名称为ZuulLoggingFilter的新类文件。
步骤2:添加注释@Componenet 。
步骤3:扩展ZuulFilter类。 ZuulFilter类中有一些抽象方法。这些抽象方法必须在ZuulLoggingFilter类中实现。
步骤4:将光标移到ZuulLoggingFilter类上。它提出了两个快速修复方法,如下图所示。单击添加未实现的方法。我们获得ZuulFilter类的所有抽象方法的默认实现。
ZuulFilter类具有下面列出的四个抽象方法:
步骤5:创建Logger类对象,并调用getLogger()方法来创建记录器。
private Logger logger=LoggerFactory.getLogger(this.getClass());
切记:导入org.slf4j软件包的Logger类。
步骤6:在run()方法中实现逻辑。
public Object run() throws ZuulException
{
//getting the current HTTP request that is to be handle
HttpServletRequest request=RequestContext.getCurrentContext().getRequest();
//printing the detail of the request
logger.info("request -> {} request uri-> {}", request, request.getRequestURI());
return null;
}
ZuulLoggingFilter.java
package com.javatpoint.microservices.netflixzuulapigatewayserver;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
@Component
public class ZuulLoggingFilter extends ZuulFilter
{
//creating Logger object
private Logger logger=LoggerFactory.getLogger(this.getClass());
@Override
public booleanshouldFilter()
{
return true; //executing filter for every request
}
//log the content of the request
@Override
public Object run() throws ZuulException
{
//getting the current HTTP request that is to be handle
HttpServletRequest request=RequestContext.getCurrentContext().getRequest();
//prints the detail of the requestin the log
logger.info("request -> {} request uri-> {}", request, request.getRequestURI());
return null;
}
@Override
public String filterType()
{
return "pre"; //intercept all the request before execution
}
@Override
public intfilterOrder()
{
return 1; //setting filter order to 1
}
}
在下一步中,我们将看到如何使用Zuul拦截请求。