使用Cassandra Prepared语句使用Cassandra Operations Spring Boot

时间:2017-11-04 03:46:02

标签: java spring spring-boot cassandra

我需要使用Cassandra操作界面和会话准备Statement /而不是Query Builder 任何示例或最近的文档。对于使用java的Cassandra

3 个答案:

答案 0 :(得分:1)

请参阅this以查看在使用java datastax驱动程序时如何使用准备好的语句。

但是我建议将所有准备好的文件存储在缓存中(例如地图),而应用程序初始化并在每次requreid时通过创建boundstatment来重用它。 例如:

//Here Key is query string 
 private static final Map<String, PreparedStatement> psMap = new ConcurrentHashMap<String, PreparedStatement>();

 //Will be invoked @ initialization 
 public void init(Session session) {
        this.session = session;
        for (QuerySetEnum cql : QuerySetEnum.values()) {

            psMap.put(cql.getStatement(), session.prepare(cql.getStatement()));
        }


        //In Dao Impl class 
        //Get bounded statment + execute by passing the value
         @Override
    public void decreaseStats(long size, long count, String mapname,
            int bucketId) {
        BoundStatement boundStatement = getBoundStatement(QuerySetEnum.DECREASE_STATS);
        metaTemplate.execute(boundStatement.bind(size, count, mapname,
                bucketId));

    }
//Below is the implementation how to get BoundStatement out to prepared statment cache
    private BoundStatement getBoundStatement(QuerySetEnum query) {
        PreparedStatement preparedStatement = queryPool
                .getPreparedStatement(query);
        BoundStatement boundStatement = new BoundStatement(preparedStatement);
        return boundStatement;
    }

答案 1 :(得分:0)

对于spring-data-cassandra v1.x,org.springframework.cassandra.core.CqlOperations getSession()方法可以让您直接访问会话。但是,自v2.0以来,不推荐使用类似的API

以下是https://github.com/opencredo/spring-data-cassandra-example/

的示例
@Autowired
private CqlOperations cqlTemplate;//or inherited interface, like CassandraOperations

private void insertEventUsingPreparedStatement() {
  PreparedStatement preparedStatement = cqlTemplate.getSession().prepare("insert into event (id, type, bucket, tags) values (?, ?, ?, ?)");
  Statement insertStatement = preparedStatement.bind(UUIDs.timeBased(), "type2", TIME_BUCKET, ImmutableSet.of("tag1", "tag2"));
  cqlTemplate.execute(insertStatement); 
} 

答案 2 :(得分:0)

使用spring-data-cassandra,这将为你做所有的魔术 应用示例http://valchkou.com/spring-boot-cassandra.html#simple

@Repository
interface ISensorMeasureRepository extends CassandraRepository<SensorMeasureEntity> {

  @Query('select * from sensor_measures_simple where sensor_id=?0 and measure_time>=?1 and measure_time<=?2')
  List<SensorMeasureEntity> getBySensorAndDateRange(int sensorId, Date start, Date end)

  @Query('select * from sensor_measures_simple where sensor_id=?0 ALLOW FILTERING')
  Stream<SensorMeasureEntity> getAllBySensor(int sensorId)
}