com.datastax.driver.core.SocketOptions Java Examples

The following examples show how to use com.datastax.driver.core.SocketOptions. 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: CassandraSocketOptions.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void initOpts() {
    opts = new SocketOptions();
    opts.setConnectTimeoutMillis(connectTimeoutMillis);
    opts.setReadTimeoutMillis(readTimeoutMillis);
    if (keepAlive != null) {
        opts.setKeepAlive(keepAlive);
    }
    if (reuseAddress != null) {
        opts.setReuseAddress(reuseAddress);
    }
    if (soLinger != null) {
        opts.setSoLinger(soLinger);
    }
    if (tcpNoDelay != null) {
        opts.setTcpNoDelay(tcpNoDelay);
    }
    if (receiveBufferSize != null) {
        opts.setReceiveBufferSize(receiveBufferSize);
    }
    if (sendBufferSize != null) {
        opts.setSendBufferSize(sendBufferSize);
    }
}
 
Example #2
Source File: HadoopFormatIOCassandraTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
  cassandraPort = NetworkTestHelper.getAvailableLocalPort();
  cassandraNativePort = NetworkTestHelper.getAvailableLocalPort();
  replacePortsInConfFile();
  // Start the Embedded Cassandra Service
  cassandra.start();
  final SocketOptions socketOptions = new SocketOptions();
  // Setting this to 0 disables read timeouts.
  socketOptions.setReadTimeoutMillis(0);
  // This defaults to 5 s.  Increase to a minute.
  socketOptions.setConnectTimeoutMillis(60 * 1000);
  cluster =
      Cluster.builder()
          .addContactPoint(CASSANDRA_HOST)
          .withClusterName("beam")
          .withSocketOptions(socketOptions)
          .withPort(cassandraNativePort)
          .build();
  session = cluster.connect();
  createCassandraData();
}
 
Example #3
Source File: Sessions.java    From glowroot with Apache License 2.0 6 votes vote down vote up
static Session createSession() throws Exception {
    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1")
            // long read timeout is sometimes needed on slow travis ci machines
            .withSocketOptions(new SocketOptions().setReadTimeoutMillis(30000))
            .withQueryOptions(getQueryOptions())
            .build();
    Session session = cluster.connect();
    session.execute("CREATE KEYSPACE IF NOT EXISTS test WITH REPLICATION ="
            + " { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }");
    session.execute("CREATE TABLE IF NOT EXISTS test.users"
            + " (id int PRIMARY KEY, fname text, lname text)");
    try {
        session.execute("TRUNCATE test.users");
    } catch (NoHostAvailableException e) {
        // sometimes slow, so give it a second chance
        session.execute("TRUNCATE test.users");
    }
    for (int i = 0; i < 10; i++) {
        session.execute("INSERT INTO test.users (id, fname, lname) VALUES (" + i + ", 'f" + i
                + "', 'l" + i + "')");
    }
    return session;
}
 
Example #4
Source File: ClusterCassandraConnectionFactory.java    From embedded-cassandra with Apache License 2.0 5 votes vote down vote up
private Cluster createCluster(Cassandra cassandra) {
	SocketOptions socketOptions = new SocketOptions();
	socketOptions.setConnectTimeoutMillis(30000);
	socketOptions.setReadTimeoutMillis(30000);
	int port = cassandra.getPort();
	int sslPort = cassandra.getSslPort();
	Cluster.Builder builder = Cluster.builder().addContactPoints(cassandra.getAddress())
			.withPort(isSslEnabled() && sslPort != -1 ? sslPort : port)
			.withSocketOptions(socketOptions);
	if (!isMetricsEnabled()) {
		builder.withoutMetrics();
	}
	if (!isJmxEnabled()) {
		builder.withoutJMXReporting();
	}
	String username = getUsername();
	String password = getPassword();
	if (username != null && password != null) {
		builder.withCredentials(username, password);
	}
	if (isSslEnabled()) {
		RemoteEndpointAwareJdkSSLOptions.Builder sslOptionsBuilder = RemoteEndpointAwareJdkSSLOptions.builder();
		if (getKeystore() != null || getTruststore() != null) {
			sslOptionsBuilder.withSSLContext(getSslContext());
		}
		List<String> cipherSuites = getCipherSuites();
		if (!cipherSuites.isEmpty()) {
			sslOptionsBuilder.withCipherSuites(cipherSuites.toArray(new String[0]));
		}
		builder.withSSL(sslOptionsBuilder.build());
	}
	List<TypeCodec<?>> typeCodecs = getTypeCodecs();
	if (!typeCodecs.isEmpty()) {
		builder.withCodecRegistry(new CodecRegistry().register(typeCodecs));
	}
	this.clusterBuilderCustomizers.forEach(customizer -> customizer.accept(builder));
	return builder.build();
}
 
