com.netflix.astyanax.AstyanaxContext Java Examples

The following examples show how to use com.netflix.astyanax.AstyanaxContext. 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: CassandraMutagenImplTest.java    From mutagen-cassandra with Apache License 2.0 6 votes vote down vote up
private static void defineKeyspace() {
		context=new AstyanaxContext.Builder()
			.forKeyspace("mutagen_test")
			.withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
//					.setDiscoveryType(NodeDiscoveryType.RING_DESCRIBE)
//					.setCqlVersion("3.0.0")
//					.setTargetCassandraVersion("1.2")
				.setDefaultReadConsistencyLevel(ConsistencyLevel.CL_QUORUM)
				.setDefaultWriteConsistencyLevel(ConsistencyLevel.CL_QUORUM)
			)
			.withConnectionPoolConfiguration(
				new ConnectionPoolConfigurationImpl("testPool")
				.setPort(9160)
				.setMaxConnsPerHost(1)
				.setSeeds("localhost")
			)
			.withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
			.buildKeyspace(ThriftFamilyFactory.getInstance());

		context.start();
		keyspace=context.getClient();
	}
 
Example #2
Source File: Migration.java    From blueflood with Apache License 2.0 6 votes vote down vote up
private static AstyanaxContext<Keyspace> connect(String host, int port, String keyspace, int threads, NodeDiscoveryType discovery) {
    AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder()
                    .forKeyspace(keyspace)
            .withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
                .setDiscoveryType(discovery)
                .setRetryPolicy(new RetryNTimes(10)))
                
            .withConnectionPoolConfiguration(new ConnectionPoolConfigurationImpl(host + ":" + keyspace)
                    .setMaxConns(threads * 2)
                    .setSeeds(host)
                    .setPort(port)
                    .setRetryBackoffStrategy(new FixedRetryBackoffStrategy(1000, 1000)))
            .withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
            .buildKeyspace(ThriftFamilyFactory.getInstance());
    context.start();
    return context;
}
 
Example #3
Source File: AstyanaxSupport.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
public AstyanaxContext<Keyspace> newAstyanaxContextForKeyspace(String keyspace) {
    AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder()
            .forCluster(clusterName)
            .forKeyspace(keyspace)
            .withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
                    .setDiscoveryType(NodeDiscoveryType.NONE))
            .withConnectionPoolConfiguration(new ConnectionPoolConfigurationImpl("BrooklynPool")
                    .setPort(thriftPort)
                    .setMaxConnsPerHost(1)
                    .setConnectTimeout(5000) // 10s
                    .setSeeds(String.format("%s:%d", hostname, thriftPort)))
            .withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
            .buildKeyspace(ThriftFamilyFactory.getInstance());

    context.start();
    return context;
}
 
Example #4
Source File: AstyanaxSupport.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
public AstyanaxContext<Cluster> newAstyanaxContextForCluster() {
    AstyanaxContext<Cluster> context = new AstyanaxContext.Builder()
            .forCluster(clusterName)
            .withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
                    .setDiscoveryType(NodeDiscoveryType.NONE))
            .withConnectionPoolConfiguration(new ConnectionPoolConfigurationImpl("BrooklynPool")
                    .setPort(thriftPort)
                    .setMaxConnsPerHost(1)
                    .setConnectTimeout(5000) // 10s
                    .setSeeds(String.format("%s:%d", hostname, thriftPort)))
            .withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
            .buildCluster(ThriftFamilyFactory.getInstance());

    context.start();
    return context;
}
 
Example #5
Source File: DefaultAstyanaxClusterClientProvider.java    From staash with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized Cluster acquireCluster(ClusterKey clusterKey) {
    String clusterName = clusterKey.getClusterName().toLowerCase();
    Preconditions.checkNotNull(clusterName, "Invalid cluster name 'null'");
    
    ClusterContextHolder holder = contextMap.get(clusterName);
    if (holder == null) {
        HostSupplierProvider hostSupplierProvider = hostSupplierProviders.get(clusterKey.getDiscoveryType());
        Preconditions.checkNotNull(hostSupplierProvider, String.format("Unknown host supplier provider '%s' for cluster '%s'", clusterKey.getDiscoveryType(), clusterName));
        
        AstyanaxContext<Cluster> context = new AstyanaxContext.Builder()
            .forCluster(clusterName)
            .withAstyanaxConfiguration(configurationProvider.get(clusterName))
            .withConnectionPoolConfiguration(cpProvider.get(clusterName))
            .withConnectionPoolMonitor(monitorProvider.get(clusterName))
            .withHostSupplier(hostSupplierProvider.getSupplier(clusterName))
            .buildCluster(ThriftFamilyFactory.getInstance());
        
        holder = new ClusterContextHolder(context);
        holder.start();
    }
    holder.addRef();
    
    return holder.getKeyspace();
}
 
