5

私は Web サービス サーバーを使用しており、内部接続を持つオブジェクトがあります。
この接続の初期化には非常に時間がかかるため、オブジェクト プールを使用してさまざまな要求間で接続を再利用することを考えました。

オブジェクトは各ユーザーに接続されているため、ユーザー名をキーとして使用し、接続を値として使用することを好みます。しかし、私は接続を永遠に開いておきたくありません。ユーザーがリクエストを開始しない場合、しばらくしてから破棄する必要があります。

Apache オブジェクト プールを使用することを考えましたが、そこに有効期限が表示されませんでした (間違っていたら訂正してください)。

ehcache は、エビクションと有効期限に関する通知を提供しますが、キャッシュされたオブジェクトが再び触れられた場合にのみ、タイムアウトが終了した後にトリガーされません。

誰かが私のためにこの仕事をすることができるライブラリを知っていますか?

4

3 に答える 3

4

assylia のアイデアに触発されて、ここで私のソリューションにグアバを使用しました

final RemovalListener<Integer, Connection> removalListener = new RemovalListener<Integer, Connection>() {
    @Override
    public void onRemoval(final RemovalNotification<Integer, Connection> notification) {
        disconnect(notification.getValue());
    }
};

Cache<Integer, Connection> cache = CacheBuilder.newBuilder().maximumSize(20)
        .expireAfterAccess(30, TimeUnit.SECONDS)
        .removalListener(removalListener).build();
final ScheduledExecutorService cacheMaintanance = Executors.newSingleThreadScheduledExecutor();
cacheMaintanance.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        cache.cleanUp();
    }
}, 10, 10, TimeUnit.SECONDS);
于 2013-07-16T14:44:55.723 に答える
4

http://commons.apache.org/proper/commons-pool/api-1.6/org/apache/commons/pool/impl/GenericObjectPool.htmlをご覧ください。

javadoc から:

Optionally, one may configure the pool to examine and possibly evict objects
as they sit idle in the pool and to ensure that a minimum number of idle
objects are available. This is performed by an "idle object eviction" thread,
which runs asynchronously. Caution should be used when configuring this
optional feature. Eviction runs contend with client threads for access to
objects in the pool, so if they run too frequently performance issues may
result.

.... 

minEvictableIdleTimeMillis specifies the minimum amount of time that 
an object may sit idle in the pool before it is eligible for eviction
due to idle time. When non-positive, no object will be dropped from 
the pool due to idle time alone. This setting has no effect unless
timeBetweenEvictionRunsMillis > 0. The default setting for this 
parameter is 30 minutes.

PoolableObjectFactory接続を作成する を実装し、接続を閉じるメソッドも実装しますPoolableObjectFactory.destroyObject(T object)。このメソッドは、オブジェクトが削除されたときに GenericObejctPool によって呼び出されます。

于 2013-07-16T13:59:11.940 に答える
0

最近、これに新しい汎用インターフェースが追加されました。

http://commons.apache.org/proper/commons-pool/

于 2014-07-08T19:46:59.610 に答える