Java Code Examples for com.datastax.driver.core.QueryOptions#setConsistencyLevel()

The following examples show how to use com.datastax.driver.core.QueryOptions#setConsistencyLevel() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CassandraConfig.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private Builder populateQueryOptions(Map<String, String> properties, Builder builder) {
    String consistencyLevelProp = properties.get(DBConstants.Cassandra.CONSISTENCY_LEVEL);
    String serialConsistencyLevelProp = properties.get(DBConstants.Cassandra.SERIAL_CONSISTENCY_LEVEL);
    String fetchSize = properties.get(DBConstants.Cassandra.FETCH_SIZE);
    QueryOptions options = new QueryOptions();
    if (consistencyLevelProp != null) {
        options.setConsistencyLevel(ConsistencyLevel.valueOf(consistencyLevelProp));
    }
    if (serialConsistencyLevelProp != null) {
        options.setSerialConsistencyLevel(ConsistencyLevel.valueOf(serialConsistencyLevelProp));
    }
    if (fetchSize != null) {
        options.setFetchSize(Integer.parseInt(fetchSize));
    }
    return builder.withQueryOptions(options);
}
 
Example 2
Source File: ExecutionEngine.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private Session createSession(Profile profile) {
	QueryOptions options = new QueryOptions();
	options.setConsistencyLevel(profile.getConsistencyLevel());
   Cluster.Builder builder = Cluster.builder();
   builder.addContactPoints(profile.getNodes().toArray(new String[0]));
   builder.withPort(profile.getPort());
   builder.withQueryOptions(options);

   if(!StringUtils.isBlank(profile.getUsername()) && !StringUtils.isBlank(profile.getPassword())) {
      builder.withCredentials(profile.getUsername(), profile.getPassword());
   }

   Cluster cluster = builder.build();
   Session session = cluster.connect(profile.getKeyspace());
   return session;
}
 
Example 3
Source File: MapConfiguredCqlClientFactory.java    From storm-cassandra-cql with Apache License 2.0 6 votes vote down vote up
private void configureQueryOptions() {

        final String consistencyConfiguration = (String) configuration.get(TRIDENT_CASSANDRA_CONSISTENCY);
        final String serialConsistencyConfiguration = (String) configuration.get(TRIDENT_CASSANDRA_SERIAL_CONSISTENCY);
        final QueryOptions queryOptions = builder.getConfiguration().getQueryOptions();

        if (StringUtils.isNotEmpty(consistencyConfiguration)) {
            queryOptions.setConsistencyLevel(ConsistencyLevel.valueOf(consistencyConfiguration));
        }

        if (StringUtils.isNotEmpty(serialConsistencyConfiguration)) {
            queryOptions.setSerialConsistencyLevel(ConsistencyLevel.valueOf(serialConsistencyConfiguration));
        }

        builder = builder.withQueryOptions(queryOptions);

    }
 
Example 4
Source File: CassandraDbProvider.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Currently we connect just once and then reuse the connection.
 * We do not bother with closing the connection.
 *
 * It is normal to use one Session per DB. The Session is thread safe.
 */
private void connect() {

    if (cluster == null) {

        log.info("Connecting to Cassandra server on " + this.dbHost + " at port " + this.dbPort);

        // allow fetching as much data as present in the DB
        QueryOptions queryOptions = new QueryOptions();
        queryOptions.setFetchSize(Integer.MAX_VALUE);
        queryOptions.setConsistencyLevel(ConsistencyLevel.ONE);

        cluster = Cluster.builder()
                         .addContactPoint(this.dbHost)
                         .withPort(this.dbPort)
                         .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
                         .withReconnectionPolicy(new ExponentialReconnectionPolicy(500, 30000))
                         .withQueryOptions(queryOptions)
                         .withCredentials(this.dbUser, this.dbPassword)
                         .build();

    }

    if (session == null) {

        log.info("Connecting to Cassandra DB with name " + this.dbName);
        session = cluster.connect(dbName);
    }
}
 
Example 5
Source File: CassandraSession.java    From eventapis with Apache License 2.0 5 votes vote down vote up
private QueryOptions getQueryOptions() {
    QueryOptions options = new QueryOptions();
    if (eventStoreConfig.getConsistencyLevel() != null) {
        options.setConsistencyLevel(eventStoreConfig.getConsistencyLevel());
    }
    if (eventStoreConfig.getSerialConsistencyLevel() != null) {
        options.setSerialConsistencyLevel(eventStoreConfig.getSerialConsistencyLevel());
    }
    options.setFetchSize(eventStoreConfig.getFetchSize());
    return options;
}
 
