总的来说,cassandra新增了一个包,名字:com.datastax.driver.core
这个包提供了很多api类和接口,让在代码中对cassandra数据库的操作变得更容易和更简洁了。
首先从创建一个连接说起
1. com.datastax.driver.core.PoolingOptions连接池类
PoolingOptions pools = new PoolingOptions();
pools.setCoreConnectionsPerHost(HostDistance.LOCAL,2);//和集群中每台机器最少保存着两个连接
pools.setMaxConnectionsPerHost(HostDistance.LOCAL,100);//和集群中每台机器最多100个连接
pools.setIdleTimeoutSeconds(10);//超时时间
pools.setMaxRequestsPerConnection(HostDistance.LOCAL,100);//每个连接最多接受100个请求
2. com.datastax.driver.core.Cluster集群类
Clustercluster= new Cluster.Builder()
.addContactPoints(dataStaxConfig.getHosts()).withPort(dataStaxConfig.getPort())
.withPoolingOptions(pools)
.withSocketOptions(newSocketOptions().setTcpNoDelay(true)
.setSendBufferSize(dataStaxConfig.getSendBufferSize())
.setReceiveBufferSize(dataStaxConfig.getReceiveBufferSize())
.setConnectTimeoutMillis(6000)
.setReadTimeoutMillis(180000)
) .build();
-- dataStaxConfig.getHosts()核心节点ip,dataStaxConfig.getPort()端口,.withPoolingOptions(pools)绑定的线程池,withSocketOptions网络交互sock的参数配置
3.com.datastax.driver.core.Session会话类
Session session =cluster.connect(dataStaxConfig.getKeyspaceName());//选择某个表空间,获得会话句柄,通过该会话句柄操作cassandra数据库,比如Session.execute(String cql)
4. 各种Statement类
跟jdbc不同,cassandra虽然也提供各种Statement类,但是用法却不一样。Jdbc是用Statement. Execute(sql),而cassandra是用Session.execute(Statement)
比如SimpleStatement
SimpleStatementStatement s = new SimpleStatement("select * from zrf_test");
session.execute(s);
比如BoundStatement / PreparedStatement
PreparedStatement pre=getSession().prepare("select * fromzrf_test where serid=? ");
pre.setConsistencyLevel(type);//设置数据一致性
BoundStatementboundStatement = new BoundStatement(pre);
boundStatement.bind(“123”);
比如BatchStatement/BuiltStatement
因为这两个不是常用的,以后再完善
5.com.datastax.driver.core.ResultSet
ResultSetresult= session. .execute(boundStatement);
--总而言之,获取连接会话操作sql语句的整个正常流程就是这样了