共用方式為


整合 Azure Cosmos DB for Cassandra 與服務連接器

此頁面顯示支援的驗證方法和用戶端,並顯示可讓您使用服務連接器將 Azure Cosmos DB for Apache Cassandra 連線至其他雲端服務的範例程式碼。 在未使用服務連接器的情況下,您仍可透過其他程式設計語言連線至 Azure Cosmos DB for Cassandra。 此頁面也顯示您在建立服務連線時取得的預設環境變數名稱和值 (或 Spring Boot 設定)。

支援的計算服務

服務連接器可用來將下列計算服務連線至 Azure Cosmos DB for Apache Cassandra:

  • Azure App Service
  • Azure 容器應用程式
  • Azure Functions
  • Azure Kubernetes Service (AKS)
  • Azure Spring Apps

支援的驗證類型和用戶端類型

下表說明使用服務連接器將計算服務連線至 Azure Cosmos DB for Apache Cassandra 時,支援哪些用戶端類型和驗證方法的組合。 「是」表示支援的組合,而「否」則表示不支援。

用戶端類型 系統指派的受控識別 使用者指派的受控識別 祕密 / 連接字串 服務主體
.NET Yes .是 .是 Yes
Go Yes .是 .是 Yes
Java Yes .是 .是 Yes
Java - Spring Boot No .是 No
Node.js Yes .是 .是 Yes
Python Yes .是 .是 Yes
Yes .是 .是 Yes

此表指出表中所有用戶端類型和驗證方法的組合均受支援,但 Java - Spring Boot 用戶端類型 (其僅支援秘密/連接字串方法) 除外。 所有其他用戶端類型都可以使用任何驗證方法,使用服務連接器連線至 Azure Cosmos DB for Apache Cassandra。

預設環境變數名稱或應用程式屬性和範例程式碼

根據連線的驗證類型和用戶端類型,參考下表中的連線詳細資料和範例程式碼,將計算服務連線至 Azure Cosmos DB for Apache Cassandra。 如需命名慣例的詳細資訊,請參閱服務連接器內部一文。

系統指派的受控識別

預設環境變數名稱 描述 範例值
AZURE_COSMOS_LISTKEYURL 要取得連接字串的 URL https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<Azure-Cosmos-DB-account>/listKeys?api-version=2021-04-15
AZURE_COSMOS_SCOPE 您的受控識別範圍 https://management.azure.com/.default
AZURE_COSMOS_RESOURCEENDPOINT 您的資源端點 https://<Azure-Cosmos-DB-account>.documents.azure.com:443/
AZURE_COSMOS_CONTACTPOINT Azure Cosmos DB for Apache Cassandra 連絡點 <Azure-Cosmos-DB-account>.cassandra.cosmos.azure.com
AZURE_COSMOS_PORT Cassandra 連線連接埠 10350
AZURE_COSMOS_KEYSPACE Cassandra Keyspace <keyspace>
AZURE_COSMOS_USERNAME Cassandra 使用者名稱 <username>

範例指令碼

