为了伙计们少走一点弯路,菜鸡的简单方法,利用Webfilter接口去写访问日志
百度AOP中获取Request和Response对象从来都是null,不要疑惑为啥,因为你跟别人不一样,别人都是一个web一个线程,你用reactor是异步的能从线程池拉到一个变量时不可能的,并且响应式编程,一个消息只能用一次,所以只能你自己在拉之前手动备份,可以参考https://blog.csdn.net/weixin_30591551/article/details/99855125。手动搞一个RequestContextListener都不行,异步就是异步,你不配拥有@autowired。
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
查了半天资料都拿不来request,debug一调都在,一到controller就没了。麻了一周,换个思路,搞过滤器去,用ServerWebExchange.getRequest()取,取出来先用为敬,用完再chain。思路时找到了一位大佬的博客有的想法,https://qcsdn.com/article/242147.html
上代码ReactiveRequestContextFilter.class
import reactor.core.publisher.Mono;
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class ReactiveRequestContextFilter implements WebFilter {
private final Logger logger = LoggerFactory.getLogger(ReactiveRequestContextFilter.class);
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
// 记录下请求内容
logger.info("################ Request URL : " + request.getURI().toString());
logger.info("################ Http Method : " + request.getMethod());
logger.info("################ Query Params : " + request.getQueryParams());
logger.info("################ Remote Address : " + request.getRemoteAddress());
logger.info("################ ID : " + request.getId());
logger.info("################ Header : " + request.getHeaders());
return chain.filter(exchange);
}
}
好了,request的内容算是都搞出来了。还想搞controller的具体方法的你可以用AOP了,参考https://www.cnblogs.com/wangshen31/p/9379197.html就行,已经不用再记录request了,就记录一下controller行为就行
logger.info("######################################## THE ARGS OF THE CONTROLLER : " + Arrays.toString(joinPoint.getArgs()));
// 下面这个getSignature().getDeclaringTypeName()是获取包+类名的
// 然后后面的joinPoint.getSignature.getName()获取了方法名
logger.info("######################################## CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
+ joinPoint.getSignature().getName());