Is there a good way to check if Datastax Session.executeAsync () raised an exception?

I am trying to speed up our code by calling session.executeAsync() instead of session.execute() to write a DB.

We have cases when the connection to the database may not be available, currently the previous execute() throws an exception when the connection is lost (there are not enough hosts in the cluster). We can catch these exceptions and try again or save the data in another place, etc.

With executeAsync() , it doesn't seem like any way to fulfill this use case is that you need to access the object of the returned ResultSetFuture object to check the result, which will lead to the defeat of the goal of using executeAsync() in the first place ...

Is there a way to add a listener (or something similar) anywhere in the call to executeAsync (), which will asynchronously notify any other code that failed to write to the database failed?

Is this appropriate? Datastax 1.0.2 Java 1.7.40

+8
java datastax-java-driver datastax
source share
2 answers

You can try something like this, since 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.

+14
source share

You can pass a callback to a method to decide on an exception. If you need ResultSetFuture , you can 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 name it like this:

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

If you need to know what an exception is, also add an exception parameter:

 interface ResultSetFutureHandler { void handle(ResultSetFuture rs, RuntimeException e); } 
+1
source share

All Articles