Example #5
Source File: CassandraClusterFactoryJavaConfigTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Bean(name = "my-service")
public Cluster testClusterFactoryWithConfig() {

	CassandraClusterConfig config = new CassandraClusterConfig();
	SocketOptions socketOptions = new SocketOptions();
	socketOptions.setSendBufferSize(12345);
	config.setSocketOptions(socketOptions);

	return connectionFactory().cluster("my-service", config);
}
 
Example #6
Source File: CassandraClusterCreatorTest.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateClusterWithConfig() throws Exception {

	CassandraServiceInfo info = new CassandraServiceInfo("local",
			Collections.singletonList("127.0.0.1"), 9142);

	CassandraClusterConfig config = new CassandraClusterConfig();
	config.setCompression(ProtocolOptions.Compression.NONE);
	config.setPoolingOptions(new PoolingOptions().setPoolTimeoutMillis(1234));
	config.setQueryOptions(new QueryOptions());
	config.setProtocolVersion(ProtocolVersion.NEWEST_SUPPORTED);
	config.setLoadBalancingPolicy(new RoundRobinPolicy());
	config.setReconnectionPolicy(new ConstantReconnectionPolicy(1));
	config.setRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
	config.setSocketOptions(new SocketOptions());

	Cluster cluster = creator.create(info, config);

	Configuration configuration = cluster.getConfiguration();

	assertThat(configuration.getProtocolOptions().getCompression(),
			is(config.getCompression()));
	assertThat(configuration.getQueryOptions(), is(config.getQueryOptions()));
	assertThat(configuration.getSocketOptions(), is(config.getSocketOptions()));

	Policies policies = configuration.getPolicies();
	assertThat(policies.getLoadBalancingPolicy(),
			is(config.getLoadBalancingPolicy()));
	assertThat(policies.getReconnectionPolicy(), is(config.getReconnectionPolicy()));
	assertThat(policies.getRetryPolicy(), is(config.getRetryPolicy()));
}
 
Example #7
Source File: CassandraSessionProvider.java    From nifi with Apache License 2.0 5 votes vote down vote up
private Cluster createCluster(List<InetSocketAddress> contactPoints, SSLContext sslContext,
                              String username, String password, String compressionType,
                              Optional<Integer> readTimeoutMillisOptional, Optional<Integer> connectTimeoutMillisOptional) {
    Cluster.Builder builder = Cluster.builder().addContactPointsWithPorts(contactPoints);

    if (sslContext != null) {
        JdkSSLOptions sslOptions = JdkSSLOptions.builder()
                .withSSLContext(sslContext)
                .build();
        builder = builder.withSSL(sslOptions);
    }

    if (username != null && password != null) {
        builder = builder.withCredentials(username, password);
    }

    if(ProtocolOptions.Compression.SNAPPY.equals(compressionType)) {
        builder = builder.withCompression(ProtocolOptions.Compression.SNAPPY);
    } else if(ProtocolOptions.Compression.LZ4.equals(compressionType)) {
        builder = builder.withCompression(ProtocolOptions.Compression.LZ4);
    }

    SocketOptions socketOptions = new SocketOptions();
    readTimeoutMillisOptional.ifPresent(socketOptions::setReadTimeoutMillis);
    connectTimeoutMillisOptional.ifPresent(socketOptions::setConnectTimeoutMillis);

    builder.withSocketOptions(socketOptions);

    return builder.build();
}
 