Example #6
Source File: InstanceDataDAOCassandra.java    From Raigad with Apache License 2.0 6 votes vote down vote up
private AstyanaxContext<Keyspace> initWithThriftDriverWithEurekaHostsSupplier() {
    logger.info("Boot cluster (BOOT_CLUSTER) is {}, keyspace name (KS_NAME) is {}", BOOT_CLUSTER, KS_NAME);

    return new AstyanaxContext.Builder()
            .forCluster(BOOT_CLUSTER)
            .forKeyspace(KS_NAME)
            .withAstyanaxConfiguration(
                    new AstyanaxConfigurationImpl()
                            .setDiscoveryType(
                                    NodeDiscoveryType.DISCOVERY_SERVICE))
            .withConnectionPoolConfiguration(
                    new ConnectionPoolConfigurationImpl(
                            "MyConnectionPool")
                            .setMaxConnsPerHost(3)
                            .setPort(thriftPortForAstyanax))
            .withHostSupplier(eurekaHostsSupplier.getSupplier(BOOT_CLUSTER))
            .withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
            .buildKeyspace(ThriftFamilyFactory.getInstance());

}
 
Example #7
Source File: InstanceDataDAOCassandra.java    From Raigad with Apache License 2.0 6 votes vote down vote up
private AstyanaxContext<Keyspace> initWithThriftDriverWithExternalHostsSupplier() {
    logger.info("Boot cluster (BOOT_CLUSTER) is {}, keyspace name (KS_NAME) is {}", BOOT_CLUSTER, KS_NAME);

    return new AstyanaxContext.Builder()
            .forCluster(BOOT_CLUSTER)
            .forKeyspace(KS_NAME)
            .withAstyanaxConfiguration(
                    new AstyanaxConfigurationImpl()
                            .setDiscoveryType(
                                    NodeDiscoveryType.DISCOVERY_SERVICE)
                            .setConnectionPoolType(
                                    ConnectionPoolType.ROUND_ROBIN))
            .withConnectionPoolConfiguration(
                    new ConnectionPoolConfigurationImpl(
                            "MyConnectionPool")
                            .setMaxConnsPerHost(3)
                            .setPort(thriftPortForAstyanax))
            .withHostSupplier(getSupplier())
            .withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
            .buildKeyspace(ThriftFamilyFactory.getInstance());

}
 
Example #8
Source File: TestChunking.java    From staash with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
	AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder()
			.forCluster("Test Cluster")
			.forKeyspace(KS)
			.withAstyanaxConfiguration(
					new AstyanaxConfigurationImpl()
							.setDiscoveryType(NodeDiscoveryType.RING_DESCRIBE))
			.withConnectionPoolConfiguration(
					new ConnectionPoolConfigurationImpl("MyConnectionPool")
							.setPort(9160).setMaxConnsPerHost(1)
							.setSeeds("127.0.0.1:9160"))
			.withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
			.buildKeyspace(ThriftFamilyFactory.getInstance());

	context.start();
	keyspace = context.getClient();
}
 
