com.datastax.driver.core.policies.RoundRobinPolicy Java Examples

The following examples show how to use com.datastax.driver.core.policies.RoundRobinPolicy. 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: Application.java    From cassandra-exporter with Apache License 2.0 6 votes vote down vote up
private Cluster establishClusterConnection() {
    final Cluster.Builder clusterBuilder = Cluster.builder()
            .addContactPointsWithPorts(cqlAddress)
            .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), ImmutableList.of(cqlAddress)));

    if (cqlUser != null ^ cqlPassword != null) {
        throw new ParameterException(commandSpec.commandLine(), "Both --cql-user and --cql-password are required when either is used.");
    }

    if (cqlUser != null && cqlPassword != null) {
        clusterBuilder.withCredentials(cqlUser, cqlPassword);
    }

    final Cluster cluster = clusterBuilder.build();

    cluster.connect();

    return cluster;
}
 
Example #2
Source File: IgnitePersistentStoreTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
private IgniteConfiguration igniteConfig() throws IOException {
    URL url = getClass().getClassLoader().getResource("org/apache/ignite/tests/persistence/pojo/persistence-settings-3.xml");
    String persistence = U.readFileToString(url.getFile(), "UTF-8");

    KeyValuePersistenceSettings persistenceSettings = new KeyValuePersistenceSettings(persistence);

    DataSource dataSource = new DataSource();
    dataSource.setContactPoints(CassandraHelper.getContactPointsArray());
    dataSource.setCredentials(new CassandraAdminCredentials());
    dataSource.setLoadBalancingPolicy(new RoundRobinPolicy());

    CassandraCacheStoreFactory<String, Person> storeFactory = new CassandraCacheStoreFactory<>();
    storeFactory.setDataSource(dataSource);
    storeFactory.setPersistenceSettings(persistenceSettings);

    CacheConfiguration<String, Person> cacheConfiguration = new CacheConfiguration<>();
    cacheConfiguration.setName("cache1");
    cacheConfiguration.setReadThrough(true);
    cacheConfiguration.setWriteThrough(true);
    cacheConfiguration.setCacheStoreFactory(storeFactory);

    IgniteConfiguration config = new IgniteConfiguration();
    config.setCacheConfiguration(cacheConfiguration);

    return config;
}
 
Example #3
Source File: CassandraClusterXmlConfigTest.java    From spring-cloud-connectors with Apache License 2.0 6 votes vote down vote up
@Test
public void cassandraSessionWithConfiguration() throws Exception {
	ApplicationContext testContext = getTestApplicationContext(
			"cloud-cassandra-with-config.xml", createService("my-service"));
	Cluster cluster = testContext.getBean("cassandra-full-config",
			getConnectorType());

	assertNotNull(cluster.getConfiguration().getSocketOptions());
	assertEquals(15000,
			cluster.getConfiguration().getSocketOptions().getConnectTimeoutMillis());
	assertTrue(DefaultRetryPolicy.class.isAssignableFrom(
			cluster.getConfiguration().getPolicies().getRetryPolicy().getClass()));
	assertTrue(RoundRobinPolicy.class.isAssignableFrom(cluster.getConfiguration()
			.getPolicies().getLoadBalancingPolicy().getClass()));
	assertTrue(ConstantReconnectionPolicy.class.isAssignableFrom(cluster
			.getConfiguration().getPolicies().getReconnectionPolicy().getClass()));
}
 
Example #4
Source File: CQLSession.java    From cassandra-sidecar with Apache License 2.0 5 votes vote down vote up
@Inject
public CQLSession(Configuration configuration)
{
    inet = InetSocketAddress.createUnresolved(configuration.getCassandraHost(), configuration.getCassandraPort());
    wlp = new WhiteListPolicy(new RoundRobinPolicy(), Collections.singletonList(inet));
    this.nettyOptions = new NettyOptions();
    this.queryOptions = new QueryOptions().setConsistencyLevel(ConsistencyLevel.ONE);
    this.reconnectionPolicy = new ExponentialReconnectionPolicy(1000,
                                                                configuration.getHealthCheckFrequencyMillis());
}
 
Example #5
Source File: CQLSession.java    From cassandra-sidecar with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
CQLSession(InetSocketAddress target, NettyOptions options)
{
    inet = target;
    wlp = new WhiteListPolicy(new RoundRobinPolicy(), Collections.singletonList(inet));
    this.nettyOptions = options;
    this.queryOptions = new QueryOptions().setConsistencyLevel(ConsistencyLevel.ONE);
    reconnectionPolicy = new ExponentialReconnectionPolicy(100, 1000);
}
 
Example #6
Source File: CassandraDbProvider.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Currently we connect just once and then reuse the connection.
 * We do not bother with closing the connection.
 *
 * It is normal to use one Session per DB. The Session is thread safe.
 */
private void connect() {

    if (cluster == null) {

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

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

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

    }

    if (session == null) {

        log.info("Connecting to Cassandra DB with name " + this.dbName);
        session = cluster.connect(dbName);
    }
}
 
Example #7
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 #8
Source File: UtilsUnitTest.java    From cassandra-jdbc-wrapper with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadBalancingPolicyParsing() throws Exception
{
	String lbPolicyStr = "RoundRobinPolicy()";
	System.out.println(lbPolicyStr);
	assertTrue(Utils.parseLbPolicy(lbPolicyStr) instanceof RoundRobinPolicy);
	System.out.println("====================");
	lbPolicyStr = "TokenAwarePolicy(RoundRobinPolicy())";
	System.out.println(lbPolicyStr);
	assertTrue(Utils.parseLbPolicy(lbPolicyStr) instanceof TokenAwarePolicy);
	System.out.println("====================");
	lbPolicyStr = "DCAwareRoundRobinPolicy(\"dc1\")";
	System.out.println(lbPolicyStr);
	assertTrue(Utils.parseLbPolicy(lbPolicyStr) instanceof DCAwareRoundRobinPolicy);
	System.out.println("====================");
	lbPolicyStr = "TokenAwarePolicy(DCAwareRoundRobinPolicy(\"dc1\"))";
	System.out.println(lbPolicyStr);
	assertTrue(Utils.parseLbPolicy(lbPolicyStr) instanceof TokenAwarePolicy);    	
	System.out.println("====================");
	lbPolicyStr = "TokenAwarePolicy";
	System.out.println(lbPolicyStr);
	assertTrue(Utils.parseLbPolicy(lbPolicyStr)==null);
	System.out.println("====================");
	lbPolicyStr = "LatencyAwarePolicy(TokenAwarePolicy(RoundRobinPolicy()),(double) 10.5,(long) 1,(long) 10,(long)1,10)";    	
	System.out.println(lbPolicyStr);
	assertTrue(Utils.parseLbPolicy(lbPolicyStr) instanceof LatencyAwarePolicy);
	System.out.println("====================");    	    	
	
}
 
Example #9
Source File: BackplaneConfiguration.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void initialize() {
    String cassandraHosts = env.getProperty("ea.cassandra.hosts","localhost:9042");
    String cassandraClusterName = env.getProperty("ea.cassandra.cluster","ElasticActorsCluster");
    String cassandraKeyspaceName = env.getProperty("ea.cassandra.keyspace","\"ElasticActors\"");
    Integer cassandraPort = env.getProperty("ea.cassandra.port", Integer.class, 9042);

    Set<String> hostSet = StringUtils.commaDelimitedListToSet(cassandraHosts);

    String[] contactPoints = new String[hostSet.size()];
    int i=0;
    for (String host : hostSet) {
        if(host.contains(":")) {
            contactPoints[i] = host.substring(0,host.indexOf(":"));
        } else {
            contactPoints[i] = host;
        }
        i+=1;
    }

    PoolingOptions poolingOptions = new PoolingOptions();
    poolingOptions.setHeartbeatIntervalSeconds(60);
    poolingOptions.setConnectionsPerHost(HostDistance.LOCAL, 2, env.getProperty("ea.cassandra.maxActive",Integer.class,Runtime.getRuntime().availableProcessors() * 3));
    poolingOptions.setPoolTimeoutMillis(2000);

    Cluster cassandraCluster =
            Cluster.builder().withClusterName(cassandraClusterName)
                    .addContactPoints(contactPoints)
                    .withPort(cassandraPort)
            .withLoadBalancingPolicy(new RoundRobinPolicy())
            .withRetryPolicy(new LoggingRetryPolicy(DefaultRetryPolicy.INSTANCE))
            .withPoolingOptions(poolingOptions)
            .withReconnectionPolicy(new ConstantReconnectionPolicy(env.getProperty("ea.cassandra.retryDownedHostsDelayInSeconds",Integer.class,1) * 1000))
            .withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.QUORUM)).build();

    this.cassandraSession = cassandraCluster.connect(cassandraKeyspaceName);

    
}
 
Example #10
Source File: RoundRobinPolicyFactoryTest.java    From dropwizard-cassandra with Apache License 2.0 5 votes vote down vote up
@Test
public void buildsPolicy() throws Exception {
    final RoundRobinPolicyFactory factory = new RoundRobinPolicyFactory();

    final LoadBalancingPolicy policy = factory.build();

    assertThat(policy).isExactlyInstanceOf(RoundRobinPolicy.class);
}
 
