SpringSecurity是spring家族中的一份子,关于使用方式我们不多说,我们看下其执行源码路径如何,介绍依赖于注解的配置。
因为我们的项目中采用了Spring5的Reactor响应式框架,它底层是基于netty的网络编程。
所以程序入口是在NioEventLoop的run方法中:如下:
try {
processSelectedKeys();
}
通过processSelectedKeys查找程序中有没有可读或者可写的请求。后面会进入NioEventLoop的processSelectedKey(SelectionKey k, AbstractNioChannel ch)方法中,查看是否与可读或者可写,然后执行相应操作,如下:
if ((readyOps & SelectionKey.OP_WRITE) != 0) {
// Call forceFlush which will also take care of clear the OP_WRITE once there is nothing left to write
ch.unsafe().forceFlush();
}
// Also check for readOps of 0 to workaround possible JDK bug which may otherwise lead
// to a spin loop
if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) {
unsafe.read();
}
因为我们一个请求过来是读请求,所以进入unsafe.read()方法,去通道中去读取信息,然后进入了HttpServerHandler类的channelRead方法中.
然后调用ChannnelOptions类的applyHandler方法,映射Request,Response进行业务处理,如下:
protected final void applyHandler() {
// channel.pipeline()
// .fireUserEventTriggered(NettyPipeline.handlerStartedEvent());
if (log.isDebugEnabled()) {
log.debug("[{}] {} handler is being applied: {}", formatName(), channel
(), handler);
}
Mono.fromDirect(handler.apply((INBOUND) this, (OUTBOUND) this))
.subscribe(this);
}
看到这段代码很多人会很疑惑,this是HttpServerOptions,这个类强转成了INBOUND和OUTBOUND两种类型,这是为什么,我们来看下HttpServerOptions类型的结构图:
可以看到HttpServerOperations类型实现了HttpServerResponse和HtteServerRequest两种类型。
接着向下看,因为选择的handler的类型为:HttpWebHandlerAdapter,后面会执行其handle()方法,在这个hande方法中继续深入,最后进入FilteringWebHandler的handle方法开始调用过滤器链如下:
@Override
public Mono<Void> handle(ServerWebExchange exchange) {
return this.filters.length != 0 ?
new DefaultWebFilterChain(getDelegate(), this.filters).filter(exchange) :
super.handle(exchange);
}