Example 6
Source File: CassandraTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private Cluster getCluster() throws StageException {
  RemoteEndpointAwareJdkSSLOptions sslOptions = null;

  if (conf.tlsConfig.isEnabled()) {
    // Not certain why we need the downcast here, but we do
    sslOptions = (RemoteEndpointAwareJdkSSLOptions)RemoteEndpointAwareJdkSSLOptions.builder()
        .withSSLContext(conf.tlsConfig.getSslContext())
        .build();
  }

  SocketOptions socketOptions = new SocketOptions();
  socketOptions.setConnectTimeoutMillis(conf.connectionTimeout);
  socketOptions.setReadTimeoutMillis(conf.readTimeout);

  QueryOptions queryOptions = new QueryOptions();
  queryOptions.setConsistencyLevel(conf.consistencyLevel);

  Cluster cluster = Cluster.builder()
      .addContactPoints(contactPoints)
      .withSSL(sslOptions)
      // If authentication is disabled on the C* cluster, this method has no effect.
      .withAuthProvider(getAuthProvider())
      .withProtocolVersion(conf.protocolVersion)
      .withPort(conf.port)
      .withCodecRegistry(new CodecRegistry().register(SDC_CODECS))
      .withSocketOptions(socketOptions)
      .withQueryOptions(queryOptions)
      .build();

  if (conf.logSlowQueries) {
    QueryLogger queryLogger = QueryLogger.builder()
        .withConstantThreshold(conf.slowQueryThreshold)
        .build();
    cluster.register(queryLogger);
  }
  return cluster;
}
 
Example 7
Source File: CqlConfigHelper.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private static QueryOptions getReadQueryOptions(Configuration conf)
{
    String CL = ConfigHelper.getReadConsistencyLevel(conf);
    Optional<Integer> fetchSize = getInputPageRowSize(conf);
    QueryOptions queryOptions = new QueryOptions();
    if (CL != null && !CL.isEmpty())
        queryOptions.setConsistencyLevel(com.datastax.driver.core.ConsistencyLevel.valueOf(CL));

    if (fetchSize.isPresent())
        queryOptions.setFetchSize(fetchSize.get());
    return queryOptions;
}
 
Example 8
Source File: ConstructorConfiguredCqlClientFactory.java    From storm-cassandra-cql with Apache License 2.0 5 votes vote down vote up
public Cluster.Builder getClusterBuilder() {

        final List<InetSocketAddress> sockets = new ArrayList<InetSocketAddress>();
        for (String host : hosts) {
            if(StringUtils.contains(host, ":")) {
                String hostParts [] = StringUtils.split(host, ":");
                sockets.add(new InetSocketAddress(hostParts[0], Integer.valueOf(hostParts[1])));
                LOG.debug("Connecting to [" + host + "] with port [" + hostParts[1] + "]");
            } else {
                sockets.add(new InetSocketAddress(host, ProtocolOptions.DEFAULT_PORT));
                LOG.debug("Connecting to [" + host + "] with port [" + ProtocolOptions.DEFAULT_PORT + "]");
            }
        }

        Cluster.Builder builder = Cluster.builder().addContactPointsWithPorts(sockets).withCompression(compression);
        QueryOptions queryOptions = new QueryOptions();
        queryOptions.setConsistencyLevel(clusterConsistencyLevel);
        queryOptions.setSerialConsistencyLevel(serialConsistencyLevel);
        builder = builder.withQueryOptions(queryOptions);

        if (StringUtils.isNotEmpty(clusterName)) {
            builder = builder.withClusterName(clusterName);
        }

        return builder;

    }
 
Example 9
Source File: CassandraConfiguration.java    From tutorials with MIT License 5 votes vote down vote up
private QueryOptions getQueryOptions(CassandraProperties properties) {
    QueryOptions options = new QueryOptions();
    if (properties.getConsistencyLevel() != null) {
        options.setConsistencyLevel(properties.getConsistencyLevel());
    }
    if (properties.getSerialConsistencyLevel() != null) {
        options.setSerialConsistencyLevel(properties.getSerialConsistencyLevel());
    }
    options.setFetchSize(properties.getFetchSize());
    return options;
}
 
