Java Code Examples for com.datastax.driver.core.Cluster.Builder#build()

The following examples show how to use com.datastax.driver.core.Cluster.Builder#build() . 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
public CassandraConfig(DataService dataService, String configId, Map<String, String> properties,
                       boolean odataEnable) throws DataServiceFault {
    super(dataService, configId, DataSourceTypes.CASSANDRA, properties, odataEnable);
    Builder builder = Cluster.builder();
    this.populateSettings(builder, properties);
    String keyspace = properties.get(DBConstants.Cassandra.KEYSPACE);
    this.cluster = builder.build();
    try {
        if (keyspace != null && keyspace.trim().length() > 0) {
            this.session = this.cluster.connect(keyspace);
        } else {
            this.session = this.cluster.connect();
        }
        this.nativeBatchRequestsSupported = this.session.getCluster().
                getConfiguration().getProtocolOptions().getProtocolVersion().toInt() > 1;
    } catch (NoHostAvailableException e) {
        throw new DataServiceFault(e, DBConstants.FaultCodes.CONNECTION_UNAVAILABLE_ERROR, e.getMessage());
    }
}
 
Example 2
Source File: SchemaManager.java    From newts with Apache License 2.0 6 votes vote down vote up
@Inject
public SchemaManager(@Named("cassandra.keyspace") String keyspace, @Named("cassandra.host") String host, @Named("cassandra.port") int port,
        @Named("cassandra.username") String username, @Named("cassandra.password") String password, @Named("cassandra.ssl") boolean ssl) {
    m_keyspace = keyspace;

    Builder builder = Cluster.builder()
            .withPort(port)
            .addContactPoints(host.split(","));
    if (username != null && password != null) {
        LOG.info("Using username: {} and password: XXXXXXXX", username);
        builder.withCredentials(username, password);
    }

    if (ssl) {
        LOG.info("Using SSL.");
        builder.withSSL();
    }
    m_cluster= builder.build();
    m_session = m_cluster.connect();
}
 
Example 3
Source File: CassandraConnector.java    From tutorials with MIT License 6 votes vote down vote up
public void connect(final String node, final Integer port) {

        Builder b = Cluster.builder().addContactPoint(node);

        if (port != null) {
            b.withPort(port);
        }
        cluster = b.build();

        Metadata metadata = cluster.getMetadata();
        LOG.info("Cluster name: " + metadata.getClusterName());

        for (Host host : metadata.getAllHosts()) {
            LOG.info("Datacenter: " + host.getDatacenter() + " Host: " + host.getAddress() + " Rack: " + host.getRack());
        }

        session = cluster.connect();
    }
 
Example 4
Source File: CassandraHelper.java    From cassandana with Apache License 2.0 5 votes vote down vote up
public void tryConnecting() {
	Builder b = Cluster.builder().addContactPoint(host);
	b.withPort(port);
       cluster = b.build();
       session = cluster.connect(dbName);//keyspace
       onConnected();
}
 
Example 5
Source File: CassandraConnector.java    From Getaviz with Apache License 2.0 5 votes vote down vote up
public void connect(String node, Integer port, String keyspace) {
    Builder b = Cluster.builder().addContactPoint(node);
    if (port != null) {
        b.withPort(port);
    }
    cluster = b.build();
 
    session = cluster.connect(keyspace);
}
 
Example 6
Source File: CassandraConfig.java    From micro-service with MIT License 5 votes vote down vote up
@Bean
  public Cluster cassandraCluster() {

Builder builder = Cluster.builder();
      
if(StringUtils.isNoneBlank(cassandraProperties.getUsername()) && StringUtils.isNotBlank(cassandraProperties.getPassword())) {
      	builder = builder.withCredentials(cassandraProperties.getUsername(), cassandraProperties.getPassword());
      }

String[] contactPoints = cassandraProperties.getContactPoints().toArray(new String[cassandraProperties.getContactPoints().size()]);
builder = builder.addContactPoints(contactPoints).withPort(cassandraProperties.getPort());
      
return builder.build();
  }
 
