Java Code Examples for com.datastax.driver.core.SocketOptions#setConnectTimeoutMillis()
The following examples show how to use
com.datastax.driver.core.SocketOptions#setConnectTimeoutMillis() .
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 |
@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 |
@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: CassandraConfig.java From micro-integrator with Apache License 2.0 | 5 votes |
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 4
Source File: ClusterCassandraConnectionFactory.java From embedded-cassandra with Apache License 2.0 | 5 votes |
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: CassandraTarget.java From datacollector with Apache License 2.0 | 5 votes |
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 6
Source File: ClusterFactory.java From james-project with Apache License 2.0 | 5 votes |
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 7
Source File: CqlConfigHelper.java From stratio-cassandra with Apache License 2.0 | 5 votes |
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 8
Source File: MapConfiguredCqlClientFactory.java From storm-cassandra-cql with Apache License 2.0 | 5 votes |
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 9
Source File: CQLService.java From Doradus with Apache License 2.0 | 5 votes |
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 10
Source File: CassandraFactory.java From database-transform-tool with Apache License 2.0 | 4 votes |
/** * 描述: 初始化配置 * 时间: 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 11
Source File: AppBase.java From yb-sample-apps with Apache License 2.0 | 4 votes |
/** * 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 12
Source File: CassandraSession.java From eventapis with Apache License 2.0 | 4 votes |
private SocketOptions getSocketOptions() { SocketOptions options = new SocketOptions(); options.setConnectTimeoutMillis(this.eventStoreConfig.getConnectTimeoutMillis()); options.setReadTimeoutMillis(this.eventStoreConfig.getReadTimeoutMillis()); return options; }
Example 13
Source File: CassandraConfiguration.java From emodb with Apache License 2.0 | 4 votes |
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 14
Source File: CassandraIO.java From beam with Apache License 2.0 | 4 votes |
/** 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(); }
Example 15
Source File: CassandraConfig.java From realtime-analytics with GNU General Public License v2.0 | 4 votes |
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 16
Source File: CassandraConfiguration.java From tutorials with MIT License | 4 votes |
private SocketOptions getSocketOptions(CassandraProperties properties) { SocketOptions options = new SocketOptions(); options.setConnectTimeoutMillis(properties.getConnectTimeoutMillis()); options.setReadTimeoutMillis(properties.getReadTimeoutMillis()); return options; }