Example 10
Source File: CassandraCluster.java    From monasca-persister with Apache License 2.0 4 votes vote down vote up
@Inject
public CassandraCluster(final PersisterConfig config) {

  this.dbConfig = config.getCassandraDbConfiguration();

  QueryOptions qo = new QueryOptions();
  qo.setConsistencyLevel(ConsistencyLevel.valueOf(dbConfig.getConsistencyLevel()));
  qo.setDefaultIdempotence(true);

  String[] contactPoints = dbConfig.getContactPoints();
  int retries = dbConfig.getMaxWriteRetries();
  Builder builder = Cluster.builder().addContactPoints(contactPoints).withPort(dbConfig.getPort());
  builder
      .withSocketOptions(new SocketOptions().setConnectTimeoutMillis(dbConfig.getConnectionTimeout())
          .setReadTimeoutMillis(dbConfig.getReadTimeout()));
  builder.withQueryOptions(qo).withRetryPolicy(new MonascaRetryPolicy(retries, retries, retries));

  lbPolicy = new TokenAwarePolicy(
      DCAwareRoundRobinPolicy.builder().withLocalDc(dbConfig.getLocalDataCenter()).build());
  builder.withLoadBalancingPolicy(lbPolicy);

  String user = dbConfig.getUser();
  if (user != null && !user.isEmpty()) {
    builder.withAuthProvider(new PlainTextAuthProvider(dbConfig.getUser(), dbConfig.getPassword()));
  }
  cluster = builder.build();

  PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();

  poolingOptions.setConnectionsPerHost(HostDistance.LOCAL, dbConfig.getMaxConnections(),
      dbConfig.getMaxConnections()).setConnectionsPerHost(HostDistance.REMOTE,
          dbConfig.getMaxConnections(), dbConfig.getMaxConnections());

  poolingOptions.setMaxRequestsPerConnection(HostDistance.LOCAL, dbConfig.getMaxRequests())
      .setMaxRequestsPerConnection(HostDistance.REMOTE, dbConfig.getMaxRequests());

  metricsSession = cluster.connect(dbConfig.getKeySpace());

  measurementInsertStmt = metricsSession.prepare(MEASUREMENT_INSERT_CQL).setIdempotent(true);
  // TODO: Remove update statements, TTL issues
  measurementUpdateStmt = metricsSession.prepare(MEASUREMENT_UPDATE_CQL).setIdempotent(true);
  metricInsertStmt = metricsSession.prepare(METRICS_INSERT_CQL).setIdempotent(true);
  dimensionStmt = metricsSession.prepare(DIMENSION_INSERT_CQL).setIdempotent(true);
  dimensionMetricStmt = metricsSession.prepare(DIMENSION_METRIC_INSERT_CQL).setIdempotent(true);
  metricDimensionStmt = metricsSession.prepare(METRIC_DIMENSION_INSERT_CQL).setIdempotent(true);

  retrieveMetricIdStmt = metricsSession.prepare(RETRIEVE_METRIC_ID_CQL).setIdempotent(true);
  retrieveMetricDimensionStmt = metricsSession.prepare(RETRIEVE_METRIC_DIMENSION_CQL)
      .setIdempotent(true);

  alarmsSession = cluster.connect(dbConfig.getKeySpace());

  alarmHistoryInsertStmt = alarmsSession.prepare(INSERT_ALARM_STATE_HISTORY_SQL).setIdempotent(true);

  metricIdCache = CacheBuilder.newBuilder()
      .maximumSize(config.getCassandraDbConfiguration().getDefinitionMaxCacheSize()).build();

  dimensionCache = CacheBuilder.newBuilder()
      .maximumSize(config.getCassandraDbConfiguration().getDefinitionMaxCacheSize()).build();

  metricDimensionCache = CacheBuilder.newBuilder()
      .maximumSize(config.getCassandraDbConfiguration().getDefinitionMaxCacheSize()).build();

  logger.info("loading cached definitions from db");

  ExecutorService executor = Executors.newFixedThreadPool(250);

  //a majority of the ids are for metrics not actively receiving msgs anymore
  //loadMetricIdCache(executor);

  loadDimensionCache();

  loadMetricDimensionCache(executor);

  executor.shutdown();
}