Introduction
Although cqlsh is useful for direct interaction, production applications require a more robust connection strategy. The community-provided SDKs (DataStax drivers) handle complex tasks such as connecting to multiple nodes, balancing requests across each Cassandra node, and managing connection pools. This topic shows how to use these SDKs to connect your application to an ApsaraDB for Cassandra cluster.
Prerequisites
- Obtain connection endpoints.
-
In the ApsaraDB for Cassandra console, navigate to the Database Connection page.
- For security, access from the public network is disabled by default. To obtain a public endpoint, click Apply for Public Endpoint. In the left-side navigation pane, click Database Connection. The Connection Information page displays the internal endpoint, which ends with
.cassandra.rds.aliyuncs.com, and the CQL Port, which is9042by default.Note The number of available endpoints varies with the cluster size. If multiple endpoints are provided, use all of them to ensure high availability in case a node fails. The connection method for the public network and internal network is the same; only the endpoints differ.
-
- Configure a whitelist.
Before connecting, add your client's IP address to the whitelist. For more information, see Configure a whitelist.
Multi-language code examples
- Add the Maven dependency.
<dependency> <groupId>com.datastax.cassandra</groupId> <artifactId>cassandra-driver-core</artifactId> <version>3.7.2</version> </dependency>Important This dependency includes several common libraries. To avoid potential dependency conflicts, we recommend testing it in a new project first. - Write the Java connection code.
import com.datastax.driver.core.Cluster; import com.datastax.driver.core.PlainTextAuthProvider; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Session; public class Demo { public static void main(String[] args) { // Specify the public or internal endpoints. Provide all endpoints listed in the console. // The SDK establishes a control connection with the first available endpoint in the list. Providing multiple endpoints prevents connection failure if a single node is down. // You do not need to worry about the order of the endpoints. The SDK shuffles the list to distribute control connections from different clients. // Do not mix public and internal endpoints in the same list. String[] contactPoints = new String[]{ "cds-xxxxxxxx-core-003.cassandra.rds.aliyuncs.com", "cds-xxxxxxxx-core-002.cassandra.rds.aliyuncs.com" }; Cluster cluster = Cluster.builder() .addContactPoints(contactPoints) // Provide the username and password. If you forget the password, you can reset it on the Account Management page. .withAuthProvider(new PlainTextAuthProvider("cassandra", "123456")) // If connecting over the public network, append the @public suffix to your username to use the public network connection. // Otherwise, you may not be able to connect to all internal nodes and may experience exceptions or slow performance, which can affect local development and debugging. // In the future, the SDK will support automatic network detection, removing the need to manually add @public. Check the official changelog for updates. //.withAuthProvider(new PlainTextAuthProvider("cassandra@public", "123456")) .build(); // Initializes the cluster and establishes a control connection. You can skip this step because it is automatically called when a session is created. cluster.init(); // Connects to the cluster and establishes a persistent connection pool for each Cassandra node. // This is a resource-intensive operation. Do not create a new session for every request. As a best practice, create and reuse one or more sessions per process. // Typically, one session is sufficient. You can adjust this based on your application's needs, such as managing separate sessions for read and write operations. Session session = cluster.connect(); // Execute a query. This example queries the system_auth.roles table to list all created roles. // This is a system table. By default, only the 'cassandra' superuser has SELECT permission. // If you use a different account for testing, query a different table or grant the necessary permissions to your account. ResultSet res = session.execute("SELECT * FROM system_auth.roles"); // The ResultSet object implements the Iterable interface, so you can directly print each row to the console. res.forEach(System.out::println); // Close the session. session.close(); // Close the cluster. cluster.close(); } }
- Install the SDK.
# Install a specific version (version 3.x is recommended). pip install cassandra-driver==3.19.0 # Install the latest version. pip install cassandra-driver # https://pypi.org/project/cassandra-driver/#history - Write the Python connection code.
#!/usr/bin/env python # -*- coding: UTF-8 -*- import logging import sys from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider logging.basicConfig(stream=sys.stdout, level=logging.INFO) cluster = Cluster( # Specify the public or internal endpoints. Provide all endpoints listed in the console. # The SDK establishes a control connection with the first available endpoint in the list. Providing multiple endpoints prevents connection failure if a single node is down. # You do not need to worry about the order of the endpoints. The SDK shuffles the list to distribute control connections from different clients. # Do not mix public and internal endpoints in the same list. contact_points=["cds-xxxxxxxx-core-003.cassandra.rds.aliyuncs.com", "cds-xxxxxxxx-core-002.cassandra.rds.aliyuncs.com"], # Provide the username and password. If you forget the password, you can reset it on the Account Management page. auth_provider=PlainTextAuthProvider("cassandra", "123456")) # If connecting over the public network, append the @public suffix to your username to use the public network connection. # Otherwise, you may not be able to connect to all internal nodes and may experience exceptions or slow performance, which can affect local development and debugging. # In the future, the SDK will support automatic network detection, removing the need to manually add @public. Check the official changelog for updates. # auth_provider=PlainTextAuthProvider("cassandra@public", "123456")) # Connects to the cluster and establishes a persistent connection pool for each Cassandra node. # This is a resource-intensive operation. Do not create a new session for every request. As a best practice, create and reuse one or more sessions per process. # Typically, one session is sufficient. You can adjust this based on your application's needs, such as managing separate sessions for read and write operations. session = cluster.connect() # Execute a query. This example queries the system_auth.roles table to list all created roles. # This is a system table. By default, only the 'cassandra' superuser has SELECT permission. # If you use a different account for testing, query a different table or grant the necessary permissions to your account. rows = session.execute('SELECT * FROM system_auth.roles') # Print each row to the console. for row in rows: print("# row: {}".format(row)) # Close the session. session.shutdown() # Close the cluster. cluster.shutdown() - Other languages.
The connection process for other languages is similar to that for Java and Python. For more information, refer to the official DataStax driver documentation on GitHub: