Preface

You have learned how to use cqlsh to access an ApsaraDB for Cassandra instance. However, in practice, you may need to write code to access an ApsaraDB for Cassandra instance. In cqlsh, you can only connect to a node and type some CQL statements. You may need to connect to multiple Cassandra nodes, evenly distribute requests to each Cassandra node, and manage connection pools. You do not need to worry about this because the community versions of SDKs have already implemented these features. The following sections describe how to use the SDKs to access an ApsaraDB for Cassandra instance.

Before you begin

  1. Obtain the endpoint.
    1. Log on to the ApsaraDB for Cassandra console. Click Database Connection.

    2. View the internal endpoint. For security considerations, Internet connection is disabled by default. To obtain the public endpoint, click Apply for Public Endpoint.detail
      Note The number of endpoints varies based on the cluster size. Use as many endpoints as possible. This prevents failure to connect to the cluster due to the failure of a single node. The methods for accessing an ApsaraDB for Cassandra instance over the Internet and the internal network are almost identical except that different endpoints are used.
  2. Add IP addresses to a whitelist.

    Before you access an ApsaraDB for Cassandra instance, make sure that you have added the IP addresses of clients to the whitelist. For more information, see Configure a whitelist.

Multi-language sample code

Java-based access
  1. Add a Maven dependency.
    <dependency>
        <groupId>com.datastax.cassandra</groupId>
        <artifactId>cassandra-driver-core</artifactId>
        <version>3.7.2</version>
    </dependency>
                
    Notice This reference introduces some public libraries. To avoid unnecessary trouble caused by dependency conflicts, test the dependency in a new project first.
  2. Write Java code for the access.
    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) {
    
        // Enter the public or internal endpoints of the database. You can enter as many endpoints as provided by the console.
        // In fact, the SDK connects to only the first accessible endpoint and establish a control connection. You can enter multiple endpoints to prevent database connection failures that are caused by the failure of a single node.
        // Ignore the sequence of the endpoints, because the SDK may rearrange the endpoint sequence to prevent different clients from connecting to the same endpoint.
        // You must enter only public endpoints or only internal endpoints.
        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)
          // Enter the account name and the password. If you forget the password, you can reset the password on the Accounts page.
          .withAuthProvider(new PlainTextAuthProvider("cassandra", "123456"))
          // If you access the Cassandra cluster over the Internet, you must append @public to the account name to switch to the full Internet link.
          // Otherwise, you cannot connect to all the internal nodes over the Internet, and exceptions or delays occur. This affects local development and debugging.
          // Automatic identification of network links are supported in the future. This eliminates the need to manually add @public. For more information, see changelogs on the official website.
          //.withAuthProvider(new PlainTextAuthProvider("cassandra@public", "123456"))
          .build();
    
        // Initialize the cluster. In this case, a control connection is established. This step can be ignored. This is because the init method is automatically called when a session is established.
        cluster.init();
    
        // Connect to the cluster. A persistent connection pool is established for each Cassandra node.
        // Therefore, it is burdensome to create one session for each request. We recommend that you create several sessions in advance for each process.
        // As a general rule, one session is sufficient. You can make adjustments based on your actual needs. For example, you can separately manage the read and write sessions.
        Session session = cluster.connect();
    
        // Query the permission-related table to view the number of created roles.
        // This is the system table. By default, only the superuser account cassandra has the SELECT permission.
        // If you use another account for testing, you can switch to another table or grant the SELECT permission to the account.
        ResultSet res = session.execute("SELECT * FROM system_auth.roles");
    
        // ResultSet implements the Iterable interface to display each line of information in the console.
        res.forEach(System.out::println);
    
        // Close the session.
        session.close();
    
        // Shut down the cluster.
        cluster.close();
      }
    
    }
    
                
Python-based access
  1. Install the SDK library.
    # Install the specified version. Python 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      
  2. Write Python code for the access.
    #! /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(
        # Enter the public or internal endpoints of the database. You can enter as many endpoints as provided by the console.
        # In fact, the SDK connects to only the first accessible endpoint and establish a control connection. You can enter multiple endpoints to prevent database connection failures that are caused by the failure of a single node.
        # Ignore the sequence of the endpoints, because the SDK may rearrange the endpoint sequence to prevent different clients from connecting to the same endpoint.
        # You must enter only public endpoints or only internal endpoints.
        contact_points=["cds-xxxxxxxx-core-003.cassandra.rds.aliyuncs.com",
                        "cds-xxxxxxxx-core-002.cassandra.rds.aliyuncs.com"],
        # Enter the account name and password. If you forget the password, you can reset the password on the Accounts page.
        auth_provider=PlainTextAuthProvider("cassandra", "123456"))
        # If you access the Cassandra cluster over the Internet, you must append @public to the account name to switch to the full Internet link.
        # Otherwise, you cannot connect to all the internal nodes over the Internet, and exceptions or delays occur. This affects local development and debugging.
        # Automatic identification of network links are supported in the future. This eliminates the need to manually add @public. For more information, see changelogs on the official website.
        # auth_provider=PlainTextAuthProvider("cassandra@public", "123456"))
    
    # Connect to the cluster. A persistent connection pool is established for each Cassandra node.
    # Therefore, it is burdensome to create one session for each request. We recommend that you create several sessions in advance for each process.
    # As a general rule, one session is sufficient. You can make adjustments based on your actual needs. For example, you can separately manage the read and write sessions.
    session = cluster.connect()
    
    # Query the permission-related table to view the number of created roles.
    # This is the system table. By default, only the superuser account cassandra has the SELECT permission.
    # If you use another account for testing, you can switch to another table or grant the SELECT permission to the account.
    rows = session.execute('SELECT * FROM system_auth.roles')
    
    # Display each line of information in the console.
    for row in rows:
        print("# row: {}".format(row))
    
    # Close the session.
    session.shutdown()
    
    # Shut down the cluster.
    cluster.shutdown()
                
  3. Access in other programming languages.

    The access interfaces for other programming languages are similar to those of Python and Java. For more information, see the GitHub community documentation.