Example #8
Source File: CQLService.java    From Doradus with Apache License 2.0 5 votes vote down vote up
private Cluster buildClusterSpecs() {
    Cluster.Builder builder = Cluster.builder();
    
    // dbhost
    String dbhost = getParamString("dbhost");
    String[] nodeAddresses = dbhost.split(",");
    for (String address : nodeAddresses) {
        builder.addContactPoint(address);
    }
    
    // dbport
    builder.withPort(getParamInt("dbport", 9042));
    
    // db_timeout_millis and db_connect_retry_wait_millis
    SocketOptions socketOpts = new SocketOptions();
    socketOpts.setReadTimeoutMillis(getParamInt("db_timeout_millis", 10000));
    socketOpts.setConnectTimeoutMillis(getParamInt("db_connect_retry_wait_millis", 5000));
    builder.withSocketOptions(socketOpts);
    
    // dbuser/dbpassword
    String dbuser = getParamString("dbuser");
    if (!Utils.isEmpty(dbuser)) {
        builder.withCredentials(dbuser, getParamString("dbpassword"));
    }
    
    // compression
    builder.withCompression(Compression.SNAPPY);
    
    // TLS/SSL
    if (getParamBoolean("dbtls")) {
        builder.withSSL(getSSLOptions());
    }
    
    return builder.build();
}
 
Example #9
Source File: MapConfiguredCqlClientFactory.java    From storm-cassandra-cql with Apache License 2.0 5 votes vote down vote up
private void configureSocketOpts() {
    final String readTimeoutConfiguration = (String) configuration.get(TRIDENT_CASSANDRA_READ_TIMEOUT);
    final String connectTimeoutConfiguration = (String) configuration.get(TRIDENT_CASSANDRA_CONNECT_TIMEOUT);
    final SocketOptions socketOptions = builder.getConfiguration().getSocketOptions();

    if (StringUtils.isNotEmpty(readTimeoutConfiguration)) {
        socketOptions.setReadTimeoutMillis(Integer.parseInt(readTimeoutConfiguration));
    }

    if (StringUtils.isNotEmpty(connectTimeoutConfiguration)) {
        socketOptions.setConnectTimeoutMillis(Integer.parseInt(connectTimeoutConfiguration));
    }

    builder = builder.withSocketOptions(socketOptions);
}
 
Example #10
Source File: CqlSession.java    From ob1k with Apache License 2.0 5 votes vote down vote up
public CqlSession(final String nodes, final int port, final String keyspace, final SocketOptions socketOptions,
                  final RetryPolicy retryPolicy, final QueryOptions queryOptions,
                  final LoadBalancingPolicy loadBalancingPolicy, final int maxConnectionsPerHost,
                  final MetricFactory metricFactory) {

  // this is temp. to reuse current hosts properties:
  final Iterable<String> nodesIter = Splitter.on(",").split(nodes);
  final String[] nodesArr = Iterables.toArray(
    StreamSupport.stream(nodesIter.spliterator(), false).map(input -> {
    if (input == null) return null;

    final int idx = input.lastIndexOf(":");
    return input.substring(0, idx);
  }).collect(Collectors.toList()), String.class);


  /*PoolingOptions poolingOptions = new PoolingOptions();
  poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnectionsPerHost);
  poolingOptions.setMaxConnectionsPerHost(HostDistance.REMOTE, maxConnectionsPerHost);*/


  final Cluster cluster = Cluster.builder().
          withPort(port).
          withSocketOptions(socketOptions).
          withQueryOptions(queryOptions).
          withLoadBalancingPolicy(loadBalancingPolicy).
          //  withPoolingOptions(poolingOptions).
                  addContactPoints(nodesArr).build();
  //cluster.init();
  this.session = cluster.connect(keyspace);
  this.retryPolicy = Preconditions.checkNotNull(retryPolicy);
  this.metricFactory = Preconditions.checkNotNull(metricFactory);
}
 