Example #11
Source File: CQLService.java    From Doradus with Apache License 2.0 5 votes vote down vote up
private void displayClusterInfo() {
    Metadata metadata = m_cluster.getMetadata();
    m_logger.info("Connected to cluster with topography:");
    RoundRobinPolicy policy = new RoundRobinPolicy();
    for (Host host : metadata.getAllHosts()) {
        m_logger.info("   Host {}: datacenter: {}, rack: {}, distance: {}",
                      new Object[]{host.getAddress(), host.getDatacenter(), 
            host.getRack(), policy.distance(host)});
    }
    m_logger.info("Database contains {} keyspaces", metadata.getKeyspaces().size());
}
 
Example #12
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 #13
Source File: PaasPropertiesModule.java    From staash with Apache License 2.0 5 votes vote down vote up
@Provides
@Named("pooledmetacluster")
Cluster providePooledCluster(@Named("staash.cassclient") String clientType,@Named("staash.metacluster") String clustername) {
    if (clientType.equals("cql")) {
    Cluster cluster = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())).addContactPoint(clustername).build();
    return cluster;
    }else {
        return null;
    }
}
 
Example #14
Source File: TestPaasPropertiesModule.java    From staash with Apache License 2.0 5 votes vote down vote up
@Provides
    @Named("pooledmetacluster")
    Cluster providePooledCluster(@Named("paas.cassclient") String clientType,@Named("paas.metacluster") String clustername) {
        if (clientType.equals("cql")) {
        Cluster cluster = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())).addContactPoint(clustername).build();
//        Cluster cluster = Cluster.builder().addContactPoint(clustername).build();
        return cluster;
        }else {
            return null;
        }
    }
 
Example #15
Source File: CassandraAppender.java    From cassandra-log4j-appender with Apache License 2.0 4 votes vote down vote up
private synchronized void initClient()
   {
       // We should be able to go without an Atomic variable here.  There are two potential problems:
       // 1. Multiple threads read intialized=false and call init client.  However, the method is
       //    synchronized so only one will get the lock first, and the others will drop out here.
       // 2. One thread reads initialized=true before initClient finishes.  This also should not
       //    happen as the lock should include a memory barrier.
       if (initialized || initializationFailed)
           return;

	// Just while we initialise the client, we must temporarily
	// disable all logging or else we get into an infinite loop
	Level globalThreshold = LogManager.getLoggerRepository().getThreshold();
	LogManager.getLoggerRepository().setThreshold(Level.OFF);

	try
       {
           Cluster.Builder builder = Cluster.builder()
                                            .addContactPoints(hosts.split(",\\s*"))
                                            .withPort(port)
                                            .withLoadBalancingPolicy(new RoundRobinPolicy());

           // Kerberos provides authentication anyway, so a username and password are superfluous.  SSL
           // is compatible with either.
           boolean passwordAuthentication = !password.equals("") || !username.equals("");
           if (authProviderOptions != null && passwordAuthentication)
               throw new IllegalArgumentException("Authentication via both Cassandra usernames and Kerberos " +
                                                  "requested.");

           // Encryption
           if (authProviderOptions != null)
               builder = builder.withAuthProvider(getAuthProvider());
           if (sslOptions != null)
               builder = builder.withSSL(getSslOptions());
           if (passwordAuthentication)
               builder = builder.withCredentials(username, password);

           cluster = builder.build();
	    session = cluster.connect();
           setupSchema();
           setupStatement();
	}
       catch (Exception e)
       {
	    LogLog.error("Error ", e);
		errorHandler.error("Error setting up cassandra logging schema: " + e);

           //If the user misconfigures the port or something, don't keep failing.
           initializationFailed = true;
	}
       finally
       {
           //Always reenable logging
           LogManager.getLoggerRepository().setThreshold(globalThreshold);
           initialized = true;
	}
}
 
Example #16
Source File: RoundRobinPolicyFactory.java    From dropwizard-cassandra with Apache License 2.0 4 votes vote down vote up
@Override
public LoadBalancingPolicy build() {
    return new RoundRobinPolicy();
}
 
Example #17
Source File: CassandraTransactionalRestartRead.java    From yb-sample-apps with Apache License 2.0 4 votes vote down vote up
protected void setupLoadBalancingPolicy(Cluster.Builder builder) {
  builder.withLoadBalancingPolicy(new RoundRobinPolicy());
}