Example #9
Source File: PaasPropertiesModule.java    From staash with Apache License 2.0 5 votes vote down vote up
@Provides
@Named("astmetaks")
Keyspace provideKeyspace(@Named("staash.metacluster") String clustername,EurekaAstyanaxHostSupplier hs) {
    String clusterNameOnly = "";
    String[] clusterinfo = clustername.split(":");
    if (clusterinfo != null && clusterinfo.length == 2) {
        clusterNameOnly = clusterinfo[0];
    } else {
        clusterNameOnly = clustername;
    }
    AstyanaxContext<Keyspace> keyspaceContext = new AstyanaxContext.Builder()
    .forCluster(clusterNameOnly)
    .forKeyspace(MetaConstants.META_KEY_SPACE)
    .withAstyanaxConfiguration(
            new AstyanaxConfigurationImpl()
                    .setDiscoveryType(
                            NodeDiscoveryType.RING_DESCRIBE)
                    .setConnectionPoolType(
                            ConnectionPoolType.TOKEN_AWARE)
                    .setDiscoveryDelayInSeconds(60)
                    .setTargetCassandraVersion("1.2")
                    .setCqlVersion("3.0.0"))
                    .withHostSupplier(hs.getSupplier(clustername))
    .withConnectionPoolConfiguration(
            new ConnectionPoolConfigurationImpl(clusterNameOnly
                    + "_" + MetaConstants.META_KEY_SPACE)
                    .setSocketTimeout(11000)
                    .setConnectTimeout(2000)
                    .setMaxConnsPerHost(10).setInitConnsPerHost(3))
    .withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
    .buildKeyspace(ThriftFamilyFactory.getInstance());
    keyspaceContext.start();
    Keyspace keyspace;
    keyspace = keyspaceContext.getClient();
    return keyspace;
}
 
Example #10
Source File: CassandraStoreImpl.java    From recipes-rss with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to Cassandra
 */
private static Keyspace getKeyspace() throws Exception{
    if (ks == null) {
        try {
            AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder()
                .forKeyspace(DynamicPropertyFactory.getInstance().getStringProperty(RSSConstants.CASSANDRA_KEYSPACE, null).get())
                .withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
                    .setDiscoveryType(NodeDiscoveryType.RING_DESCRIBE)
                )
                .withConnectionPoolConfiguration(new ConnectionPoolConfigurationImpl("MyConnectionPool")
                    .setPort(DynamicPropertyFactory.getInstance().getIntProperty(RSSConstants.CASSANDRA_PORT, 0).get())
                    .setMaxConnsPerHost(DynamicPropertyFactory.getInstance().getIntProperty(RSSConstants.CASSANDRA_MAXCONNSPERHOST, 1).get())
                    .setSeeds(DynamicPropertyFactory.getInstance().getStringProperty(RSSConstants.CASSANDRA_HOST, "").get() + ":" +
                              DynamicPropertyFactory.getInstance().getIntProperty(RSSConstants.CASSANDRA_PORT, 0).get()
                    )
                )
                .withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
                .buildKeyspace(ThriftFamilyFactory.getInstance());

            context.start();
            ks = context.getEntity();
        } catch (Exception e) {
            logger.error("Exception occurred when initializing Cassandra keyspace: " + e);
            throw e;
        }
    }

    return ks;
}
 
Example #11
Source File: CassandraClusterImpl.java    From usergrid with Apache License 2.0 5 votes vote down vote up
private AstyanaxContext<Cluster> getCluster ( final String clusterName,
                                              final AstyanaxConfiguration astyanaxConfiguration,
                                              final ConnectionPoolConfiguration poolConfig ) {

    return new AstyanaxContext.Builder().forCluster( clusterName )
        .withAstyanaxConfiguration( astyanaxConfiguration )
        .withConnectionPoolConfiguration( poolConfig )
        .withConnectionPoolMonitor( new Slf4jConnectionPoolMonitorImpl())
        .buildCluster( ThriftFamilyFactory.getInstance() );

}
 
Example #12
Source File: AstyanaxIO.java    From blueflood with Apache License 2.0 5 votes vote down vote up
private static AstyanaxContext<Keyspace> createCustomHostContext(AstyanaxConfigurationImpl configuration,
        ConnectionPoolConfigurationImpl connectionPoolConfiguration) {
    return new AstyanaxContext.Builder()
            .forCluster(CassandraModel.CLUSTER)
            .forKeyspace(CassandraModel.KEYSPACE)
            .withAstyanaxConfiguration(configuration)
            .withConnectionPoolConfiguration(connectionPoolConfiguration)
            .withConnectionPoolMonitor(new InstrumentedConnectionPoolMonitor())
            .buildKeyspace(ThriftFamilyFactory.getInstance());
}
 