請參閱下列步驟和程式碼,使用系統指派的受控識別連線至 Azure Cosmos DB for Cassandra。

  1. 安裝相依性

    dotnet add package CassandraCSharpDriver --version 3.19.3
    dotnet add package Azure.Identity
    
  2. 使用用戶端程式庫 Azure.Identity 取得受控識別或服務主體的存取權杖。 使用存取權杖和 AZURE_COSMOS_LISTKEYURL 取得密碼。 從服務連接器新增的環境變數取得連線資訊,並連線至 Azure Cosmos DB for Cassandra。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。

    using System;
    using System.Security.Authentication;
    using System.Net.Security;
    using System.Net.Http;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    using System.Threading.Tasks;
    using Cassandra;
    using Azure.Identity;
    
    public class Program
    {
    	public static async Task Main()
    	{
            var cassandraContactPoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_CONTACTPOINT");
            var userName = Environment.GetEnvironmentVariable("AZURE_COSMOS_USERNAME");
            var cassandraPort = Int32.Parse(Environment.GetEnvironmentVariable("AZURE_COSMOS_PORT"));
            var cassandraKeyspace = Environment.GetEnvironmentVariable("AZURE_COSMOS_KEYSPACE");
            var listKeyUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTKEYURL");
            var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
    
            // Uncomment the following lines corresponding to the authentication type you want to use.
            // For system-assigned identity.
            // var tokenProvider = new DefaultAzureCredential();
    
            // For user-assigned identity.
            // var tokenProvider = new DefaultAzureCredential(
            //     new DefaultAzureCredentialOptions
            //     {
            //         ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
            //     }
            // );
    
            // For service principal.
            // var tenantId = Environment.GetEnvironmentVariable("AZURE_COSMOS_TENANTID");
            // var clientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
            // var clientSecret = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTSECRET");
            // var tokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
    
            // Acquire the access token. 
            AccessToken accessToken = await tokenProvider.GetTokenAsync(
                new TokenRequestContext(scopes: new string[]{ scope }));
    
            // Get the password.
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
            var response = await httpClient.POSTAsync(listKeyUrl);
            var responseBody = await response.Content.ReadAsStringAsync();
            var keys = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseBody);
            var password = keys["primaryMasterKey"];
    
            // Connect to Azure Cosmos DB for Cassandra
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);
            options.SetHostNameResolver((ipAddress) => cassandraContactPoint);
            Cluster cluster = Cluster
                .Builder()
                .WithCredentials(userName, password)
                .WithPort(cassandraPort)
                .AddContactPoint(cassandraContactPoint).WithSSL(options).Build();
            ISession session = await cluster.ConnectAsync();
        }
    
        public static bool ValidateServerCertificate
    	(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors
        )
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;
    
            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }
    }
    
    

使用者指派的受控識別

預設環境變數名稱 描述 範例值
AZURE_COSMOS_LISTKEYURL 要取得連接字串的 URL https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<Azure-Cosmos-DB-account>/listKeys?api-version=2021-04-15
AZURE_COSMOS_SCOPE 您的受控識別範圍 https://management.azure.com/.default
AZURE_COSMOS_RESOURCEENDPOINT 您的資源端點 https://<Azure-Cosmos-DB-account>.documents.azure.com:443/
AZURE_COSMOS_CONTACTPOINT Azure Cosmos DB for Apache Cassandra 連絡點 <Azure-Cosmos-DB-account>.cassandra.cosmos.azure.com
AZURE_COSMOS_PORT Cassandra 連線連接埠 10350
AZURE_COSMOS_KEYSPACE Cassandra Keyspace <keyspace>
AZURE_COSMOS_USERNAME Cassandra 使用者名稱 <username>
AZURE_COSMOS_CLIENTID 您的用戶端識別碼 <client-ID>

範例指令碼

請參閱下列步驟和程式碼,透過使用者指派的受控識別連線至 Azure Cosmos DB for Cassandra。

  1. 安裝相依性

    dotnet add package CassandraCSharpDriver --version 3.19.3
    dotnet add package Azure.Identity
    
  2. 使用用戶端程式庫 Azure.Identity 取得受控識別或服務主體的存取權杖。 使用存取權杖和 AZURE_COSMOS_LISTKEYURL 取得密碼。 從服務連接器新增的環境變數取得連線資訊,並連線至 Azure Cosmos DB for Cassandra。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。

    using System;
    using System.Security.Authentication;
    using System.Net.Security;
    using System.Net.Http;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    using System.Threading.Tasks;
    using Cassandra;
    using Azure.Identity;
    
    public class Program
    {
    	public static async Task Main()
    	{
            var cassandraContactPoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_CONTACTPOINT");
            var userName = Environment.GetEnvironmentVariable("AZURE_COSMOS_USERNAME");
            var cassandraPort = Int32.Parse(Environment.GetEnvironmentVariable("AZURE_COSMOS_PORT"));
            var cassandraKeyspace = Environment.GetEnvironmentVariable("AZURE_COSMOS_KEYSPACE");
            var listKeyUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTKEYURL");
            var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
    
            // Uncomment the following lines corresponding to the authentication type you want to use.
            // For system-assigned identity.
            // var tokenProvider = new DefaultAzureCredential();
    
            // For user-assigned identity.
            // var tokenProvider = new DefaultAzureCredential(
            //     new DefaultAzureCredentialOptions
            //     {
            //         ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
            //     }
            // );
    
            // For service principal.
            // var tenantId = Environment.GetEnvironmentVariable("AZURE_COSMOS_TENANTID");
            // var clientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
            // var clientSecret = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTSECRET");
            // var tokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
    
            // Acquire the access token. 
            AccessToken accessToken = await tokenProvider.GetTokenAsync(
                new TokenRequestContext(scopes: new string[]{ scope }));
    
            // Get the password.
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
            var response = await httpClient.POSTAsync(listKeyUrl);
            var responseBody = await response.Content.ReadAsStringAsync();
            var keys = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseBody);
            var password = keys["primaryMasterKey"];
    
            // Connect to Azure Cosmos DB for Cassandra
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);
            options.SetHostNameResolver((ipAddress) => cassandraContactPoint);
            Cluster cluster = Cluster
                .Builder()
                .WithCredentials(userName, password)
                .WithPort(cassandraPort)
                .AddContactPoint(cassandraContactPoint).WithSSL(options).Build();
            ISession session = await cluster.ConnectAsync();
        }
    
        public static bool ValidateServerCertificate
    	(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors
        )
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;
    
            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }
    }
    
    