Example #11
Source File: CqlConfigHelper.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private static SocketOptions getReadSocketOptions(Configuration conf)
{
    SocketOptions socketOptions = new SocketOptions();
    Optional<Integer> connectTimeoutMillis = getInputNativeConnectionTimeout(conf);
    Optional<Integer> readTimeoutMillis = getInputNativeReadConnectionTimeout(conf);
    Optional<Integer> receiveBufferSize = getInputNativeReceiveBufferSize(conf);
    Optional<Integer> sendBufferSize = getInputNativeSendBufferSize(conf);
    Optional<Integer> soLinger = getInputNativeSolinger(conf);
    Optional<Boolean> tcpNoDelay = getInputNativeTcpNodelay(conf);
    Optional<Boolean> reuseAddress = getInputNativeReuseAddress(conf);       
    Optional<Boolean> keepAlive = getInputNativeKeepAlive(conf);

    if (connectTimeoutMillis.isPresent())
        socketOptions.setConnectTimeoutMillis(connectTimeoutMillis.get());
    if (readTimeoutMillis.isPresent())
        socketOptions.setReadTimeoutMillis(readTimeoutMillis.get());
    if (receiveBufferSize.isPresent())
        socketOptions.setReceiveBufferSize(receiveBufferSize.get());
    if (sendBufferSize.isPresent())
        socketOptions.setSendBufferSize(sendBufferSize.get());
    if (soLinger.isPresent())
        socketOptions.setSoLinger(soLinger.get());
    if (tcpNoDelay.isPresent())
        socketOptions.setTcpNoDelay(tcpNoDelay.get());
    if (reuseAddress.isPresent())
        socketOptions.setReuseAddress(reuseAddress.get());
    if (keepAlive.isPresent())
        socketOptions.setKeepAlive(keepAlive.get());     

    return socketOptions;
}
 
Example #12
Source File: CqlConfigHelper.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static Cluster getInputCluster(String[] hosts, Configuration conf)
{
    int port = getInputNativePort(conf);
    Optional<AuthProvider> authProvider = getAuthProvider(conf);
    Optional<SSLOptions> sslOptions = getSSLOptions(conf);
    Optional<Integer> protocolVersion = getProtocolVersion(conf);
    LoadBalancingPolicy loadBalancingPolicy = getReadLoadBalancingPolicy(conf, hosts);
    SocketOptions socketOptions = getReadSocketOptions(conf);
    QueryOptions queryOptions = getReadQueryOptions(conf);
    PoolingOptions poolingOptions = getReadPoolingOptions(conf);
    
    Cluster.Builder builder = Cluster.builder()
                                     .addContactPoints(hosts)
                                     .withPort(port)
                                     .withCompression(ProtocolOptions.Compression.NONE);

    if (authProvider.isPresent())
        builder.withAuthProvider(authProvider.get());
    if (sslOptions.isPresent())
        builder.withSSL(sslOptions.get());

    if (protocolVersion.isPresent()) {
        builder.withProtocolVersion(protocolVersion.get());
    }
    builder.withLoadBalancingPolicy(loadBalancingPolicy)
           .withSocketOptions(socketOptions)
           .withQueryOptions(queryOptions)
           .withPoolingOptions(poolingOptions);

    return builder.build();
}
 
Example #13
Source File: Clusters.java    From glowroot with Apache License 2.0 5 votes vote down vote up
static Cluster newCluster() {
    return Cluster.builder().addContactPoint("127.0.0.1")
            // long read timeout is sometimes needed on slow travis ci machines
            .withSocketOptions(new SocketOptions().setReadTimeoutMillis(30000))
            // let driver know that only idempotent queries are used so it will retry on timeout
            .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
            .build();
}
 
