【问题标题】:Catching memcache exception in java在java中捕获memcache异常
【发布时间】:2016-05-09 13:14:41
【问题描述】:

我正在使用 spymemcached-2.8.4.jar 和 jdk.1.7。

这是我的代码

try {

     MemcachedClient client = new MemcachedClient(...);

     client.set('name', 1000, 'some_name');

}catch(Exception ex){
     System.out.println("Exception occurred");
     System.out.println(ex.getMessage());
     ex.printStackTrace();

     logExceptionInDB(ex);
}

在我的扫描中,我的 memcached 机器没有运行,所以它在控制台中打印以下异常,

java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:735)
    at net.spy.memcached.MemcachedConnection.handleIO(MemcachedConnection.java:369)
    at net.spy.memcached.MemcachedConnection.handleIO(MemcachedConnection.java:242)
    at net.spy.memcached.MemcachedConnection.run(MemcachedConnection.java:836)

但我想抓住这个例外,把它写到数据库中。如何捕捉这个异常?

【问题讨论】:

  • 正在捕捉到异常......只需按照你想要的方式处理它。
  • 您的控制台是否打印 - “发生异常”?如果是这样,那么您已经捕获了异常,请使用 JDBC 连接器连接到 DB 并保留错误消息(ex.getMessage())。
  • 实际上没有,实际上它是一个异步调用,使用 FutureTask 实现。在被调用的线程内部,它正在打印异常,没有抛出任何东西。

标签: java memcached spymemcached


【解决方案1】:

你无法捕捉到帖子中提到的异常,因为它已经被spymemcached自己捕捉到了,你只能看到日志,MemcachedConnection.java中的相关代码是:

catch (ConnectException var5) {
            this.getLogger().info("Reconnecting due to failure to connect to %s", new Object[]{node, var5});
            this.queueReconnect(node);
        }

之后它会尝试重新连接,因此请确保您的配置正确。
实际上,您可以捕获set方法产生的异常:

    OperationFuture<Boolean> future = client.set("name", 1000, "some_name");
    Boolean result = future.get(50, TimeUnit.MILLISECONDS);

假设你一次操作的超时时间是50毫秒,超时后你会得到CheckedOperationTimeoutException

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-02
    • 2018-11-05
    • 2017-12-27
    • 2021-10-14
    • 2013-12-01
    • 1970-01-01
    • 2016-03-10
    • 2010-11-25
    相关资源
    最近更新 更多