連接字串

警告

Microsoft 建議您使用最安全的可用驗證流程。 這個程序描述的驗證流程需要在應用程式中具備極高的信任度,且伴隨著其他流程並未面臨的風險。 請僅在其他較安全的流程 (例如受控身分識別) 皆不具可行性的情況下,才使用這個流程。

SpringBoot 用戶端類型

預設環境變數名稱 描述 範例值
spring.data.cassandra.contact-points Azure Cosmos DB for Apache Cassandra 連絡點 <Azure-Cosmos-DB-account>.cassandra.cosmos.azure.com
spring.data.cassandra.port Cassandra 連線連接埠 10350
spring.data.cassandra.keyspace-name Cassandra Keyspace <keyspace>
spring.data.cassandra.username Cassandra 使用者名稱 <username>
spring.data.cassandra.password Cassandra 密碼 <password>
spring.data.cassandra.local-datacenter Azure 區域 <Azure-region>
spring.data.cassandra.ssl SSL 狀態 true

其他用戶端類型

預設環境變數名稱 描述 範例值
AZURE_COSMOS_CONTACTPOINT Azure Cosmos DB for Apache Cassandra 連絡點 <Azure-Cosmos-DB-account>.cassandra.cosmos.azure.com
AZURE_COSMOS_PORT Cassandra 連線連接埠 10350
AZURE_COSMOS_KEYSPACE Cassandra Keyspace <keyspace>
AZURE_COSMOS_USERNAME Cassandra 使用者名稱 <username>
AZURE_COSMOS_PASSWORD Cassandra 密碼 <password>

範例指令碼

請參閱下列步驟和程式碼,使用連接字串連線至 Azure Cosmos DB for Cassandra。

  1. 安裝相依性

    dotnet add package CassandraCSharpDriver --version 3.19.3
    
  2. 從服務連接器新增的環境變數取得連線資訊,並連線至 Azure Cosmos DB for Cassandra。

    using System;
    using System.Security.Authentication;
    using System.Net.Security;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    using System.Threading.Tasks;
    using Cassandra;
    
    public class Program
    {
    	public static async Task Main()
    	{
            var cassandraContactPoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_CONTACTPOINT");
            var userName = Environment.GetEnvironmentVariable("AZURE_COSMOS_USERNAME");
            var password = Environment.GetEnvironmentVariable("AZURE_COSMOS_PASSWORD");
            var cassandraPort = Int32.Parse(Environment.GetEnvironmentVariable("AZURE_COSMOS_PORT"));
            var cassandraKeyspace = Environment.GetEnvironmentVariable("AZURE_COSMOS_KEYSPACE");
    
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);
            options.SetHostNameResolver((ipAddress) => cassandraContactPoint);
            Cluster cluster = Cluster
                .Builder()
                .WithCredentials(userName, password)
                .WithPort(cassandraPort)
                .AddContactPoint(cassandraContactPoint).WithSSL(options).Build();
            ISession session = await cluster.ConnectAsync();
        }
    
        public static bool ValidateServerCertificate
    	(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors
        )
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;
    
            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }
    }
    
    

如需詳細資訊,請參閱使用 .NET SDK 和 Azure Cosmos DB 建置 Apache Cassandra 應用程式

