我需要使用Datastax Java驱动程序查询Cassandra中的表之一。下面是我的代码,可以正常工作-
public class TestCassandra {
private Session session = null;
private Cluster cluster = null;
private static class ConnectionHolder {
static final TestCassandra connection = new TestCassandra();
}
public static TestCassandra getInstance() {
return ConnectionHolder.connection;
}
private TestCassandra() {
Builder builder = Cluster.builder();
builder.addContactPoints("127.0.0.1");
PoolingOptions opts = new PoolingOptions();
opts.setCoreConnectionsPerHost(HostDistance.LOCAL, opts.getCoreConnectionsPerHost(HostDistance.LOCAL));
cluster = builder.withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE).withPoolingOptions(opts)
.withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy("DC2")))
.withReconnectionPolicy(new ConstantReconnectionPolicy(100L))
.build();
session = cluster.connect();
}
private Set<String> getRandomUsers() {
Set<String> userList = new HashSet<String>();
for (int table = 0; table < 14; table++) {
String sql = "select * from testkeyspace.test_table_" + table + ";";
try {
SimpleStatement query = new SimpleStatement(sql);
query.setConsistencyLevel(ConsistencyLevel.QUORUM);
ResultSet res = session.execute(query);
Iterator<Row> rows = res.iterator();
while (rows.hasNext()) {
Row r = rows.next();
String user_id = r.getString("user_id");
userList.add(user_id);
}
} catch (Exception e) {
System.out.println("error= " + ExceptionUtils.getStackTrace(e));
}
}
return userList;
}
}
我在我的主应用程序中使用这样的上面的类-
TestCassandra.getInstance().getRandomUsers();
有什么办法,我可以使用PreparedStatement
的getRandomUsers
高效率?我想我需要确保PreparedStatement
只创建一次而不是多次创建。在我当前的体系结构中,最佳的设计是什么?如何使用它?
您可以创建所需语句的缓存(这是一个非常基本的示例,可以使您有所了解)。让我们从创建将用作缓存的类开始。
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();
}
}
然后将一个实例添加到您的单例中:
public class TestCassandra {
private Session session = null;
private Cluster cluster = null;
private StatementCache psCache = new StatementCache();
// rest of class...
最后使用函数中的缓存:
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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句