Example #14
Source File: ClusterFactory.java    From james-project with Apache License 2.0 5 votes vote down vote up
public static Cluster create(ClusterConfiguration configuration) {
    Preconditions.checkState(configuration.getUsername().isPresent() == configuration.getPassword().isPresent(), "If you specify username, you must specify password");

    Cluster.Builder clusterBuilder = Cluster.builder()
        .withoutJMXReporting();
    configuration.getHosts().forEach(server -> clusterBuilder
        .addContactPoint(server.getHostName())
        .withPort(server.getPort()));

    configuration.getUsername().ifPresent(username ->
        configuration.getPassword().ifPresent(password ->
            clusterBuilder.withCredentials(username, password)));

    clusterBuilder.withQueryOptions(queryOptions());

    SocketOptions socketOptions = new SocketOptions();
    socketOptions.setReadTimeoutMillis(configuration.getReadTimeoutMillis());
    socketOptions.setConnectTimeoutMillis(configuration.getConnectTimeoutMillis());
    clusterBuilder.withSocketOptions(socketOptions);
    clusterBuilder.withRetryPolicy(new LogConsistencyAllRetryPolicy());
    configuration.getPoolingOptions().ifPresent(clusterBuilder::withPoolingOptions);

    if (configuration.useSsl()) {
        clusterBuilder.withSSL();
    }

    Cluster cluster = clusterBuilder.build();
    try {
        configuration.getQueryLoggerConfiguration().map(queryLoggerConfiguration ->
            cluster.register(queryLoggerConfiguration.getQueryLogger()));
        ensureContactable(cluster);
        return cluster;
    } catch (Exception e) {
        cluster.close();
        throw e;
    }
}
 
Example #15
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 #16
Source File: DataSource.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    fetchSize = (Integer)in.readObject();
    readConsistency = (ConsistencyLevel)in.readObject();
    writeConsistency = (ConsistencyLevel)in.readObject();
    user = U.readString(in);
    pwd = U.readString(in);
    port = (Integer)in.readObject();
    contactPoints = (List<InetAddress>)in.readObject();
    contactPointsWithPorts = (List<InetSocketAddress>)in.readObject();
    maxSchemaAgreementWaitSeconds = (Integer)in.readObject();
    protoVer = (Integer)in.readObject();
    compression = U.readString(in);
    useSSL = (Boolean)in.readObject();
    collectMetrix = (Boolean)in.readObject();
    jmxReporting = (Boolean)in.readObject();
    creds = (Credentials)in.readObject();
    loadBalancingPlc = (LoadBalancingPolicy)readObject(in);
    reconnectionPlc = (ReconnectionPolicy)readObject(in);
    addrTranslator = (AddressTranslator)readObject(in);
    speculativeExecutionPlc = (SpeculativeExecutionPolicy)readObject(in);
    authProvider = (AuthProvider)readObject(in);
    sslOptions = (SSLOptions)readObject(in);
    poolingOptions = (PoolingOptions)readObject(in);
    sockOptions = (SocketOptions)readObject(in);
    nettyOptions = (NettyOptions)readObject(in);
}
 
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: ManagedSetupConnection.java    From heroic with Apache License 2.0 5 votes vote down vote up
public AsyncFuture<Connection> construct() {
    AsyncFuture<Session> session = async.call(() -> {


        final QueryOptions queryOptions = new QueryOptions()
            .setFetchSize(fetchSize)
            .setConsistencyLevel(consistencyLevel);

        final SocketOptions socketOptions = new SocketOptions()
            .setReadTimeoutMillis((int) readTimeout.toMilliseconds());

        final Cluster.Builder cluster = Cluster.builder()
            .addContactPointsWithPorts(seeds)
            .withRetryPolicy(retryPolicy)
            .withQueryOptions(queryOptions)
            .withSocketOptions(socketOptions)
            .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
            .withoutJMXReporting();

        authentication.accept(cluster);
        poolingOptions.apply(cluster);

        return cluster.build().connect();
    });

    if (configure) {
        session = session.lazyTransform(s -> schema.configure(s).directTransform(i -> s));
    }

    return session.lazyTransform(
        s -> schema.instance(s).directTransform(schema -> new Connection(s, schema)));
}
 
