如何使用Java DataStax驱动通过PPK文件和用户名连接Apache Cassandra
Connecting to Cassandra via DataStax Java Driver with SSH PPK Key (Matching PuTTY Setup)
Since you're using PuTTY with a PPK key and x@domain.com to access your Apache Cassandra instance, you'll need to replicate the SSH tunnel functionality in your Java code first—just like PuTTY does under the hood. Here's a complete, working implementation to match your setup:
Background
Your PuTTY workflow creates an SSH tunnel that forwards local traffic to the remote Cassandra port (default 9042) on your server. To mirror this in Java, we'll use the JSch library to handle SSH connection/port forwarding, then connect the DataStax driver to the local forwarded port.
Step 1: Add Dependencies
First, include the required libraries in your project. For Maven:
<dependencies> <!-- DataStax Cassandra Driver (match your cluster version) --> <dependency> <groupId>com.datastax.cassandra</groupId> <artifactId>cassandra-driver-core</artifactId> <version>3.11.4</version> </dependency> <!-- JSch for SSH tunneling --> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> </dependencies>
For Gradle:
dependencies { implementation 'com.datastax.cassandra:cassandra-driver-core:3.11.4' implementation 'com.jcraft:jsch:0.1.55' }
Step 2: Full Code Implementation
package com.cassandra.tutorial; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; // Alias to avoid conflict with Cassandra's Session class import com.jcraft.jsch.Session as SshSession; public class CassConnector { private static Cluster cluster; private static Session cassandraSession; private static SshSession sshSession; // Set up SSH tunnel using your PPK key private static void setupSshTunnel(String sshUsername, String sshHost, String ppkKeyPath, int localPort, int remoteCassandraPort) throws JSchException { JSch jsch = new JSch(); // Load your PPK private key file jsch.addIdentity(ppkKeyPath); // Initialize SSH session to your server sshSession = jsch.getSession(sshUsername, sshHost, 22); // Skip host key check for testing (remove this in production!) sshSession.setConfig("StrictHostKeyChecking", "no"); sshSession.connect(); // Forward local port to remote Cassandra port sshSession.setPortForwardingL(localPort, "127.0.0.1", remoteCassandraPort); System.out.println("SSH tunnel established: localhost:" + localPort + " -> " + sshHost + ":" + remoteCassandraPort); } // Connect to Cassandra via the local forwarded port private static Cluster connectCassandra(String localHost, int localPort) { return Cluster.builder() .addContactPoint(localHost) .withPort(localPort) // Uncomment below if your Cassandra requires username/password auth // .withCredentials("cassandra_user", "cassandra_password") .build(); } public static void main(String[] args) { // Configure your connection details here String sshUser = "x@domain.com"; String sshServerIp = "172.31.yy.xx"; // Use the IP you retrieved from PuTTY String ppkFilePath = "C:\\your\\ppk\\file\\path\\key.ppk"; // Update to your PPK file location int localForwardPort = 9042; // Change if local port is in use int remoteCassandraPort = 9042; // Default Cassandra port String targetKeyspace = "core"; try { // 1. First establish the SSH tunnel setupSshTunnel(sshUser, sshServerIp, ppkFilePath, localForwardPort, remoteCassandraPort); // 2. Connect to Cassandra through the tunnel cluster = connectCassandra("localhost", localForwardPort); cassandraSession = cluster.connect(targetKeyspace); // Verify connection with a simple query System.out.println("Connected to Cassandra keyspace: " + targetKeyspace); cassandraSession.execute("SELECT release_version FROM system.local;") .forEach(row -> System.out.println("Cassandra version: " + row.getString("release_version"))); } catch (JSchException e) { System.err.println("Failed to establish SSH tunnel: " + e.getMessage()); e.printStackTrace(); } finally { // Clean up resources in reverse order if (cassandraSession != null) cassandraSession.close(); if (cluster != null) cluster.close(); if (sshSession != null && sshSession.isConnected()) { sshSession.disconnect(); System.out.println("SSH tunnel closed."); } } } }
Key Notes
- PPK Key Compatibility: JSch supports PPK files directly, but if you run into issues, convert your PPK to an OpenSSH-formatted
.pemfile using PuTTYgen, then updatejsch.addIdentity()to point to the.pemfile. - Production Safety: Never leave
StrictHostKeyCheckingset tonoin production. Add your server's host key to a known_hosts file and configure JSch to use it instead. - Cassandra Authentication: If your cluster uses password auth, uncomment the
.withCredentials()line and fill in your Cassandra credentials. - Port Conflicts: If local port 9042 is occupied, change
localForwardPortto another number (like 9043) and update the driver connection to match.
内容的提问来源于stack exchange,提问作者vinay kumar
相关产品推荐
相关产品推荐

