How to use prepared statement efficiently using datastax java driver in Cassandra?
You can create a cache (this is a fairly basic example to give you an idea) of the statements you need. Lets start by creating the class that will be used as a cache.
private class StatementCache {
Map<String, PreparedStatement> statementCache = new HashMap<>();
public BoundStatement getStatement(String cql) {
PreparedStatement ps = statementCache.get(cql);
// no statement cached, create one and cache it now.
if (ps == null) {
ps = session.prepare(cql);
statementCache.put(cql, ps);
}
return ps.bind();
}
}
Then add an instance to your singleton:
public class TestCassandra {
private Session session = null;
private Cluster cluster = null;
private StatementCache psCache = new StatementCache();
// rest of class...
And finally use the cache from your function:
private Set<String> getRandomUsers(String cql) {
// lots of code.
try {
SimpleStatement query = new SimpleStatement(cql);
query.setConsistencyLevel(ConsistencyLevel.QUORUM);
// abstract the handling of the cache to it's own class.
// this will need some work to make sure it's thread safe
// as currently it's not.
ResultSet res = session.execute(psCache.getStatement(cql));