Is there a good way to check whether a Datastax Session.executeAsync() has thrown an exception?

点点圈 提交于 2019-12-05 21:15:30

问题


I'm trying to speed up our code by calling session.executeAsync() instead of session.execute() for DB writes.

We have use cases where the DB connection might be down, currently the previous execute() throws an exception when the connection is lost (no hosts reachable in the cluster). We can catch these exceptions and retry or save the data somewhere else etc...

With executeAsync(), it doesn't look like there's any way to fulfill this use case - the returned ResultSetFuture object needs to be accessed to check the result, which would defeat the purpose of using the executeAsync() in the first place...

Is there any way to add a listener (or something similar) anywhere for the executeAsync() call that will asynchronously notify some other code that a DB write has failed?

Is this pertinent? Datastax 1.0.2 Java 1.7.40


回答1:


You could try something like this since the ResultSetFuture implements ListenableFuture from the Guava library:

    ResultSetFuture resultSetFuture = session.executeAsync("SELECT * FROM test.t;");
    Futures.addCallback(resultSetFuture, new FutureCallback<ResultSet>() {
        @Override
        public void onSuccess(@Nullable com.datastax.driver.core.ResultSet resultSet) {
            // do nothing
        }

        @Override
        public void onFailure(Throwable throwable) {
            System.out.printf("Failed with: %s\n", throwable);
        }
    });

This approach will not block your application.




回答2:


You could pass a callback to the method to take action on exception. If you need the ResultSetFuture, you could try something like this:

interface ResultSetFutureHandler {
    void handle(ResultSetFuture rs);
}

public void catchException(ResultSetFutureHandler handler) {
    ResultSetFuture resultSet = null;
    try {
        resultSet = getSession().executeAsync(query);
        for (Row row : results.getUninterruptibly()) {
            // do something
        }
    } catch (RuntimeException e) {
        handler.handle(resultSet); // resultSet may or may not be null
    }
}

Then call it like this:

catchException(new ResultSetFutureHandler() {
    void handle(ResultSetFuture resultSet) {
        // do something with the ResultSetFuture
    }
});

If you need to know what the exception was, add an exception parameter too:

interface ResultSetFutureHandler {
    void handle(ResultSetFuture rs, RuntimeException e);
}


来源:https://stackoverflow.com/questions/22322510/is-there-a-good-way-to-check-whether-a-datastax-session-executeasync-has-throw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!