use of com.datastax.driver.core.WriteType in project java-driver by datastax.
the class DowngradingRetry method write.
/**
* Inserts data, retrying if necessary with a downgraded CL.
*
* @param cl the consistency level to apply.
* @param retryCount the current retry count.
* @throws DriverException if the current consistency level cannot be downgraded.
*/
private void write(ConsistencyLevel cl, int retryCount) {
System.out.printf("Writing at %s (retry count: %d)%n", cl, retryCount);
BatchStatement batch = new BatchStatement(UNLOGGED);
batch.add(new SimpleStatement("INSERT INTO downgrading.sensor_data " + "(sensor_id, date, timestamp, value) " + "VALUES (" + "756716f7-2e54-4715-9f00-91dcbea6cf50," + "'2018-02-26'," + "'2018-02-26T13:53:46.345+01:00'," + "2.34)"));
batch.add(new SimpleStatement("INSERT INTO downgrading.sensor_data " + "(sensor_id, date, timestamp, value) " + "VALUES (" + "756716f7-2e54-4715-9f00-91dcbea6cf50," + "'2018-02-26'," + "'2018-02-26T13:54:27.488+01:00'," + "2.47)"));
batch.add(new SimpleStatement("INSERT INTO downgrading.sensor_data " + "(sensor_id, date, timestamp, value) " + "VALUES (" + "756716f7-2e54-4715-9f00-91dcbea6cf50," + "'2018-02-26'," + "'2018-02-26T13:56:33.739+01:00'," + "2.52)"));
batch.setConsistencyLevel(cl);
try {
session.execute(batch);
System.out.println("Write succeeded at " + cl);
} catch (DriverException e) {
if (retryCount == maxRetries) {
throw e;
}
e = unwrapNoHostAvailableException(e);
System.out.println("Write failed: " + e);
if (e instanceof UnavailableException) {
// With an UnavailableException, we know that the write wasn't even attempted.
// Downgrade to the number of replicas reported alive and retry.
int aliveReplicas = ((UnavailableException) e).getAliveReplicas();
ConsistencyLevel downgraded = downgrade(cl, aliveReplicas, e);
write(downgraded, retryCount + 1);
} else if (e instanceof WriteTimeoutException) {
WriteType writeType = ((WriteTimeoutException) e).getWriteType();
int acknowledgements = ((WriteTimeoutException) e).getReceivedAcknowledgements();
switch(writeType) {
case SIMPLE:
case BATCH:
// a retry would ever succeed.
if (acknowledgements == 0) {
throw e;
}
break;
case UNLOGGED_BATCH:
// For unlogged batches, the write might have been persisted only partially,
// so we can't simply ignore the exception: instead, we need to retry with
// consistency level equal to the number of acknowledged writes.
ConsistencyLevel downgraded = downgrade(cl, acknowledgements, e);
write(downgraded, retryCount + 1);
break;
case BATCH_LOG:
// Rare edge case: the peers that were chosen by the coordinator
// to receive the distributed batch log failed to respond.
// Simply retry with same consistency level.
write(cl, retryCount + 1);
break;
default:
// Other write types are uncommon and should not be retried.
throw e;
}
} else {
// Unexpected error: just retry with same consistency level
// and hope to talk to a healthier coordinator.
write(cl, retryCount + 1);
}
}
}
Aggregations