【发布时间】:2015-04-30 19:41:25
【问题描述】:
我需要使用 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();
有什么方法可以有效地在getRandomUsers 中使用PreparedStatement?我想我需要确保我只创建一次PreparedStatement,而不是多次创建它。在我当前的架构中,最好的设计是什么?我该如何使用它?
【问题讨论】:
标签: java cassandra prepared-statement datastax-java-driver