Example #19
Source File: ReaperCassandraIT.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
private static Cluster buildCluster() {
  return Cluster.builder()
      .addContactPoint("127.0.0.1")
      .withSocketOptions(new SocketOptions().setConnectTimeoutMillis(20000).setReadTimeoutMillis(40000))
      .withoutJMXReporting()
      .build();
}
 
Example #20
Source File: ReaperCassandraSidecarIT.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
private static Cluster buildCluster() {
  return Cluster.builder()
      .addContactPoint("127.0.0.1")
      .withSocketOptions(new SocketOptions().setConnectTimeoutMillis(20000).setReadTimeoutMillis(40000))
      .withoutJMXReporting()
      .build();
}
 
Example #21
Source File: BasicSteps.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
private static Cluster buildCluster() {
  return Cluster.builder()
      .addContactPoint("127.0.0.1")
      .withSocketOptions(new SocketOptions().setConnectTimeoutMillis(20000).setReadTimeoutMillis(40000))
      .withoutJMXReporting()
      .build();
}
 
Example #22
Source File: CassandraConfiguration.java    From tutorials with MIT License 4 votes vote down vote up
private SocketOptions getSocketOptions(CassandraProperties properties) {
    SocketOptions options = new SocketOptions();
    options.setConnectTimeoutMillis(properties.getConnectTimeoutMillis());
    options.setReadTimeoutMillis(properties.getReadTimeoutMillis());
    return options;
}
 
Example #23
Source File: CassandraConfig.java    From realtime-analytics with GNU General Public License v2.0 4 votes vote down vote up
public Builder createBuilder() {
    Builder builder = Cluster.builder();
    for (String address : contactPoints) {
        builder.addContactPoint(address);
    }
    builder.withCompression(compression);
    if (username != null && password != null) {
        builder.withCredentials(username, password);
    }
 
    if (reconnectionPolicy != null) {
        builder.withReconnectionPolicy(reconnectionPolicy);
    }

    if (retryPolicy != null) {
        builder.withRetryPolicy(retryPolicy);
    }
    builder.withPort(port);

    if (!jmxEnabled) {
        builder.withoutJMXReporting();
    }

    if (!metricsEnabled) {
        builder.withoutMetrics();
    }

    if (sslOptions != null) {
        builder.withSSL(sslOptions);
    }

    copyPoolingOptions(builder);

    SocketOptions opts = new SocketOptions();
    opts.setConnectTimeoutMillis(connectTimeoutMillis);
    opts.setReadTimeoutMillis(readTimeoutMillis);

    if (receiveBufferSize != null) {
        opts.setReceiveBufferSize(receiveBufferSize);
    }
    if (sendBufferSize != null) {
        opts.setSendBufferSize(sendBufferSize);
    }
    if (soLinger != null) {
        opts.setSoLinger(soLinger);
    }
    if (keepAlive != null) {
        opts.setKeepAlive(keepAlive);
    }
    if (reuseAddress != null) {
        opts.setReuseAddress(reuseAddress);
    }
    if (tcpNoDelay != null) {
        opts.setTcpNoDelay(tcpNoDelay);
    }

    builder.withSocketOptions(opts);
    return builder;
}
 
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: CassandraClusterConfig.java    From spring-cloud-connectors with Apache License 2.0 4 votes vote down vote up
public void setSocketOptions(SocketOptions socketOptions) {
	this.socketOptions = socketOptions;
}
 
Example #26
Source File: CassandraClusterConfig.java    From spring-cloud-connectors with Apache License 2.0 4 votes vote down vote up
public SocketOptions getSocketOptions() {
	return socketOptions;
}
 
