本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
使用 Cassandra .NET Core 用戶端驅動程式以程式設計方式存取 Amazon Keyspaces
本節說明如何使用 .NET Core 用戶端驅動程式連線至 Amazon Keyspaces。設定步驟會根據您的環境和作業系統而有所不同,您可能需要相應地修改這些步驟。Amazon Keyspaces 需要使用 Transport Layer Security (TLS) 來協助保護用戶端的連線。若要使用 TLS 連線至 Amazon Keyspaces,您需要下載 Starfield 數位憑證,並將驅動程式設定為使用 TLS。
-
下載 Starfield 憑證並將其儲存至本機目錄,並記下路徑。以下是使用 PowerShell 的範例。
$client = new-object System.Net.WebClient $client.DownloadFile("https://certs.secureserver.net/repository/sf-class2-root.crt","
path_to_file
\sf-class2-root.crt") -
使用 nuget 主控台透過 nuget 安裝 CassandraCSharpDriver。
PM> Install-Package CassandraCSharpDriver
-
下列範例使用 .NET Core C# 主控台專案來連線至 Amazon Keyspaces 並執行查詢。
using Cassandra; using System; using System.Collections.Generic; using System.Linq; using System.Net.Security; using System.Runtime.ConstrainedExecution; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace CSharpKeyspacesExample { class Program { public Program(){} static void Main(string[] args) { X509Certificate2Collection certCollection = new X509Certificate2Collection(); X509Certificate2 amazoncert = new X509Certificate2(@"
path_to_file
\sf-class2-root.crt"); var userName = "ServiceUserName
"; var pwd = "ServicePassword
"; certCollection.Add(amazoncert); var awsEndpoint = "cassandra.us-east-2.amazonaws.com
" ; var cluster = Cluster.Builder() .AddContactPoints(awsEndpoint) .WithPort(9142) .WithAuthProvider(new PlainTextAuthProvider(userName, pwd)) .WithSSL(new SSLOptions().SetCertificateCollection(certCollection)) .Build(); var session = cluster.Connect(); var rs = session.Execute("SELECT * FROM system_schema.tables;"); foreach (var row in rs) { var name = row.GetValue<String>("keyspace_name"); Console.WriteLine(name); } } } }用量備註:
"
將 取代為第一個步驟中儲存的憑證路徑。path_to_file
/sf-class2-root.crt"依照 的步驟,確保
ServiceUserName
和ServicePassword
與您產生服務特定憑證時取得的使用者名稱和密碼相符建立服務特定的登入資料,以程式設計方式存取 Amazon Keyspaces。如需可用端點的清單,請參閱Amazon Keyspaces 的服務端點。