Introduction
Bien que cqlsh soit utile pour une interaction directe, les applications de production nécessitent une stratégie de connexion plus robuste. Les SDK fournis par la communauté (pilotes DataStax) gèrent des tâches complexes telles que la connexion à plusieurs nœuds, l'équilibrage des requêtes entre les nœuds Cassandra et la gestion des pools de connexions. Cette rubrique explique comment utiliser ces SDK pour connecter votre application à un cluster ApsaraDB for Cassandra.
Prérequis
-
Obtenez les points de terminaison de connexion.
Dans la ApsaraDB for Cassandra console, accédez à la page Database Connection.
-
Par mesure de sécurité, l'accès depuis le réseau public est désactivé par défaut. Pour obtenir un point de terminaison public, cliquez sur Apply for Public Endpoint. Dans le volet de navigation de gauche, cliquez sur Database Connection. La page Connection Information affiche le point de terminaison interne, qui se termine par
.cassandra.rds.aliyuncs.com, ainsi que le CQL Port, défini par défaut sur9042.RemarqueLe nombre de points de terminaison disponibles varie en fonction de la taille du cluster. Si plusieurs points de terminaison sont fournis, utilisez-les tous afin de garantir une haute disponibilité en cas de défaillance d'un nœud. La méthode de connexion est identique pour le réseau public et le réseau interne ; seuls les points de terminaison diffèrent.
-
Configurez une liste blanche.
Avant d'établir la connexion, ajoutez l'adresse IP de votre client à la liste blanche. Pour plus d'informations, reportez-vous à la section Configurer une liste blanche.
Exemples de code multilingues
Java
-
Ajoutez la dépendance Maven.
<dependency> <groupId>com.datastax.cassandra</groupId> <artifactId>cassandra-driver-core</artifactId> <version>3.7.2</version> </dependency>ImportantCette dépendance inclut plusieurs bibliothèques courantes. Afin d'éviter d'éventuels conflits de dépendances, nous vous recommandons de la tester d'abord dans un nouveau projet.
-
Rédigez le code de connexion Java.
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(); } }
Python
-
Installez le 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 -
Rédigez le code de connexion Python.
#!/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() -
Autres langages.
Le processus de connexion pour les autres langages est similaire à celui de Java et Python. Pour plus d'informations, reportez-vous à la documentation officielle des pilotes DataStax sur GitHub :