Example #27
Source File: AppBase.java    From yb-sample-apps with Apache License 2.0 4 votes vote down vote up
/**
 * Private method that is thread-safe and creates the Cassandra client. Exactly one calling thread
 * will succeed in creating the client. This method does nothing for the other threads.
 * @param contactPoints list of contact points for the client.
 */
protected synchronized void createCassandraClient(List<ContactPoint> contactPoints) {
  Cluster.Builder builder;
  if (cassandra_cluster == null) {
    builder = Cluster.builder();
    if (appConfig.dbUsername != null) {
      if (appConfig.dbPassword == null) {
        throw new IllegalArgumentException("Password required when providing a username");
      }
      builder = builder
          .withCredentials(appConfig.dbUsername, appConfig.dbPassword);
    }
    if (appConfig.sslCert != null) {
      builder = builder
          .withSSL(createSSLHandler(appConfig.sslCert));
    }
    Integer port = null;
    SocketOptions socketOptions = new SocketOptions();
    if (appConfig.cqlConnectTimeoutMs > 0) {
      socketOptions.setConnectTimeoutMillis(appConfig.cqlConnectTimeoutMs);
    }
    if (appConfig.cqlReadTimeoutMs > 0) {
      socketOptions.setReadTimeoutMillis(appConfig.cqlReadTimeoutMs);
    }
    builder.withSocketOptions(socketOptions);
    for (ContactPoint cp : contactPoints) {
      if (port == null) {
        port = cp.getPort();
        builder.withPort(port);
      } else if (port != cp.getPort()) {
        throw new IllegalArgumentException("Using multiple CQL ports is not supported.");
      }
      builder.addContactPoint(cp.getHost());
    }
    LOG.info("Connecting with " + appConfig.concurrentClients + " clients to nodes: "
        + builder.getContactPoints()
            .stream().map(it -> it.toString()).collect(Collectors.joining(",")));
    PoolingOptions poolingOptions = new PoolingOptions();
    poolingOptions
        .setCoreConnectionsPerHost(HostDistance.LOCAL, appConfig.concurrentClients)
        .setMaxConnectionsPerHost(HostDistance.LOCAL, appConfig.concurrentClients)
        .setCoreConnectionsPerHost(HostDistance.REMOTE, appConfig.concurrentClients)
        .setMaxConnectionsPerHost(HostDistance.REMOTE, appConfig.concurrentClients);
    cassandra_cluster =
        builder.withLoadBalancingPolicy(getLoadBalancingPolicy())
               .withPoolingOptions(poolingOptions)
               .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
               .withRetryPolicy(new LoggingRetryPolicy(DefaultRetryPolicy.INSTANCE))
               .build();
    LOG.debug("Connected to cluster: " + cassandra_cluster.getClusterName());
  }
  if (cassandra_session == null) {
    LOG.debug("Creating a session...");
    cassandra_session = cassandra_cluster.connect();
    createKeyspace(cassandra_session, keyspace);
  }
}
 
Example #28
Source File: CassandraSession.java    From eventapis with Apache License 2.0 4 votes vote down vote up
private SocketOptions getSocketOptions() {
    SocketOptions options = new SocketOptions();
    options.setConnectTimeoutMillis(this.eventStoreConfig.getConnectTimeoutMillis());
    options.setReadTimeoutMillis(this.eventStoreConfig.getReadTimeoutMillis());
    return options;
}
 
