【发布时间】:2016-01-28 18:35:32
【问题描述】:
我正在尝试找出是否可以创建 Java 动态代理来自动关闭 Autocloseable 资源,而不必记住使用 try-resources 块嵌入此类资源。
例如,我有一个 JedisPool,它有一个 getResource 方法,可以像这样使用:
try(Jedis jedis = jedisPool.getResource() {
// use jedis client
}
现在我做了类似的事情:
class JedisProxy implements InvocationHandler {
private final JedisPool pool;
public JedisProxy(JedisPool pool) {
this.pool = pool;
}
public static JedisCommands newInstance(Pool<Jedis> pool) {
return (JedisCommands) java.lang.reflect.Proxy.newProxyInstance(
JedisCommands.class.getClassLoader(),
new Class[] { JedisCommands.class },
new JedisProxy(pool));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try (Jedis client = pool.getResource()) {
return method.invoke(client, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw e;
}
}
}
现在,每次我在 Jedis (JedisCommands) 上调用方法时,此方法都会传递给代理,代理会从池中获取新客户端,执行方法并将此资源返回到池中。
它工作正常,但是当我想在客户端上执行多个方法时,每个方法的资源都从池中取出并再次返回(这可能很耗时)。你知道如何改进吗?
【问题讨论】:
标签: java proxy java-8 jedis autocloseable