Spring Data Cassandra和PreparedStatementCache

4
我不明白如何使用Spring Data Cassandra实现非常简单的目标。我想要多次执行"INSERT"语句,每次使用不同的参数值。当前我没有映射到域类,所以我使用Spring Data提供的接口。 但是当我仅使用execute(String CQL, Object... args)时,Cassandra驱动程序会抱怨"重新准备已经准备好的查询通常是一种反模式,很可能会影响性能。考虑仅准备一次该语句"。因为Spring Data使用SimplePreparedStatementCreator。但我找不到任何方法告诉Spring Data使用CachedPreparedStatementCreator代替。我看到的只有一个execute(PreparedStatementCreator psc)方法,它不允许我提供参数值。 那么,有没有办法告诉Spring Data使用正确的语句缓存或实现类似于execute(PreparedStatementCreator, Object...)的功能呢?
1个回答

5

CqlTemplate提供了回调和自定义钩子,允许根据您的应用程序需求来定制其功能。

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

Spring Data Cassandra的包core.cql.support提供了对CachedPreparedStatementCreatorPreparedStatementCache的支持,您可以使用它们来实现目的。

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

public class MyCachedCqlTemplate extends CqlTemplate {

    PreparedStatementCache cache = MapPreparedStatementCache.create();

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

}

Cassandra驱动程序4.0+不会记录警告,因为它说 - “会话具有内置缓存,可以安全地准备相同的字符串两次。” - Suyash Soni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接