我在网络服务服务器上,我有内部连接的对象 初始化此连接需要很长时间,所以我的想法是使用对象池重用不同请求之间的连接。
对象连接到每个用户,所以我更喜欢使用用户名作为密钥,连接作为值。但我不希望永远打开这种联系。也许过了一段时间,如果用户不再启动请求,它应该被销毁。
我考虑使用apache object pool,但我没有看到那里的到期(如果我错了,请纠正我)
ehcache向我提供有关驱逐和过期的notifications,但是在超时结束后才触发,只有在再次触摸缓存的对象时才会触发。
有人知道可以为我做这项工作的lib吗?
答案 0 :(得分:3)
来自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将调用此方法。
答案 1 :(得分:3)
受到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);
答案 2 :(得分:0)
最近添加了新的通用界面: