com.datastax.driver.core.Cluster.Builder Java Examples

The following examples show how to use com.datastax.driver.core.Cluster.Builder. 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 realtime-analytics with GNU General Public License v2.0 6 votes vote down vote up
private void copyPoolingOptions(Builder builder) {
    PoolingOptions opts = new PoolingOptions();

    opts.setCoreConnectionsPerHost(HostDistance.REMOTE,
            remoteCoreConnectionsPerHost);
    opts.setCoreConnectionsPerHost(HostDistance.LOCAL,
            localCoreConnectionsPerHost);
    opts.setMaxConnectionsPerHost(HostDistance.REMOTE,
            remoteMaxConnectionsPerHost);
    opts.setMaxConnectionsPerHost(HostDistance.LOCAL,
            localMaxConnectionsPerHost);
    opts.setMaxSimultaneousRequestsPerConnectionThreshold(
            HostDistance.REMOTE,
            remoteMaxSimultaneousRequestsPerConnectionThreshold);
    opts.setMaxSimultaneousRequestsPerConnectionThreshold(
            HostDistance.LOCAL,
            localMaxSimultaneousRequestsPerConnectionThreshold);
    opts.setMinSimultaneousRequestsPerConnectionThreshold(
            HostDistance.REMOTE,
            remoteMinSimultaneousRequestsPerConnectionThreshold);
    opts.setMinSimultaneousRequestsPerConnectionThreshold(
            HostDistance.LOCAL,
            localMinSimultaneousRequestsPerConnectionThreshold);

    builder.withPoolingOptions(opts);
}
 
Example #2
Source File: CassandraTest.java    From copper-engine with Apache License 2.0 6 votes vote down vote up
@BeforeClass
    public synchronized static void setUpBeforeClass() throws Exception {
        if (factory == null) {
//            logger.info("Starting embedded cassandra...");
//            EmbeddedCassandraServerHelper.startEmbeddedCassandra("unittest-cassandra.yaml", "./build/cassandra");
//            Thread.sleep(100);
//            logger.info("Successfully started embedded cassandra.");

            final Cluster cluster = new Builder().addContactPoint("localhost").withPort(CASSANDRA_PORT).build();
//            final Session session = cluster.newSession();
//            session.execute("CREATE KEYSPACE copper WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");

            factory = new UnitTestCassandraEngineFactory(false);
            factory.setCassandraPort(CASSANDRA_PORT);
            try {
                factory.getEngine().startup();
            } catch (NoHostAvailableException e) {
                factory = null;
            }
        }
    }
 
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: 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 #5
Source File: CassandraPojoSinkExample.java    From flink with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

	DataStreamSource<Message> source = env.fromCollection(messages);

	CassandraSink.addSink(source)
		.setClusterBuilder(new ClusterBuilder() {
			@Override
			protected Cluster buildCluster(Builder builder) {
				return builder.addContactPoint("127.0.0.1").build();
			}
		})
		.setMapperOptions(() -> new Mapper.Option[]{Mapper.Option.saveNullFields(true)})
		.build();

	env.execute("Cassandra Sink example");
}
 
Example #6
Source File: CassandraTupleSinkExample.java    From flink with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

	DataStreamSource<Tuple2<String, Integer>> source = env.fromCollection(collection);

	CassandraSink.addSink(source)
		.setQuery(INSERT)
		.setClusterBuilder(new ClusterBuilder() {
			@Override
			protected Cluster buildCluster(Builder builder) {
				return builder.addContactPoint("127.0.0.1").build();
			}
		})
		.build();

	env.execute("WriteTupleIntoCassandra");
}
 
Example #7
Source File: CCMBridge.java    From cassandra-jdbc-wrapper with Apache License 2.0 6 votes vote down vote up
public void createCluster() {
    erroredOut = false;
    schemaCreated = false;
    cassandraCluster = CCMBridge.create("test", 1);
    try {
        Builder builder = Cluster.builder();
        builder = configure(builder);
        cluster = builder.addContactPoints(IP_PREFIX + '1').build();
        session = cluster.connect();
    } catch (NoHostAvailableException e) {
        erroredOut = true;
        for (Map.Entry<InetSocketAddress, Throwable> entry : e.getErrors().entrySet())
            logger.info("Error connecting to " + entry.getKey() + ": " + entry.getValue());
        throw new RuntimeException(e);
    }
}
 
Example #8
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 #9
Source File: CassandraPojoSinkExample.java    From flink with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

	DataStreamSource<Message> source = env.fromCollection(messages);

	CassandraSink.addSink(source)
		.setClusterBuilder(new ClusterBuilder() {
			@Override
			protected Cluster buildCluster(Builder builder) {
				return builder.addContactPoint("127.0.0.1").build();
			}
		})
		.setMapperOptions(() -> new Mapper.Option[]{Mapper.Option.saveNullFields(true)})
		.build();

	env.execute("Cassandra Sink example");
}
 
Example #10
Source File: CassandraPojoSinkExample.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

	DataStreamSource<Message> source = env.fromCollection(messages);

	CassandraSink.addSink(source)
		.setClusterBuilder(new ClusterBuilder() {
			@Override
			protected Cluster buildCluster(Builder builder) {
				return builder.addContactPoint("127.0.0.1").build();
			}
		})
		.setMapperOptions(() -> new Mapper.Option[]{Mapper.Option.saveNullFields(true)})
		.build();

	env.execute("Cassandra Sink example");
}
 
Example #11
Source File: CassandraTupleSinkExample.java    From flink with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

	DataStreamSource<Tuple2<String, Integer>> source = env.fromCollection(collection);

	CassandraSink.addSink(source)
		.setQuery(INSERT)
		.setClusterBuilder(new ClusterBuilder() {
			@Override
			protected Cluster buildCluster(Builder builder) {
				return builder.addContactPoint("127.0.0.1").build();
			}
		})
		.build();

	env.execute("WriteTupleIntoCassandra");
}
 
Example #12
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 #13
Source File: CassandraConfig.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private Builder populateRetrytPolicy(Map<String, String> properties, Builder builder) throws DataServiceFault {
    String retryPolicy = properties.get(DBConstants.Cassandra.RETRY_POLICY);
    if (retryPolicy != null) {
        if ("DefaultRetryPolicy".equals(retryPolicy)) {
            builder = builder.withRetryPolicy(DefaultRetryPolicy.INSTANCE);
        } else if ("DowngradingConsistencyRetryPolicy".equals(retryPolicy)) {
            builder = builder.withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
        } else if ("FallthroughRetryPolicy".equals(retryPolicy)) {
            builder = builder.withRetryPolicy(FallthroughRetryPolicy.INSTANCE);
        } else if ("LoggingDefaultRetryPolicy".equals(retryPolicy)) {
            builder = builder.withRetryPolicy(new LoggingRetryPolicy(DefaultRetryPolicy.INSTANCE));
        } else if ("LoggingDowngradingConsistencyRetryPolicy".equals(retryPolicy)) {
            builder = builder.withRetryPolicy(new LoggingRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE));                
        } else if ("LoggingFallthroughRetryPolicy".equals(retryPolicy)) {
            builder = builder.withRetryPolicy(new LoggingRetryPolicy(FallthroughRetryPolicy.INSTANCE));                
        } else {
            throw new DataServiceFault("Invalid Cassandra retry policy: " + retryPolicy);
        }
    }
    return builder;
}
 
Example #14
Source File: CassandraTupleSinkExample.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

	DataStreamSource<Tuple2<String, Integer>> source = env.fromCollection(collection);

	CassandraSink.addSink(source)
		.setQuery(INSERT)
		.setClusterBuilder(new ClusterBuilder() {
			@Override
			protected Cluster buildCluster(Builder builder) {
				return builder.addContactPoint("127.0.0.1").build();
			}
		})
		.build();

	env.execute("WriteTupleIntoCassandra");
}
 
Example #15
Source File: CassandraConfig.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private Builder populateCredentials(Map<String, String> properties, Builder builder) {
    String usernameProp = properties.get(DBConstants.Cassandra.USERNAME);
    String passwordProp = properties.get(DBConstants.Cassandra.PASSWORD);
    if (usernameProp != null) {
        builder = builder.withCredentials(usernameProp, passwordProp);
    }
    return builder;
}
 
Example #16
Source File: CassandraConfig.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private Builder populatePoolingSettings(Map<String, String> properties, Builder builder) {
    String localCoreConnectionsPerHost = properties.get(DBConstants.Cassandra.LOCAL_CORE_CONNECTIONS_PER_HOST);
    String remoteCoreConnectionsPerHost = properties.get(DBConstants.Cassandra.REMOTE_CORE_CONNECTIONS_PER_HOST);
    String localMaxConnectionsPerHost = properties.get(DBConstants.Cassandra.LOCAL_MAX_CONNECTIONS_PER_HOST);
    String remoteMaxConnectionsPerHost = properties.get(DBConstants.Cassandra.REMOTE_MAX_CONNECTIONS_PER_HOST);
    String localNewConnectionThreshold = properties.get(DBConstants.Cassandra.LOCAL_NEW_CONNECTION_THRESHOLD);
    String remoteNewConnectionThreshold = properties.get(DBConstants.Cassandra.REMOTE_NEW_CONNECTION_THRESHOLD);
    String localMaxRequestsPerConnection = properties.get(DBConstants.Cassandra.LOCAL_MAX_REQUESTS_PER_CONNECTION);
    String remoteMaxRequestsPerConnection = properties.get(DBConstants.Cassandra.REMOTE_MAX_REQUESTS_PER_CONNECTION);
    PoolingOptions options = new PoolingOptions();
    if (localCoreConnectionsPerHost != null) {
        options.setCoreConnectionsPerHost(HostDistance.LOCAL, Integer.parseInt(localCoreConnectionsPerHost));
    }
    if (remoteCoreConnectionsPerHost != null) {
        options.setCoreConnectionsPerHost(HostDistance.REMOTE, Integer.parseInt(remoteCoreConnectionsPerHost));
    }
    if (localMaxConnectionsPerHost != null) {
        options.setMaxConnectionsPerHost(HostDistance.LOCAL, Integer.parseInt(localMaxConnectionsPerHost));
    }
    if (remoteMaxConnectionsPerHost != null) {
        options.setMaxConnectionsPerHost(HostDistance.REMOTE, Integer.parseInt(remoteMaxConnectionsPerHost));
    }
    if (localNewConnectionThreshold != null) {
        options.setNewConnectionThreshold(HostDistance.LOCAL, Integer.parseInt(localNewConnectionThreshold));
    }
    if (remoteNewConnectionThreshold != null) {
        options.setNewConnectionThreshold(HostDistance.REMOTE, Integer.parseInt(remoteNewConnectionThreshold));
    }
    if (localMaxRequestsPerConnection != null) {
        options.setMaxRequestsPerConnection(HostDistance.LOCAL, Integer.parseInt(localMaxRequestsPerConnection));
    }
    if (remoteMaxRequestsPerConnection != null) {
        options.setMaxRequestsPerConnection(HostDistance.REMOTE, Integer.parseInt(remoteMaxRequestsPerConnection));
    }
    builder = builder.withPoolingOptions(options);
    return builder;
}
 
Example #17
Source File: CassandraConfig.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private Builder populateSocketOptions(Map<String, String> properties, Builder builder) throws DataServiceFault {
    String connectionTimeoutMillisProp = properties.get(DBConstants.Cassandra.CONNECTION_TIMEOUT_MILLIS);
    String keepAliveProp = properties.get(DBConstants.Cassandra.KEEP_ALIVE);
    String readTimeoutMillisProp = properties.get(DBConstants.Cassandra.READ_TIMEOUT_MILLIS);
    String receiveBufferSizeProp = properties.get(DBConstants.Cassandra.RECEIVER_BUFFER_SIZE);
    String reuseAddress = properties.get(DBConstants.Cassandra.REUSE_ADDRESS);
    String sendBufferSize = properties.get(DBConstants.Cassandra.SEND_BUFFER_SIZE);
    String soLinger = properties.get(DBConstants.Cassandra.SO_LINGER);
    String tcpNoDelay = properties.get(DBConstants.Cassandra.TCP_NODELAY);
    SocketOptions options = new SocketOptions();
    if (connectionTimeoutMillisProp != null) {
        options.setConnectTimeoutMillis(Integer.parseInt(connectionTimeoutMillisProp));
    }
    if (keepAliveProp != null) {
        options.setKeepAlive(Boolean.parseBoolean(keepAliveProp));
    }
    if (readTimeoutMillisProp != null) {
        options.setReadTimeoutMillis(Integer.parseInt(readTimeoutMillisProp));
    }
    if (receiveBufferSizeProp != null) {
        options.setReceiveBufferSize(Integer.parseInt(receiveBufferSizeProp));
    }
    if (reuseAddress != null) {
        options.setReuseAddress(Boolean.parseBoolean(reuseAddress));
    }
    if (sendBufferSize != null) {
        options.setSendBufferSize(Integer.parseInt(sendBufferSize));
    }
    if (soLinger != null) {
        options.setSoLinger(Integer.parseInt(soLinger));
    }
    if (tcpNoDelay != null) {
        options.setTcpNoDelay(Boolean.parseBoolean(tcpNoDelay));
    }
    return builder.withSocketOptions(options);
}
 
Example #18
Source File: BuildCluster.java    From cassandra-jdbc-wrapper with Apache License 2.0 5 votes vote down vote up
public static boolean isClusterActive(){
	try{
		Builder builder = Cluster.builder().withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.QUORUM).setSerialConsistencyLevel(ConsistencyLevel.LOCAL_SERIAL));
		cluster = builder.addContactPoint("127.0.0.1").build();
		session = cluster.connect();
		return true;
	} catch(Exception e){
		return false;			
	}
	
}
 
Example #19
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 #20
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 #21
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 #22
Source File: DatastaxAuthentication.java    From heroic with Apache License 2.0 4 votes vote down vote up
@Override
public void accept(final Builder builder) {
    builder.withAuthProvider(new PlainTextAuthProvider(username, password));
}
 
Example #23
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();
}
 
Example #24
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 #25
Source File: CassandraSessionImpl.java    From newts with Apache License 2.0 4 votes vote down vote up
@Inject
public CassandraSessionImpl(@Named("cassandra.keyspace") String keyspace, @Named("cassandra.hostname") String hostname,
        @Named("cassandra.port") int port, @Named("cassandra.compression") String compression,
        @Named("cassandra.username") String username, @Named("cassandra.password") String password,
        @Named("cassandra.ssl") boolean ssl,
        @Named("cassandra.pool.core-connections-per-host") Integer coreConnectionsPerHost,
        @Named("cassandra.pool.max-connections-per-host") Integer maxConnectionsPerHost,
        @Named("cassandra.pool.max-requests-per-connection") Integer maxRequestsPerConnection) {

    checkNotNull(keyspace, "keyspace argument");
    checkNotNull(hostname, "hostname argument");
    checkArgument(port > 0 && port < 65535, "not a valid port number: %d", port);
    checkNotNull(compression, "compression argument");

    LOG.info("Setting up session with {}:{} using compression {}", hostname, port, compression.toUpperCase());

    final PoolingOptions poolingOptions = new PoolingOptions();
    if (coreConnectionsPerHost != null) {
        LOG.debug("Using {} core connections per host.", coreConnectionsPerHost);
        poolingOptions.setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnectionsPerHost)
                .setCoreConnectionsPerHost(HostDistance.REMOTE, coreConnectionsPerHost);
    }
    if (maxConnectionsPerHost != null) {
        LOG.debug("Using {} max connections per host.", maxConnectionsPerHost);
        poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnectionsPerHost)
                .setMaxConnectionsPerHost(HostDistance.REMOTE, maxConnectionsPerHost);
    }
    if (maxRequestsPerConnection != null) {
        LOG.debug("Using {} max requests per connection.", maxRequestsPerConnection);
        poolingOptions.setMaxRequestsPerConnection(HostDistance.LOCAL, maxRequestsPerConnection)
                .setMaxRequestsPerConnection(HostDistance.REMOTE, maxRequestsPerConnection);
    }

    Builder builder = Cluster
            .builder()
            .withPort(port)
            .addContactPoints(hostname.split(","))
            .withReconnectionPolicy(new ExponentialReconnectionPolicy(1000, 2 * 60 * 1000))
            .withPoolingOptions(poolingOptions)
            .withCompression(Compression.valueOf(compression.toUpperCase()));

    if (username != null && password != null) {
        LOG.info("Using username: {} and password: XXXXXXXX", username);
        builder.withCredentials(username, password);
    }

    if (ssl) {
        LOG.info("Enabling SSL.");
        builder.withSSL();
    }

    m_session = builder.build().connect(keyspace);
}
 
Example #26
Source File: DatastaxAuthentication.java    From heroic with Apache License 2.0 4 votes vote down vote up
@Override
public void accept(Builder builder) {
}
 
Example #27
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 #28
Source File: CCMBridge.java    From cassandra-jdbc-wrapper with Apache License 2.0 4 votes vote down vote up
public static CCMCluster create(CCMBridge cassandraCluster, Cluster.Builder builder, int totalNodes) {
    return new CCMCluster(cassandraCluster, builder, totalNodes);
}
 
Example #29
Source File: CCMBridge.java    From cassandra-jdbc-wrapper with Apache License 2.0 4 votes vote down vote up
public static CCMCluster create(int nbNodesDC1, int nbNodesDC2, Cluster.Builder builder) {
    if (nbNodesDC1 == 0) throw new IllegalArgumentException();

    return new CCMCluster(CCMBridge.create("test", nbNodesDC1, nbNodesDC2), builder, nbNodesDC1 + nbNodesDC2);
}
 
Example #30
Source File: CCMBridge.java    From cassandra-jdbc-wrapper with Apache License 2.0 4 votes vote down vote up
public static CCMCluster create(int nbNodes, Cluster.Builder builder) {
    if (nbNodes == 0) throw new IllegalArgumentException();

    return new CCMCluster(CCMBridge.create("test", nbNodes), builder, nbNodes);
}