首页 > 解决方案 > Spring Data Cassandra 和 PreparedStatementCache

问题描述

我不明白如何使用 Spring Data Cassandra 实现非常简单的目标。

我想使用不同的参数值多次执行“INSERT”语句。我目前没有映射域类,所以我使用CqlOperationsSpring Data 提供的接口。

当我刚刚使用execute(String cql, Object... args)时,Cassandra 驱动程序抱怨“重新准备已经准备好的查询通常是一种反模式,可能会影响性能。考虑只准备一次语句”。因为 Spring Data 使用SimplePreparedStatementCreator. 但是我看不到任何方法可以告诉 Spring Data 使用它CachedPreparedStatementCreator。我所看到的只是execute(PreparedStatementCreator psc)不允许我提供参数值的方法。

那么,有没有办法告诉 Spring Data 使用正确的语句缓存或实现类似的东西execute(PreparedStatementCreator, Object...)

标签: javaspringcassandraspring-dataspring-data-cassandra

解决方案


CqlTemplate公开回调和自定义钩子,允许根据应用程序的需要定制其某些功能。

CqlTemplate确实故意没有缓存,因为缓存会导致时间与空间的考虑。Spring Data Cassandra 无法做出决定,因为我们无法假设应用程序通常需要什么。

Spring Data Cassandra 的包core.cql.support附带了对CachedPreparedStatementCreator和 a 的支持PreparedStatementCache,您可以将其用于该目的。

子类化CqlTemplate并覆盖其newPreparedStatementCreator(…)方法以指定PreparedStatementCreator使用哪个。以下示例显示了具有无限保留的缓存示例:

public class MyCachedCqlTemplate extends CqlTemplate {

    PreparedStatementCache cache = MapPreparedStatementCache.create();

    @Override
    protected PreparedStatementCreator newPreparedStatementCreator(String cql) {
        return CachedPreparedStatementCreator.of(cache, cql);
    }

}

推荐阅读