Example #13
Source File: DefaultKeyspaceClientProvider.java    From staash with Apache License 2.0 5 votes vote down vote up
@Override
public Keyspace acquireKeyspace(KeyspaceKey key) {
    String schemaName = key.getSchemaName().toLowerCase();
    
    Preconditions.checkNotNull(schemaName, "Invalid schema name 'null'");
    
    KeyspaceContextHolder holder = contextMap.get(schemaName);
    if (holder == null) {
        Preconditions.checkNotNull(key.getClusterName(),   "Missing cluster name for schema " + schemaName);
        Preconditions.checkNotNull(key.getKeyspaceName(),  "Missing cluster name for schema " + schemaName);
        Preconditions.checkNotNull(key.getDiscoveryType(), "Missing cluster name for schema " + schemaName);
        
        HostSupplierProvider hostSupplierProvider = hostSupplierProviders.get(key.getDiscoveryType());
        Preconditions.checkNotNull(hostSupplierProvider, "Unknown host supplier provider " + key.getDiscoveryType());
        
        AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder()
            .forCluster(key.getClusterName())
            .forKeyspace(key.getKeyspaceName())
            .withAstyanaxConfiguration(configurationProvider.get(schemaName))
            .withConnectionPoolConfiguration(cpProvider.get(schemaName))
            .withConnectionPoolMonitor(monitorProvider.get(schemaName))
            .withHostSupplier(hostSupplierProvider.getSupplier(key.getClusterName()))
            .buildKeyspace(ThriftFamilyFactory.getInstance());
        
        holder = new KeyspaceContextHolder(context);
        contextMap.put(schemaName, holder);
        holder.start();
    }
    holder.addRef();
    
    return holder.getKeyspace();
}
 
Example #14
Source File: CassandraClusterHolder.java    From staash with Apache License 2.0 5 votes vote down vote up
/**
 * Register a keyspace such that a client is created for it and it is now accessible to 
 * this instance
 * 
 * @param keyspaceName
 * @throws AlreadyExistsException
 */
public synchronized void registerKeyspace(String keyspaceName) throws AlreadyExistsException {
    Preconditions.checkNotNull(keyspaceName);
    
    if (keyspaces.containsKey(keyspaceName)) {
        throw new AlreadyExistsException("keyspace", keyspaceName);
    }
    
    CassandraKeyspaceHolder keyspace = new CassandraKeyspaceHolder(new AstyanaxContext.Builder()
            .forCluster(clusterName)
            .forKeyspace(keyspaceName)
            .withAstyanaxConfiguration(
                    new AstyanaxConfigurationImpl()
                            .setDiscoveryType(NodeDiscoveryType.RING_DESCRIBE)
                            .setConnectionPoolType(ConnectionPoolType.ROUND_ROBIN)
                            .setDiscoveryDelayInSeconds(60000))
            .withConnectionPoolConfiguration(
                    new ConnectionPoolConfigurationImpl(
                            clusterName + "_" + keyspaceName)
                            .setSeeds("localhost:9160"))
            .withConnectionPoolMonitor(new Slf4jConnectionPoolMonitorImpl())
            .buildKeyspace(ThriftFamilyFactory.getInstance()));
    
    try {
        keyspace.initialize();
    }
    finally {
        keyspaces.put(keyspaceName, keyspace);
    }
}
 
Example #15
Source File: CassandraStorage.java    From greycat with Apache License 2.0 5 votes vote down vote up
public CassandraStorage(String keySpace) {
    context = new AstyanaxContext.Builder()
            .forKeyspace(keySpace)
            .withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
                    .setDiscoveryType(NodeDiscoveryType.RING_DESCRIBE)
            )
            .withConnectionPoolConfiguration(new ConnectionPoolConfigurationImpl("MyConnectionPool")
                    .setMaxConnsPerHost(1)
                    .setSeeds("127.0.0.1:9160")
            )
            .withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
            .buildKeyspace(ThriftFamilyFactory.getInstance());
}
 
Example #16
Source File: TestStaashModule.java    From staash with Apache License 2.0 5 votes vote down vote up
@Provides
    @Named("astmetaks")
    @Singleton
    Keyspace provideKeyspace() {
         AstyanaxContext<Keyspace> keyspaceContext = new AstyanaxContext.Builder()
        .forCluster("test cluster")
        .forKeyspace(MetaConstants.META_KEY_SPACE)
        .withAstyanaxConfiguration(
                new AstyanaxConfigurationImpl()
                        .setDiscoveryType(
                                NodeDiscoveryType.NONE)
                        .setConnectionPoolType(
                                ConnectionPoolType.ROUND_ROBIN)
                        .setTargetCassandraVersion("1.2")
                        .setCqlVersion("3.0.0"))
//                        .withHostSupplier(hs.getSupplier(clustername))
        .withConnectionPoolConfiguration(
                new ConnectionPoolConfigurationImpl("localpool"
                        + "_" + MetaConstants.META_KEY_SPACE)
                        .setSocketTimeout(30000)
                        .setMaxTimeoutWhenExhausted(20000)
                        .setMaxConnsPerHost(3).setInitConnsPerHost(1)
                        .setSeeds("localhost"+":"+"9160"))  //uncomment for localhost
//        .withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
        .buildKeyspace(ThriftFamilyFactory.getInstance());
        keyspaceContext.start();
        Keyspace keyspace;
        keyspace = keyspaceContext.getClient();
        return keyspace;
    }
 
