我为Jedis创建了一个代理类,然后它可以将资源返回到池并自动标记损坏的资源。
public class JedisProxy implements InvocationHandler {
private final JedisPool jedisPool;
public JedisProxy(JedisPool pool) {
this.jedisPool = pool;
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result;
Jedis jedis = obtainJedis();
try {
result = m.invoke(jedis, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new JedisException("Unexpected proxy invocation exception: " + e.getMessage(), e);
} finally {
returnJedis(jedis);
}
return result;
}
private Jedis obtainJedis() {
Jedis jedis;
jedis = jedisPool.getResource();
return jedis;
}
private void returnJedis(Jedis jedis) {
try {
if (jedis.isConnected()) {
jedis.ping();
jedisPool.returnResource(jedis);
} else {
jedisPool.returnBrokenResource(jedis);
}
} catch (JedisException e) {
jedisPool.returnBrokenResource(jedis);
}
}
}
然后使用:
JedisPool p = new JedisPool("10.32.16.19", 6379);
JedisCommands jc = (JedisCommands) Proxy.newProxyInstance(Jedis.class.getClassLoader(), Jedis.class.getInterfaces(), new JedisProxy(pool));
我知道JedisPool是线程安全的。
但是“jc”对象线程是否安全? Proxy.newProxyInstance()线程的代理对象是否安全?
我查看了Proxy的源代码,代理对象是由JVM创建的,我不熟悉JVM。
谢谢!
答案 0 :(得分:0)
Proxy.newProxyInstance()线程的代理对象是否安全?
我不知道问题可能会如何发生。除了InvocationHandler之外,它没有任何状态,并且它是不可变的。问题是,您的InvocationHandler线程安全吗?