本文整理匯總了Java中com.datastax.driver.core.Session類的典型用法代碼示例。如果您正苦於以下問題:Java Session類的具體用法?Java Session怎麽用?Java Session使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Session類屬於com.datastax.driver.core包,在下文中一共展示了Session類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: executeAdaptiveQueryAsync
import com.datastax.driver.core.Session; //導入依賴的package包/類
private static ListenableFuture<ResultSet> executeAdaptiveQueryAsync(Session session, Statement statement, int fetchSize,
int remainingAdaptations) {
statement.setFetchSize(fetchSize);
ResultSetFuture rawFuture = session.executeAsync(statement);
// Lazily wrap the result set from the async result with an AdaptiveResultSet
ListenableFuture<ResultSet> adaptiveFuture = Futures.transform(rawFuture, new Function<ResultSet, ResultSet>() {
@Override
public ResultSet apply(ResultSet resultSet) {
return new AdaptiveResultSet(session, resultSet, remainingAdaptations);
}
});
return Futures.withFallback(adaptiveFuture, t -> {
if (isAdaptiveException(t) && remainingAdaptations > 0 && fetchSize > MIN_FETCH_SIZE) {
// Try again with half the fetch size
int reducedFetchSize = Math.max(fetchSize / 2, MIN_FETCH_SIZE);
_log.debug("Repeating previous query with fetch size {} due to {}", reducedFetchSize, t.getMessage());
return executeAdaptiveQueryAsync(session, statement, reducedFetchSize, remainingAdaptations - 1);
}
throw Throwables.propagate(t);
});
}
示例2: createSession
import com.datastax.driver.core.Session; //導入依賴的package包/類
@Bean
public Session createSession(CassandraProperties properties, Cluster cluster) throws Exception {
Session session = Retriable.wrap(cluster::connect)
.withErrorMessage("Cannot connect to cassandra cluster")
.retryOn(NoHostAvailableException.class)
.withDelaySec(properties.getConnectDelaySec())
.call();
initDb(properties, session);
if (!session.getCluster().getMetadata().checkSchemaAgreement()) {
log.warn("SCHEMA IS NOT IN AGREEMENT!!!");
}
return session;
}
示例3: testRequestMessageStatement
import com.datastax.driver.core.Session; //導入依賴的package包/類
/**
* Test with incoming message containing a header with RegularStatement.
*/
@Test
public void testRequestMessageStatement() throws Exception {
Update.Where update = update("camel_user")
.with(set("first_name", bindMarker()))
.and(set("last_name", bindMarker()))
.where(eq("login", bindMarker()));
Object response = producerTemplate.requestBodyAndHeader(new Object[]{"Claus 2", "Ibsen 2", "c_ibsen"},
CassandraConstants.CQL_QUERY, update);
Cluster cluster = CassandraUnitUtils.cassandraCluster();
Session session = cluster.connect(CassandraUnitUtils.KEYSPACE);
ResultSet resultSet = session.execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen");
Row row = resultSet.one();
assertNotNull(row);
assertEquals("Claus 2", row.getString("first_name"));
assertEquals("Ibsen 2", row.getString("last_name"));
session.close();
cluster.close();
}
示例4: testDelayOnPreparedStatementWhenIgnoreOnPrepareIsFalse
import com.datastax.driver.core.Session; //導入依賴的package包/類
@Test
public void testDelayOnPreparedStatementWhenIgnoreOnPrepareIsFalse() throws Exception {
Prime prime =
PrimeDsl.when("select * from table where c1=?")
.then(noRows())
.delay(2, TimeUnit.SECONDS)
.applyToPrepare()
.build();
HttpTestResponse response = server.prime(prime.getPrimedRequest());
assertNotNull(response);
RequestPrime responseQuery = om.readValue(response.body, RequestPrime.class);
assertThat(responseQuery).isEqualTo(prime.getPrimedRequest());
String contactPoint = HttpTestUtil.getContactPointString(server.getCluster(), 0);
try (com.datastax.driver.core.Cluster cluster =
defaultBuilder().addContactPoint(contactPoint).build()) {
Session session = cluster.connect();
long start = System.currentTimeMillis();
session.prepare("select * from table where c1=?");
long duration = System.currentTimeMillis() - start;
// should have taken longer than 2 seconds.
assertThat(duration).isGreaterThan(2000);
}
}
示例5: primeAndExecuteQueries
import com.datastax.driver.core.Session; //導入依賴的package包/類
private void primeAndExecuteQueries(String[] primed, String[] queries) throws Exception {
SuccessResult result = getSampleSuccessResult();
for (String primeQuery : primed) {
server.prime(when(primeQuery).then(result));
}
try (com.datastax.driver.core.Cluster driverCluster =
defaultBuilder(server.getCluster())
.withRetryPolicy(FallthroughRetryPolicy.INSTANCE)
.build()) {
Session session = driverCluster.connect();
server.getCluster().clearLogs();
for (String executeQuery : queries) {
SimpleStatement stmt = new SimpleStatement(executeQuery);
stmt.setDefaultTimestamp(100);
session.execute(stmt);
}
}
}
示例6: getClientSession
import com.datastax.driver.core.Session; //導入依賴的package包/類
public static Session getClientSession(String hostAddr) {
if(REGISTRY.containsKey(hostAddr)) {
return REGISTRY.get(hostAddr);
} else {
Cluster.Builder clientClusterBuilder = new Cluster.Builder()
.addContactPoint(hostAddr)
.withQueryOptions(new QueryOptions()
.setConsistencyLevel(ConsistencyLevel.ONE)
.setSerialConsistencyLevel(ConsistencyLevel.LOCAL_SERIAL))
.withoutJMXReporting()
.withoutMetrics()
.withReconnectionPolicy(new ConstantReconnectionPolicy(RECONNECT_DELAY_IN_MS));
long startTimeInMillis = System.currentTimeMillis();
Cluster clientCluster = clientClusterBuilder.build();
Session clientSession = clientCluster.connect();
LOG.info("Client session established after {} ms.", System.currentTimeMillis() - startTimeInMillis);
REGISTRY.putIfAbsent(hostAddr, clientSession);
return clientSession;
}
}
示例7: createSession
import com.datastax.driver.core.Session; //導入依賴的package包/類
public static Session createSession(String ip, int port) {
Cluster cluster;
cluster = Cluster.builder()
.addContactPoint(ip)
.withPort(port)
.build();
Session session = cluster.connect();
session.execute("CREATE KEYSPACE IF NOT EXISTS cassandrait WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }");
session.execute("DROP TABLE IF EXISTS cassandrait.counter");
session.execute("CREATE TABLE cassandrait.counter (key text, value counter, PRIMARY key(key));");
return session;
}
示例8: selectByDevice
import com.datastax.driver.core.Session; //導入依賴的package包/類
@Override
public Status selectByDevice(TsPoint point, Date startTime, Date endTime) {
long costTime = 0L;
Cluster cluster = null;
try {
// cluster = Cluster.builder().addContactPoint(CASSADRA_URL).build();
// Session session = cluster.connect(KEY_SPACE_NAME);
Session session = SessionManager.getSession();
String selectCql = "SELECT * FROM point WHERE device_code='" + point.getDeviceCode() + "' and timestamp>="
+ startTime.getTime() + " and timestamp<=" + endTime.getTime() + " ALLOW FILTERING";
// System.out.println(selectCql);
long startTime1 = System.nanoTime();
ResultSet rs = session.execute(selectCql);
long endTime1 = System.nanoTime();
costTime = endTime1 - startTime1;
} finally {
if (cluster != null)
cluster.close();
}
// System.out.println("此次查詢消耗時間[" + costTime / 1000 + "]s");
return Status.OK(costTime);
}
示例9: selectByDeviceAndSensor
import com.datastax.driver.core.Session; //導入依賴的package包/類
@Override
public Status selectByDeviceAndSensor(TsPoint point, Date startTime, Date endTime) {
long costTime = 0L;
Cluster cluster = null;
try {
// cluster = Cluster.builder().addContactPoint(CASSADRA_URL).build();
// Session session = cluster.connect(KEY_SPACE_NAME);
Session session = SessionManager.getSession();
String selectCql = "SELECT * FROM point WHERE device_code='" + point.getDeviceCode() + "' and sensor_code='"
+ point.getSensorCode() + "' and timestamp>=" + startTime.getTime() + " and timestamp<="
+ endTime.getTime() + " ALLOW FILTERING";
// System.out.println(selectCql);
long startTime1 = System.nanoTime();
ResultSet rs = session.execute(selectCql);
long endTime1 = System.nanoTime();
costTime = endTime1 - startTime1;
} finally {
if (cluster != null)
cluster.close();
}
// System.out.println("此次查詢消耗時間[" + costTime / 1000 + "]s");
return Status.OK(costTime);
}
示例10: selectMaxByDeviceAndSensor
import com.datastax.driver.core.Session; //導入依賴的package包/類
@Override
public Status selectMaxByDeviceAndSensor(String deviceCode, String sensorCode, Date startTime, Date endTime) {
long costTime = 0L;
Cluster cluster = null;
try {
// cluster = Cluster.builder().addContactPoint(CASSADRA_URL).build();
// Session session = cluster.connect(KEY_SPACE_NAME);
Session session = SessionManager.getSession();
String selectCql = "SELECT MAX(value) FROM point WHERE device_code='" + deviceCode + "' and sensor_code='"
+ sensorCode + "' and timestamp>=" + startTime.getTime() + " and timestamp<=" + endTime.getTime()
+ " ALLOW FILTERING";
long startTime1 = System.nanoTime();
// System.out.println("aaa");
ResultSet rs = session.execute(selectCql);
// System.out.println("bbb");
long endTime1 = System.nanoTime();
costTime = endTime1 - startTime1;
} finally {
if (cluster != null)
cluster.close();
}
// System.out.println("此次查詢消耗時間[" + costTime / 1000 + "]s");
return Status.OK(costTime);
}
示例11: selectMinByDeviceAndSensor
import com.datastax.driver.core.Session; //導入依賴的package包/類
@Override
public Status selectMinByDeviceAndSensor(String deviceCode, String sensorCode, Date startTime, Date endTime) {
long costTime = 0L;
Cluster cluster = null;
try {
cluster = Cluster.builder().addContactPoint(CASSADRA_URL).build();
Session session = cluster.connect(KEY_SPACE_NAME);
String selectCql = "SELECT MIN(value) FROM point WHERE device_code='" + deviceCode + "' and sensor_code='"
+ sensorCode + "' and timestamp>=" + startTime.getTime() + " and timestamp<=" + endTime.getTime()
+ " ALLOW FILTERING";
// System.out.println(selectCql);
long startTime1 = System.nanoTime();
ResultSet rs = session.execute(selectCql);
long endTime1 = System.nanoTime();
costTime = endTime1 - startTime1;
} finally {
if (cluster != null)
cluster.close();
}
// System.out.println("此次查詢消耗時間[" + costTime / 1000 + "]s");
return Status.OK(costTime);
}
示例12: selectAvgByDeviceAndSensor
import com.datastax.driver.core.Session; //導入依賴的package包/類
@Override
public Status selectAvgByDeviceAndSensor(String deviceCode, String sensorCode, Date startTime, Date endTime) {
long costTime = 0L;
Cluster cluster = null;
try {
cluster = Cluster.builder().addContactPoint(CASSADRA_URL).build();
Session session = cluster.connect(KEY_SPACE_NAME);
String selectCql = "SELECT AVG(value) FROM point WHERE device_code='" + deviceCode + "' and sensor_code='"
+ sensorCode + "' and timestamp>=" + startTime.getTime() + " and timestamp<=" + endTime.getTime()
+ " ALLOW FILTERING";
// System.out.println(selectCql);
long startTime1 = System.nanoTime();
ResultSet rs = session.execute(selectCql);
long endTime1 = System.nanoTime();
costTime = endTime1 - startTime1;
} finally {
if (cluster != null)
cluster.close();
}
// System.out.println("此次查詢消耗時間[" + costTime / 1000 + "]s");
return Status.OK(costTime);
}
示例13: selectCountByDeviceAndSensor
import com.datastax.driver.core.Session; //導入依賴的package包/類
@Override
public Status selectCountByDeviceAndSensor(String deviceCode, String sensorCode, Date startTime, Date endTime) {
long costTime = 0L;
Cluster cluster = null;
try {
cluster = Cluster.builder().addContactPoint(CASSADRA_URL).build();
Session session = cluster.connect(KEY_SPACE_NAME);
String selectCql = "SELECT COUNT(*) FROM point WHERE device_code='" + deviceCode + "' and sensor_code='"
+ sensorCode + "' and timestamp>=" + startTime.getTime() + " and timestamp<=" + endTime.getTime()
+ " ALLOW FILTERING";
// System.out.println(selectCql);
long startTime1 = System.nanoTime();
ResultSet rs = session.execute(selectCql);
long endTime1 = System.nanoTime();
costTime = endTime1 - startTime1;
} finally {
if (cluster != null)
cluster.close();
}
// System.out.println("此次查詢消耗時間[" + costTime / 1000 + "]s");
return Status.OK(costTime);
}
示例14: untilApplied
import com.datastax.driver.core.Session; //導入依賴的package包/類
public static boolean untilApplied(Session session, BatchStatement.Type type, Consumer<BatchStatement> transaction) {
for (int i = 1; i <= MAX_RETRY; i ++) {
BatchStatement batchStatement = new BatchStatement(type);
transaction.accept(batchStatement);
if (batchStatement.size() == 0) return false;
boolean applied;
if (batchStatement.size() > 1) {
applied = session.execute(batchStatement).wasApplied();
} else {
Statement statement = Iterables.getOnlyElement(batchStatement.getStatements());
applied = session.execute(statement).wasApplied();
}
if (applied) return true;
log.warn("Attempt {}/{} failed executing {}", i, MAX_RETRY, batchStatement);
try {
Thread.sleep(100 * i);
} catch (InterruptedException e) {
throw new AttemptsFailedException(e);
}
}
throw new AttemptsFailedException();
}
示例15: executeSchemaCql
import com.datastax.driver.core.Session; //導入依賴的package包/類
public static void executeSchemaCql(Session session, boolean deleteData) {
try {
URL schema = Resources.getResource("schema.cql");
String schemaCql = Resources.toString(schema, Charset.forName("UTF-8"));
schemaCql = schemaCql.replaceAll("(?m)//.*$", "");
String[] statements = schemaCql.split(";");
if (deleteData) {
dropSchema(session);
}
for (String statement : statements) {
statement = statement.trim();
if (statement.isEmpty()) continue;
executeWithLog(session, statement);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}