Example #17
Source File: CassandraDatacenterLiveTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
protected static Boolean areVersionsConsistent(CassandraNode node) {
    AstyanaxContext<Cluster> context = null;
    try {
        context = new AstyanaxSample(node).newAstyanaxContextForCluster();
        Map<String, List<String>> v = context.getEntity().describeSchemaVersions();
        return v.size() == 1;
    } catch (Exception e) {
        return null;
    } finally {
        if (context != null) context.shutdown();
    }
}
 
Example #18
Source File: AstyanaxSupport.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    AstyanaxSample support = new AstyanaxSample("ignored", "ec2-79-125-32-2.eu-west-1.compute.amazonaws.com", 9160);
    AstyanaxContext<Cluster> context = support.newAstyanaxContextForCluster();
    try {
        System.out.println(context.getEntity().describeSchemaVersions());
    } finally {
        context.shutdown();
    }
}
 
Example #19
Source File: AstyanaxSupport.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
/**
 * Read from a {@link CassandraNode} using the Astyanax API.
 * @throws ConnectionException 
 */
public void readData(String keyspaceName) throws ConnectionException {
    // Create context
    AstyanaxContext<Keyspace> context = newAstyanaxContextForKeyspace(keyspaceName);
    try {
        Keyspace keyspace = context.getEntity();

        // Query data
        OperationResult<ColumnList<String>> query = keyspace.prepareQuery(sampleColumnFamily)
                .getKey("one")
                .execute();
        assertEquals(query.getHost().getHostName(), hostname);
        assertTrue(query.getLatency() > 0L);

        ColumnList<String> columns = query.getResult();
        assertEquals(columns.size(), 2);

        // Lookup columns in response by name
        String name = columns.getColumnByName("name").getStringValue();
        assertEquals(name, "Alice");

        // Iterate through the columns
        for (Column<String> c : columns) {
            assertTrue(ImmutableList.of("name", "company").contains(c.getName()));
        }
    } finally {
        context.shutdown();
    }
}
 
Example #20
Source File: CassandraConfiguration.java    From emodb with Apache License 2.0 5 votes vote down vote up
public AstyanaxCluster cluster() {
    checkNotNull(_cluster, "cluster");
    String metricName;
    ConnectionPoolConfiguration poolConfig;

    if (_keyspace == null) {
        // Use the shared pool configuration
        metricName = Objects.firstNonNull(_clusterMetric, _cluster);
        poolConfig = CassandraConfiguration.this;
    } else {
        // Use the configuration specifically for this keyspace
        KeyspaceConfiguration keyspaceConfig = checkNotNull(_keyspaces.get(_keyspace), "keyspaceConfig");
        metricName = Objects.firstNonNull(keyspaceConfig.getKeyspaceMetric(), _keyspace);
        poolConfig = keyspaceConfig;
    }

    AstyanaxContext.Builder builder = newAstyanaxBuilder(_cluster, poolConfig, _metricRegistry)
            .forCluster(_cluster);

    if (!_disableClusterMetrics) {
            builder = builder
                    .withTracerFactory(new InstrumentedTracerFactory(metricName, _metricRegistry))
                    .withConnectionPoolMonitor(new MetricConnectionPoolMonitor(metricName, _metricRegistry));
    }

    AstyanaxContext<Cluster> astyanaxContext = builder.buildCluster(ThriftFamilyFactory.getInstance());

    return new AstyanaxCluster(astyanaxContext, _cluster, _dataCenter);
}
 
