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に精通していません。
ありがとう!