Example #29
Source File: CassandraConfiguration.java    From emodb with Apache License 2.0 4 votes vote down vote up
private com.datastax.driver.core.Cluster.Builder newCqlDriverBuilder(ConnectionPoolConfiguration poolConfig,
                                                                     MetricRegistry metricRegistry) {
    performHostDiscovery(metricRegistry);

    String[] seeds = _seeds.split(",");
    List<String> contactPoints = Lists.newArrayListWithCapacity(seeds.length);

    // Each seed may be a host name or a host name and port (e.g.; "1.2.3.4" or "1.2.3.4:9160").  These need
    // to be converted into host names only.
    for (String seed : seeds) {
        HostAndPort hostAndPort = HostAndPort.fromString(seed);
        seed = hostAndPort.getHostText();
        if (hostAndPort.hasPort()) {
            if (hostAndPort.getPort() == _thriftPort) {
                _log.debug("Seed {} found using RPC port; swapping for native port {}", seed, _cqlPort);
            } else if (hostAndPort.getPort() != _cqlPort) {
                throw new IllegalArgumentException(String.format(
                        "Seed %s found with invalid port %s.  The port must match either the RPC (thrift) port %s " +
                        "or the native (CQL) port %s", seed, hostAndPort.getPort(), _thriftPort, _cqlPort));
            }
        }

        contactPoints.add(seed);
    }

    PoolingOptions poolingOptions = new PoolingOptions();
    if (poolConfig.getMaxConnectionsPerHost().or(getMaxConnectionsPerHost()).isPresent()) {
        poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, poolConfig.getMaxConnectionsPerHost().or(getMaxConnectionsPerHost()).get());
    }
    if (poolConfig.getCoreConnectionsPerHost().or(getCoreConnectionsPerHost()).isPresent()) {
        poolingOptions.setCoreConnectionsPerHost(HostDistance.LOCAL, poolConfig.getCoreConnectionsPerHost().or(getCoreConnectionsPerHost()).get());
    }

    SocketOptions socketOptions = new SocketOptions();
    if (poolConfig.getConnectTimeout().or(getConnectTimeout()).isPresent()) {
        socketOptions.setConnectTimeoutMillis(poolConfig.getConnectTimeout().or(getConnectTimeout()).get());
    }
    if (poolConfig.getSocketTimeout().or(getSocketTimeout()).isPresent()) {
        socketOptions.setReadTimeoutMillis(poolConfig.getSocketTimeout().or(getSocketTimeout()).get());
    }

    AuthProvider authProvider = _authenticationCredentials != null
            ? new PlainTextAuthProvider(_authenticationCredentials.getUsername(), _authenticationCredentials.getPassword())
            : AuthProvider.NONE;

    return com.datastax.driver.core.Cluster.builder()
            .addContactPoints(contactPoints.toArray(new String[contactPoints.size()]))
            .withPort(_cqlPort)
            .withPoolingOptions(poolingOptions)
            .withSocketOptions(socketOptions)
            .withRetryPolicy(Policies.defaultRetryPolicy())
            .withAuthProvider(authProvider);
}
 
Example #30
Source File: CassandraIO.java    From beam with Apache License 2.0 4 votes vote down vote up
/** Get a Cassandra cluster using hosts and port. */
private static Cluster getCluster(
    ValueProvider<List<String>> hosts,
    ValueProvider<Integer> port,
    ValueProvider<String> username,
    ValueProvider<String> password,
    ValueProvider<String> localDc,
    ValueProvider<String> consistencyLevel,
    ValueProvider<Integer> connectTimeout,
    ValueProvider<Integer> readTimeout) {

  Cluster.Builder builder =
      Cluster.builder().addContactPoints(hosts.get().toArray(new String[0])).withPort(port.get());

  if (username != null) {
    builder.withAuthProvider(new PlainTextAuthProvider(username.get(), password.get()));
  }

  DCAwareRoundRobinPolicy.Builder dcAwarePolicyBuilder = new DCAwareRoundRobinPolicy.Builder();
  if (localDc != null) {
    dcAwarePolicyBuilder.withLocalDc(localDc.get());
  }

  builder.withLoadBalancingPolicy(new TokenAwarePolicy(dcAwarePolicyBuilder.build()));

  if (consistencyLevel != null) {
    builder.withQueryOptions(
        new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf(consistencyLevel.get())));
  }

  SocketOptions socketOptions = new SocketOptions();

  builder.withSocketOptions(socketOptions);

  if (connectTimeout != null) {
    socketOptions.setConnectTimeoutMillis(connectTimeout.get());
  }

  if (readTimeout != null) {
    socketOptions.setReadTimeoutMillis(readTimeout.get());
  }

  return builder.build();
}