服務主體

預設環境變數名稱 描述 範例值
AZURE_COSMOS_LISTKEYURL 要取得連接字串的 URL https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<Azure-Cosmos-DB-account>/listKeys?api-version=2021-04-15
AZURE_COSMOS_SCOPE 您的受控識別範圍 https://management.azure.com/.default
AZURE_COSMOS_RESOURCEENDPOINT 您的資源端點 https://<Azure-Cosmos-DB-account>.documents.azure.com:443/
AZURE_COSMOS_CONTACTPOINT Azure Cosmos DB for Apache Cassandra 連絡點 <Azure-Cosmos-DB-account>.cassandra.cosmos.azure.com
AZURE_COSMOS_PORT Cassandra 連線連接埠 10350
AZURE_COSMOS_KEYSPACE Cassandra Keyspace <keyspace>
AZURE_COSMOS_USERNAME Cassandra 使用者名稱 <username>
AZURE_COSMOS_CLIENTID 您的用戶端識別碼 <client-ID>
AZURE_COSMOS_CLIENTSECRET 您的用戶端密碼 <client-secret>
AZURE_COSMOS_TENANTID 您的租用戶識別碼 <tenant-ID>

範例指令碼

請參閱下列步驟和程式碼,使用服務主體連線至 Azure Cosmos DB for Cassandra。

  1. 安裝相依性

    dotnet add package CassandraCSharpDriver --version 3.19.3
    dotnet add package Azure.Identity
    
  2. 使用用戶端程式庫 Azure.Identity 取得受控識別或服務主體的存取權杖。 使用存取權杖和 AZURE_COSMOS_LISTKEYURL 取得密碼。 從服務連接器新增的環境變數取得連線資訊,並連線至 Azure Cosmos DB for Cassandra。 使用下列程式代碼時,請取消註解您想要使用的驗證類型代碼段部分。

    using System;
    using System.Security.Authentication;
    using System.Net.Security;
    using System.Net.Http;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    using System.Threading.Tasks;
    using Cassandra;
    using Azure.Identity;
    
    public class Program
    {
    	public static async Task Main()
    	{
            var cassandraContactPoint = Environment.GetEnvironmentVariable("AZURE_COSMOS_CONTACTPOINT");
            var userName = Environment.GetEnvironmentVariable("AZURE_COSMOS_USERNAME");
            var cassandraPort = Int32.Parse(Environment.GetEnvironmentVariable("AZURE_COSMOS_PORT"));
            var cassandraKeyspace = Environment.GetEnvironmentVariable("AZURE_COSMOS_KEYSPACE");
            var listKeyUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTKEYURL");
            var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
    
            // Uncomment the following lines corresponding to the authentication type you want to use.
            // For system-assigned identity.
            // var tokenProvider = new DefaultAzureCredential();
    
            // For user-assigned identity.
            // var tokenProvider = new DefaultAzureCredential(
            //     new DefaultAzureCredentialOptions
            //     {
            //         ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
            //     }
            // );
    
            // For service principal.
            // var tenantId = Environment.GetEnvironmentVariable("AZURE_COSMOS_TENANTID");
            // var clientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
            // var clientSecret = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTSECRET");
            // var tokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
    
            // Acquire the access token. 
            AccessToken accessToken = await tokenProvider.GetTokenAsync(
                new TokenRequestContext(scopes: new string[]{ scope }));
    
            // Get the password.
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
            var response = await httpClient.POSTAsync(listKeyUrl);
            var responseBody = await response.Content.ReadAsStringAsync();
            var keys = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseBody);
            var password = keys["primaryMasterKey"];
    
            // Connect to Azure Cosmos DB for Cassandra
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);
            options.SetHostNameResolver((ipAddress) => cassandraContactPoint);
            Cluster cluster = Cluster
                .Builder()
                .WithCredentials(userName, password)
                .WithPort(cassandraPort)
                .AddContactPoint(cassandraContactPoint).WithSSL(options).Build();
            ISession session = await cluster.ConnectAsync();
        }
    
        public static bool ValidateServerCertificate
    	(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors
        )
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;
    
            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }
    }
    
    

下一步

請遵循下方列出的教學課程以深入了解服務連接器。