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

StackOverflow https://stackoverflow.com/questions/22322510

Question

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

Était-ce utile?

La solution

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.

Autres conseils

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);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top