Example #21
Source File: AstyanaxCassandraConnection.java    From staash with Apache License 2.0 4 votes vote down vote up
private Keyspace createAstyanaxKeyspace(String clustername, String db,
		EurekaAstyanaxHostSupplier supplier) {
	String clusterNameOnly = "localhost";
	String clusterPortOnly = "9160";
	String[] clusterinfo = clustername.split(":");
	if (clusterinfo != null && clusterinfo.length == 2) {
		clusterNameOnly = clusterinfo[0];
	} else {
		clusterNameOnly = clustername;
	}
	AstyanaxContext<Keyspace> keyspaceContext;
	if (supplier!=null) {
	keyspaceContext = new AstyanaxContext.Builder()
			.forCluster("Casss_Paas")
			.forKeyspace(db)
			.withAstyanaxConfiguration(
					new AstyanaxConfigurationImpl()
							.setDiscoveryType(
									NodeDiscoveryType.DISCOVERY_SERVICE)
							.setConnectionPoolType(
									ConnectionPoolType.TOKEN_AWARE)
							.setDiscoveryDelayInSeconds(60)
							.setTargetCassandraVersion("1.2")
							.setCqlVersion("3.0.0"))
			.withHostSupplier(supplier.getSupplier(clustername))
			.withConnectionPoolConfiguration(
					new ConnectionPoolConfigurationImpl(clusterNameOnly
							+ "_" + db)
							.setSocketTimeout(10000)
							.setPort(7102)
							.setMaxConnsPerHost(10).setInitConnsPerHost(3)
							.setSeeds(null))
			.withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
			.buildKeyspace(ThriftFamilyFactory.getInstance());
	} else {
		keyspaceContext = new AstyanaxContext.Builder()
        .forCluster(clusterNameOnly)
        .forKeyspace(db)
        .withAstyanaxConfiguration(
                new AstyanaxConfigurationImpl()
                        .setDiscoveryType(
                                NodeDiscoveryType.RING_DESCRIBE)
                        .setConnectionPoolType(
                                ConnectionPoolType.TOKEN_AWARE)
                        .setDiscoveryDelayInSeconds(60)
                        .setTargetCassandraVersion("1.2")
                        .setCqlVersion("3.0.0"))
                        //.withHostSupplier(hs.getSupplier(clustername))
        .withConnectionPoolConfiguration(
                new ConnectionPoolConfigurationImpl(clusterNameOnly
                        + "_" + db)
                        .setSocketTimeout(11000)
                        .setConnectTimeout(2000)
                        .setMaxConnsPerHost(10).setInitConnsPerHost(3)	 
                      .setSeeds(clusterNameOnly+":"+clusterPortOnly))
         .buildKeyspace(ThriftFamilyFactory.getInstance());
	}
	keyspaceContext.start();
	Keyspace keyspace;
	keyspace = keyspaceContext.getClient();
	return keyspace;
}
 
Example #22
Source File: TestPaasPropertiesModule.java    From staash with Apache License 2.0 4 votes vote down vote up
@Provides
    @Named("astmetaks")
    @Singleton
    Keyspace provideKeyspace(@Named("paas.metacluster") String clustername) {
        String clusterNameOnly = "";
        String clusterPortOnly = "";
        String[] clusterinfo = clustername.split(":");
        if (clusterinfo != null && clusterinfo.length == 2) {
            clusterNameOnly = clusterinfo[0];
            clusterPortOnly = clusterinfo[1];
        } else {
            clusterNameOnly = clustername;
            clusterPortOnly = "9160";
        }
//        hs = new EurekaAstyanaxHostSupplier();
        AstyanaxContext<Keyspace> keyspaceContext = new AstyanaxContext.Builder()
        .forCluster(clusterNameOnly)
        .forKeyspace(MetaConstants.META_KEY_SPACE)
        .withAstyanaxConfiguration(
                new AstyanaxConfigurationImpl()
                        .setDiscoveryType(
                                NodeDiscoveryType.RING_DESCRIBE)
                        .setConnectionPoolType(
                                ConnectionPoolType.TOKEN_AWARE)
                        .setDiscoveryDelayInSeconds(60000)
                        .setTargetCassandraVersion("1.1")
                        .setCqlVersion("3.0.0"))
//                        .withHostSupplier(hs.getSupplier(clustername))
        .withConnectionPoolConfiguration(
                new ConnectionPoolConfigurationImpl(clusterNameOnly
                        + "_" + MetaConstants.META_KEY_SPACE)
                        .setSocketTimeout(3000)
                        .setMaxTimeoutWhenExhausted(2000)
                        .setMaxConnsPerHost(3).setInitConnsPerHost(1)
                        .setSeeds(clusterNameOnly+":"+clusterPortOnly))  //uncomment for localhost
        .withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
        .buildKeyspace(ThriftFamilyFactory.getInstance());
        keyspaceContext.start();
        Keyspace keyspace;
        keyspace = keyspaceContext.getClient();
        return keyspace;
    }
 
