Cassandra PreparedStatement应该在singleton类中准备一次,然后在DAO实现中引用

Cassandra PreparedStatement应该在singleton类中准备一次,然后在DAO实现中引用,cassandra,singleton,prepared-statement,Cassandra,Singleton,Prepared Statement,在每次调用中都会创建PreparedStatement,因此负载会影响性能。 因此,我需要确保PreparedStatement应该在singleton类中准备一次并再次重用。 如何做到这一点?有人能给出一个示例代码吗?在最简单的情况下,它可能是这样的: 公共类PrepStatementCache{ 私有静态ConcurrentHashMap缓存=新ConcurrentHashMap(); 静态PreparedStatement getStatement(会话,最终字符串查询){ 返回cache

在每次调用中都会创建PreparedStatement,因此负载会影响性能。 因此,我需要确保PreparedStatement应该在singleton类中准备一次并再次重用。
如何做到这一点?有人能给出一个示例代码吗?

在最简单的情况下,它可能是这样的:

公共类PrepStatementCache{
私有静态ConcurrentHashMap缓存=新ConcurrentHashMap();
静态PreparedStatement getStatement(会话,最终字符串查询){
返回cache.computeFabSent(查询,q->session.prepare(查询));
}
}
但是,由于在计算过程中可能会阻塞映射,因此最好实现函数
getStatement
,如下所示:

static PreparedStatement getStatement(会话会话,最终字符串查询){
PreparedStatement PreparedStatement=cache.get(查询);
if(preparedStatement==null){
preparedStatement=session.prepare(查询);
if(preparedStatement!=null){
PreparedStatement p2=cache.putIfAbsent(查询,PreparedStatement);
preparedStatement=p2==null?preparedStatement:p2;
}
}
返回已准备好的报表;
}

但是要考虑到,对于Java驱动程序4,这是自动完成的,因此如果您正在启动新项目,那么最好使用它,因为它包含更多的功能。

我们不必编写私有构造函数使其成为单例它是更多的实现部分-即使您创建了一个对象-它也不会让事情变得更糟