I am using Spring Data with Cassandra and would like to be as resilient as possible in terms of error prevention and handling. Currently, we wrap our our com.datastax.cassandra.Session by implementing the interface with our own implementation that creates a nested instance (effectively a proxy), like so:
private class CassandraSessionProxy implements Session {
private Session cassandraSession;
private Session cassandraSession() {
if (cassandraSession != null) {
return cassandraSession;
} else {
synchronized (this) {
try {
cassandraSession = createCassandraSession();
return cassandraSession;
} catch (Exception e) {
LOGGER.error("An error happened but after Spring's container started", e);
}
}
}
}
// implement Session methods, proxying to cassandraSession field
@Override
public void close() {
cassandraSession().close();
}
}
All proxying methods in our Session implementation access the cassandraSession field through a synchronized block that checks if it exists and if not creates the connection, catching any exceptions outside of the scope of Spring's startup.
Curious if there is a slicker method for achieving this. An overlooked feature of datastax's native driver or spring-data would be ideal.
Much obliged :)
Session is an interface. Why don't you simply construct a SessionBuilder that constructs a Session instance? You can then have it return a basic Cassandra Session until you need something else.
The above solution is usually best practice when it comes to OO design.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With