Example #23
Source File: CassandraKeyspaceHolder.java    From staash with Apache License 2.0 4 votes vote down vote up
public CassandraKeyspaceHolder(AstyanaxContext<Keyspace> context) {
    this.context = context;
}
 
Example #24
Source File: DefaultAstyanaxClusterClientProvider.java    From staash with Apache License 2.0 4 votes vote down vote up
public ClusterContextHolder(AstyanaxContext<Cluster> context) {
    this.context = context;
}
 
Example #25
Source File: DefaultKeyspaceClientProvider.java    From staash with Apache License 2.0 4 votes vote down vote up
public KeyspaceContextHolder(AstyanaxContext<Keyspace> context) {
    this.context = context;
}
 
Example #26
Source File: DefaultKeyspaceClientProvider.java    From staash with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized Keyspace acquireKeyspace(String schemaName) {
    schemaName = schemaName.toLowerCase();
    
    Preconditions.checkNotNull(schemaName, "Invalid schema name 'null'");
    
    KeyspaceContextHolder holder = contextMap.get(schemaName);
    if (holder == null) {
        LOG.info("Creating schema for '{}'", new Object[]{schemaName});
        
        String clusterName   = configuration.getString(String.format(CLUSTER_NAME_FORMAT,   schemaName));
        String keyspaceName  = configuration.getString(String.format(KEYSPACE_NAME__FORMAT, schemaName));
        String discoveryType = configuration.getString(String.format(DISCOVERY_TYPE_FORMAT, schemaName));
        if (clusterName==null || clusterName.equals("")) clusterName   = configuration.getString(String.format(CLUSTER_NAME_FORMAT,   "configuration"));
        if (keyspaceName == null || keyspaceName.equals("")) keyspaceName = schemaName;
        if (discoveryType==null || discoveryType.equals("")) discoveryType = configuration.getString(String.format(DISCOVERY_TYPE_FORMAT, "configuration"));
        Preconditions.checkNotNull(clusterName,   "Missing cluster name for schema " + schemaName + " " + String.format(CLUSTER_NAME_FORMAT,schemaName));
        Preconditions.checkNotNull(keyspaceName,  "Missing cluster name for schema " + schemaName + " " + String.format(KEYSPACE_NAME__FORMAT,schemaName));
        Preconditions.checkNotNull(discoveryType, "Missing cluster name for schema " + schemaName + " " + String.format(DISCOVERY_TYPE_FORMAT,schemaName));
        
        HostSupplierProvider hostSupplierProvider = hostSupplierProviders.get(discoveryType);
        Preconditions.checkNotNull(hostSupplierProvider, 
                String.format("Unknown host supplier provider '%s' for schema '%s'", discoveryType, schemaName));
        
        AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder()
            .forCluster(clusterName)
            .forKeyspace(keyspaceName)
            .withAstyanaxConfiguration(configurationProvider.get(schemaName))
            .withConnectionPoolConfiguration(cpProvider.get(schemaName))
            .withConnectionPoolMonitor(monitorProvider.get(schemaName))
            .withHostSupplier(hostSupplierProvider.getSupplier(clusterName))
            .buildKeyspace(ThriftFamilyFactory.getInstance());
        context.start();
        try {
            context.getClient().createKeyspace(defaultKsOptions);
        } catch (ConnectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        holder = new KeyspaceContextHolder(context);
        contextMap.put(schemaName, holder);
        holder.start();
    }
    holder.addRef();
    
    return holder.getKeyspace();
}
 
Example #27
Source File: AstyanaxStoreManager.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
private AstyanaxContext.Builder getContextBuilder(Configuration config, int maxConnsPerHost, String usedFor) {

        final ConnectionPoolType poolType = ConnectionPoolType.valueOf(config.get(CONNECTION_POOL_TYPE));

        final NodeDiscoveryType discType = NodeDiscoveryType.valueOf(config.get(NODE_DISCOVERY_TYPE));

        final int maxConnections = config.get(MAX_CONNECTIONS);

        final int maxOperationsPerConnection = config.get(MAX_OPERATIONS_PER_CONNECTION);

        final int connectionTimeout = (int) connectionTimeoutMS.toMillis();

        ConnectionPoolConfigurationImpl cpool =
                new ConnectionPoolConfigurationImpl(usedFor + "TitanConnectionPool")
                        .setPort(port)
                        .setMaxOperationsPerConnection(maxOperationsPerConnection)
                        .setMaxConnsPerHost(maxConnsPerHost)
                        .setRetryDelaySlice(retryDelaySlice)
                        .setRetryMaxDelaySlice(retryMaxDelaySlice)
                        .setRetrySuspendWindow(retrySuspendWindow)
                        .setSocketTimeout(connectionTimeout)
                        .setConnectTimeout(connectionTimeout)
                        .setSeeds(StringUtils.join(hostnames, ","));

        if (null != retryBackoffStrategy) {
            cpool.setRetryBackoffStrategy(retryBackoffStrategy);
            log.debug("Custom RetryBackoffStrategy {}", cpool.getRetryBackoffStrategy());
        } else {
            log.debug("Default RetryBackoffStrategy {}", cpool.getRetryBackoffStrategy());
        }

        if (StringUtils.isNotBlank(localDatacenter)) {
            cpool.setLocalDatacenter(localDatacenter);
            log.debug("Set local datacenter: {}", cpool.getLocalDatacenter());
        }

        AstyanaxConfigurationImpl aconf =
                new AstyanaxConfigurationImpl()
                        .setConnectionPoolType(poolType)
                        .setDiscoveryType(discType)
                        .setTargetCassandraVersion("1.2")
                        .setMaxThriftSize(thriftFrameSizeBytes);

        if (0 < maxConnections) {
            cpool.setMaxConns(maxConnections);
        }

        if (hasAuthentication()) {
            cpool.setAuthenticationCredentials(new SimpleAuthenticationCredentials(username, password));
        }

        if (config.get(SSL_ENABLED)) {
            cpool.setSSLConnectionContext(new SSLConnectionContext(config.get(SSL_TRUSTSTORE_LOCATION), config.get(SSL_TRUSTSTORE_PASSWORD)));
        }

        AstyanaxContext.Builder ctxBuilder = new AstyanaxContext.Builder();

        // Standard context builder options
        ctxBuilder
            .forCluster(clusterName)
            .forKeyspace(keySpaceName)
            .withAstyanaxConfiguration(aconf)
            .withConnectionPoolConfiguration(cpool)
            .withConnectionPoolMonitor(new CountingConnectionPoolMonitor());

        // Conditional context builder option: host supplier
        if (config.has(HOST_SUPPLIER)) {
            String hostSupplier = config.get(HOST_SUPPLIER);
            Supplier<List<Host>> supplier = null;
            if (hostSupplier != null) {
                try {
                    supplier = (Supplier<List<Host>>) Class.forName(hostSupplier).newInstance();
                    ctxBuilder.withHostSupplier(supplier);
                } catch (Exception e) {
                    log.warn("Problem with host supplier class " + hostSupplier + ", going to use default.", e);
                }
            }
        }

        return ctxBuilder;
    }
 
Example #28
Source File: AstyanaxStoreManager.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
private static AstyanaxContext<Cluster> createCluster(AstyanaxContext.Builder cb) {
    AstyanaxContext<Cluster> clusterCtx = cb.buildCluster(ThriftFamilyFactory.getInstance());
    clusterCtx.start();

    return clusterCtx;
}
 
Example #29
Source File: AstyanaxIO.java    From blueflood with Apache License 2.0 4 votes vote down vote up
private static AstyanaxContext<Keyspace> createPreferredHostContext() {
    return createCustomHostContext(createPreferredAstyanaxConfiguration(), createPreferredConnectionPoolConfiguration());
}
 
Example #30
Source File: AstyanaxCluster.java    From emodb with Apache License 2.0 4 votes vote down vote up
public AstyanaxCluster(AstyanaxContext<Cluster> astyanaxContext, String clusterName, String dataCenter) {
    super(clusterName, dataCenter);
    _astyanaxContext = astyanaxContext;
}