Example 7
Source File: CassandraFactory.java    From database-transform-tool with Apache License 2.0 4 votes vote down vote up
/**
	 * 描述: 初始化配置
	 * 时间: 2017年11月15日 上午11:25:07
	 * @author yi.zhang
	 * @param servers	服务地址
	 * @param keyspace	命名空间
	 * @param username	账号
	 * @param password	密码
	 */
	public void init(String servers,String keyspace,String username,String password) {
		try {
			// socket 链接配置
			SocketOptions socket = new SocketOptions();
			socket.setKeepAlive(true);
			socket.setReceiveBufferSize(1024* 1024);
			socket.setSendBufferSize(1024* 1024);
			socket.setConnectTimeoutMillis(5 * 1000);
			socket.setReadTimeoutMillis(1000);
			//设置连接池
			PoolingOptions pool = new PoolingOptions();
			// pool.setMaxRequestsPerConnection(HostDistance.LOCAL, 32);
			// pool.setMaxRequestsPerConnection(HostDistance.REMOTE, 32);
			// pool.setCoreConnectionsPerHost(HostDistance.LOCAL, 2);
			// pool.setCoreConnectionsPerHost(HostDistance.REMOTE, 2);
			// pool.setMaxConnectionsPerHost(HostDistance.LOCAL, 4);
			// pool.setMaxConnectionsPerHost(HostDistance.REMOTE, 4);
			pool.setHeartbeatIntervalSeconds(60);
			pool.setIdleTimeoutSeconds(120);
			pool.setPoolTimeoutMillis(5 * 1000);
			List<InetSocketAddress> saddress = new ArrayList<InetSocketAddress>();
			if (servers != null && !"".equals(servers)) {
				for (String server : servers.split(",")) {
					String[] address = server.split(":");
					String ip = address[0];
					int port = 9042;
					if (address != null && address.length > 1) {
						port = Integer.valueOf(address[1]);
					}
					saddress.add(new InetSocketAddress(ip, port));
				}
			}
			InetSocketAddress[] addresses = new InetSocketAddress[saddress.size()];
			saddress.toArray(addresses);
			
			Builder builder = Cluster.builder();
	        builder.withSocketOptions(socket);
	        // 设置压缩方式
	        builder.withCompression(ProtocolOptions.Compression.LZ4);
	        // 负载策略
//	        DCAwareRoundRobinPolicy loadBalance = DCAwareRoundRobinPolicy.builder().withLocalDc("localDc").withUsedHostsPerRemoteDc(2).allowRemoteDCsForLocalConsistencyLevel().build();
//	        builder.withLoadBalancingPolicy(loadBalance);
	        // 重试策略
	        builder.withRetryPolicy(DefaultRetryPolicy.INSTANCE);
			builder.withPoolingOptions(pool);
			builder.addContactPointsWithPorts(addresses);
			builder.withCredentials(username, password);
			Cluster cluster = builder.build();
			if (keyspace != null && !"".equals(keyspace)) {
				session = cluster.connect(keyspace);
			} else {
				session = cluster.connect();
			}
			mapping = new MappingManager(session);
		} catch (Exception e) {
			logger.error("-----Cassandra Config init Error-----", e);
		}
	}
 
Example 8
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();
}
 
Example 9
Source File: CassandraClusterCreator.java    From spring-cloud-connectors with Apache License 2.0 4 votes vote down vote up
@Override
public Cluster create(CassandraServiceInfo serviceInfo,
		ServiceConnectorConfig serviceConnectorConfig) {

	Builder builder = Cluster.builder()
			.addContactPoints(serviceInfo.getContactPoints().toArray(new String[0]))
			.withPort(serviceInfo.getPort());

	if (StringUtils.hasText(serviceInfo.getUsername())) {
		builder.withCredentials(serviceInfo.getUsername(), serviceInfo.getPassword());
	}

	if (serviceConnectorConfig instanceof CassandraClusterConfig) {

		CassandraClusterConfig config = (CassandraClusterConfig) serviceConnectorConfig;

		if (config.getCompression() != null) {
			builder.withCompression(config.getCompression());
		}

		builder.withPoolingOptions(config.getPoolingOptions());
		builder.withSocketOptions(config.getSocketOptions());
		builder.withQueryOptions(config.getQueryOptions());
		builder.withNettyOptions(config.getNettyOptions());
		builder.withLoadBalancingPolicy(config.getLoadBalancingPolicy());
		builder.withReconnectionPolicy(config.getReconnectionPolicy());
		builder.withRetryPolicy(config.getRetryPolicy());

		if (config.getProtocolVersion() != null) {
			builder.withProtocolVersion(config.getProtocolVersion());
		}

		if (!config.isMetricsEnabled()) {
			builder.withoutMetrics();
		}

		if (!config.isJmxReportingEnabled()) {
			builder.withoutJMXReporting();
		}
	}

	return builder.build();
}