序 本文主要研究一下AsyncHttpClient的SignatureCalculator SignatureCalculator org/asynchttpclient/SignatureCalculator.java SignatureCalculator定义了calculateAndAddSignature接口,它首先计算签名,然后添加到requestBuilder OAuthSignatureCalculator org/asynchttpclient SignatureCalculator接口,其calculateAndAddSignature方法使用了OAuthSignatureCalculatorInstance的sign方法 sign org/asynchttpclient constructAuthHeader计算headerValue,最后设置到requestBuilder的名为authorization的header executeSignatureCalculator org/asynchttpclient executeSignatureCalculator会执行signatureCalculator.calculateAndAddSignature(unsignedRequest, rb) build org/asynchttpclient
.*; Create a new AsyncHttpClient instance and make a request: AsyncHttpClient client = new AsyncHttpClient First, create an instance of AsyncHttpClient: AsyncHttpClient myClient = new AsyncHttpClient(); Now For example: AsyncHttpClient client = new AsyncHttpClient(); String[] allowedContentTypes = new String AsyncHttpClient client = new AsyncHttpClient(); client.setBasicAuth("username","password/token"); client.get client = new AsyncHttpClient(); client.setBasicAuth("username","password", new AuthScope("example.com
序 本文主要研究一下AsyncHttpClient的ListenableFuture ListenableFuture org/asynchttpclient/ListenableFuture.java java.util.concurrent.Future,它定义了done、abort、touch、addListener、toCompletableFuture方法 CompletedFailure org/asynchttpclient } } CompletedFailure实现了ListenableFuture接口,其cancel方法返回true、isDone返回true NettyResponseFuture org/asynchttpclient toCompletableFuture() { return future; } toCompletableFuture方法直接返回future newNettyResponseFuture org/asynchttpclient sendRequestWithCertainForceConnect则将NettyResponseFuture传递给sendRequestWithOpenChannel或者sendRequestWithNewChannel来发送请求 小结 AsyncHttpClient
序 本文主要研究一下AsyncHttpClient的ListenableFuture ListenableFuture org/asynchttpclient/ListenableFuture.java java.util.concurrent.Future,它定义了done、abort、touch、addListener、toCompletableFuture方法 CompletedFailure org/asynchttpclient } } CompletedFailure实现了ListenableFuture接口,其cancel方法返回true、isDone返回true NettyResponseFuture org/asynchttpclient toCompletableFuture() { return future; } toCompletableFuture方法直接返回future newNettyResponseFuture org/asynchttpclient sendRequestWithCertainForceConnect则将NettyResponseFuture传递给sendRequestWithOpenChannel或者sendRequestWithNewChannel来发送请求 小结 AsyncHttpClient
序 本文主要研究一下AsyncHttpClient的ChannelPool ChannelPool org/asynchttpclient/channel/ChannelPool.java public flushPartitions、getIdleChannelCountPerHost方法,它有两个实现类,分别是NoopChannelPool及DefaultChannelPool NoopChannelPool org/asynchttpclient isTtlExpired都算在内,然后挨个执行takeOwnership及close,再从channelId2Creation及partition中移除,最后再次调度一下IdleChannelDetector 小结 AsyncHttpClient
序本文主要研究一下AsyncHttpClient的SignatureCalculatorSignatureCalculatororg/asynchttpclient/SignatureCalculator.java SignatureCalculator定义了calculateAndAddSignature接口,它首先计算签名,然后添加到requestBuilderOAuthSignatureCalculatororg/asynchttpclient 实现了SignatureCalculator接口,其calculateAndAddSignature方法使用了OAuthSignatureCalculatorInstance的sign方法signorg/asynchttpclient constructAuthHeader计算headerValue,最后设置到requestBuilder的名为authorization的headerexecuteSignatureCalculatororg/asynchttpclient executeSignatureCalculator会执行signatureCalculator.calculateAndAddSignature(unsignedRequest, rb)buildorg/asynchttpclient
序本文主要研究一下AsyncHttpClient的RequestFilterRequestFilterorg/asynchttpclient/filter/RequestFilter.java/** * */public interface RequestFilter { /** * An {@link org.asynchttpclient.AsyncHttpClient} will invoke filter(FilterContext<T> ctx) throws FilterException;}RequestFilter定义了filter方法ThrottleRequestFilterorg/asynchttpclient /filter/ThrottleRequestFilter.java/** * A {@link org.asynchttpclient.filter.RequestFilter} throttles ReleasePermitOnComplete的wrap对原来的handler进行代理,在finally里头执行available.release()preProcessRequestorg/asynchttpclient
序本文主要研究一下AsyncHttpClient的TimeoutTimerTaskTimerTaskio/netty/util/TimerTask.java/** * A task which is executed boolean cancel();}Timeout接口定义了timer()、task()、isExpired()、isCancelled()、cancel()方法TimeoutTimerTaskorg/asynchttpclient TimerTask接口,它定义了expire方法,执行requestSender.abort;clean方法来重置done及nettyResponseFutureReadTimeoutTimerTaskorg/asynchttpclient 为true或者requestSender为closed则直接返回,对于nettyResponseFuture.isDone()也直接返回,其余的执行expire方法TimeoutsHolderorg/asynchttpclient 的构造器对于requestTimeoutInMs不为-1的会创建RequestTimeoutTimerTask,然后通过newTimeout进行调度scheduleRequestTimeoutorg/asynchttpclient
序 本文主要研究一下AsyncHttpClient的ConnectionSemaphore ConnectionSemaphore org/asynchttpclient/netty/channel/ConnectionSemaphore.java 、tryAcquire方法,它有两个实现类,分别是NonBlockingSemaphore、NonBlockingSemaphoreInfinite NonBlockingSemaphore org/asynchttpclient permits.compareAndSet(count, count - 1)成功则返回true,否则继续循环执行直到返回false或者true NonBlockingSemaphoreInfinite org/asynchttpclient } } NonBlockingSemaphoreInfinite表示无限的信号量,release为空操作,tryAcquire始终返回true NettyResponseFuture org/asynchttpclient releasePartitionKeyLock,它会调用connectionSemaphore.releaseChannelLock(partitionKey) NettyRequestSender org/asynchttpclient
序 本文主要研究一下AsyncHttpClient的IOExceptionFilter IOExceptionFilter org/asynchttpclient/filter/IOExceptionFilter.java occurs during an http transaction. */ public interface IOExceptionFilter { /** * An {@link org.asynchttpclient.AsyncHttpClient FilterException; } IOExceptionFilter接口定义了filter方法,在捕获到IOException的时候执行 ResumableIOExceptionFilter org/asynchttpclient /handler/resumable/ResumableIOExceptionFilter.java /** * Simple {@link org.asynchttpclient.filter.IOExceptionFilter } that replay the current {@link org.asynchttpclient.Request} using a {@link ResumableAsyncHandler}
序本文主要研究一下AsyncHttpClient的ChannelPoolChannelPoolorg/asynchttpclient/channel/ChannelPool.javapublic interface flushPartitions、getIdleChannelCountPerHost方法,它有两个实现类,分别是NoopChannelPool及DefaultChannelPoolNoopChannelPoolorg/asynchttpclient isTtlExpired都算在内,然后挨个执行takeOwnership及close,再从channelId2Creation及partition中移除,最后再次调度一下IdleChannelDetector小结AsyncHttpClient
序本文主要研究一下AsyncHttpClient的exceptionChannelClosedExceptionorg/asynchttpclient/exception/ChannelClosedException.javapublic super("Channel closed"); }}ChannelClosedException用于表示Channel closed的异常handleUnexpectedClosedChannelorg/asynchttpclient NettyRequestSender定义了handleUnexpectedClosedChannel方法,它会关闭或abort当前的channelPoolAlreadyClosedExceptionorg/asynchttpclient ("Pool is already closed"); }}PoolAlreadyClosedException用于表示连接池已经关闭的异常sendRequestWithNewChannelorg/asynchttpclient Remotely closed"); }}RemotelyClosedException用于表示Remotely closed的异常handleUnexpectedClosedChannelorg/asynchttpclient
序 本文主要研究一下AsyncHttpClient的KeepAliveStrategy KeepAliveStrategy org/asynchttpclient/channel/KeepAliveStrategy.java nettyResponse); } KeepAliveStrategy接口定义了keepAlive方法用于决定是否对该connection进行keep alive DefaultKeepAliveStrategy org/asynchttpclient connection: close的header,且http协议默认keep alive或者header包含了connection: keep-alive才返回true handleHttpResponse org/asynchttpclient KeepAliveStrategy的keepAlive来判断是否需要keep alive,然后写入到NettyResponseFuture中 exitAfterHandlingConnect org/asynchttpclient isReuseChannel() { return reuseChannel; } attachChannel这里维护了reuseChannel属性 getOpenChannel org/asynchttpclient
序本文主要研究一下AsyncHttpClient的KeepAliveStrategyKeepAliveStrategyorg/asynchttpclient/channel/KeepAliveStrategy.javapublic nettyResponse);}KeepAliveStrategy接口定义了keepAlive方法用于决定是否对该connection进行keep aliveDefaultKeepAliveStrategyorg/asynchttpclient connection: close的header,且http协议默认keep alive或者header包含了connection: keep-alive才返回truehandleHttpResponseorg/asynchttpclient 方法会通过KeepAliveStrategy的keepAlive来判断是否需要keep alive,然后写入到NettyResponseFuture中exitAfterHandlingConnectorg/asynchttpclient boolean isReuseChannel() { return reuseChannel; } attachChannel这里维护了reuseChannel属性getOpenChannelorg/asynchttpclient
序 本文主要研究一下AsyncHttpClient的默认配置 maven <dependency> <groupId>org.asynchttpclient</groupId * * @return the maximum number of connections an {@link AsyncHttpClient} can handle. */ int * * @return the maximum number of connections per host an {@link AsyncHttpClient} can handle. * * @return the maximum time in millisecond an {@link AsyncHttpClient} can stay idle. */ =AsyncHttpClient private String threadPoolName = defaultThreadPoolName(); // org.asynchttpclient.httpClientCodecMaxInitialLineLength
序本文主要研究一下AsyncHttpClient的ClientStatsClientStatsorg/asynchttpclient/ClientStats.java/** * A record class representing the state of an (@link org.asynchttpclient.AsyncHttpClient). getStatsPerHost、getTotalConnectionCount、getTotalActiveConnectionCount、getTotalIdleConnectionCount方法HostStatsorg/asynchttpclient , idleConnectionCount); }}HostStats定义了activeConnectionCount、idleConnectionCount属性getClientStatsorg/asynchttpclient totalConnectionsPerHost,从channelPool.getIdleChannelCountPerHost()获取idleConnectionCount,然后创建HostStats,最后返回ClientStats小结AsyncHttpClient
序 本文主要研究一下AsyncHttpClient的RequestFilter RequestFilter org/asynchttpclient/filter/RequestFilter.java / invoked before making an actual request. */ public interface RequestFilter { /** * An {@link org.asynchttpclient.AsyncHttpClient FilterContext<T> ctx) throws FilterException; } RequestFilter定义了filter方法 ThrottleRequestFilter org/asynchttpclient /filter/ThrottleRequestFilter.java /** * A {@link org.asynchttpclient.filter.RequestFilter} throttles , fc.getAsyncHandler()); } } executeRequest方法对于noRequestFilters为false会执行preProcessRequest 小结 AsyncHttpClient
序本文主要研究一下AsyncHttpClient的ConnectionSemaphoreConnectionSemaphoreorg/asynchttpclient/netty/channel/ConnectionSemaphore.java TooManyConnectionsPerHostException;releaseChannelLock则先释放全局空闲连接,再释放指定host的空闲连接NonBlockingSemaphoreLikeorg/asynchttpclient release、tryAcquire方法,它有两个实现类,分别是NonBlockingSemaphore、NonBlockingSemaphoreInfiniteNonBlockingSemaphoreorg/asynchttpclient permits.compareAndSet(count, count - 1)成功则返回true,否则继续循环执行直到返回false或者trueNonBlockingSemaphoreInfiniteorg/asynchttpclient releasePartitionKeyLock,它会调用connectionSemaphore.releaseChannelLock(partitionKey)NettyRequestSenderorg/asynchttpclient
序 本文主要研究一下AsyncHttpClient的exception ChannelClosedException org/asynchttpclient/exception/ChannelClosedException.java Channel closed"); } } ChannelClosedException用于表示Channel closed的异常 handleUnexpectedClosedChannel org/asynchttpclient NettyRequestSender定义了handleUnexpectedClosedChannel方法,它会关闭或abort当前的channel PoolAlreadyClosedException org/asynchttpclient is already closed"); } } PoolAlreadyClosedException用于表示连接池已经关闭的异常 sendRequestWithNewChannel org/asynchttpclient " + max); } } TooManyConnectionsException用于表示全局连接超过限制的异常 TooManyConnectionsPerHostException org/asynchttpclient
序 本文主要研究一下AsyncHttpClient的ClientStats ClientStats org/asynchttpclient/ClientStats.java /** * A record class representing the state of an (@link org.asynchttpclient.AsyncHttpClient). */ public class ClientStats getStatsPerHost、getTotalConnectionCount、getTotalActiveConnectionCount、getTotalIdleConnectionCount方法 HostStats org/asynchttpclient idleConnectionCount); } } HostStats定义了activeConnectionCount、idleConnectionCount属性 getClientStats org/asynchttpclient totalConnectionsPerHost,从channelPool.getIdleChannelCountPerHost()获取idleConnectionCount,然后创建HostStats,最后返回ClientStats 小结 AsyncHttpClient