本文涵蓋支援的驗證方法、用戶端和範例程式碼,您可以使用服務連接器將應用程式連線至 Azure Cache for Redis,在本文中,您也會發現建立服務連線時取得的預設環境變數名稱、值和組態。
支援的計算服務
您可以使用 Service Connector 將下列計算服務連線至 Azure Cache for Redis:
- Azure App Service
- Azure 容器應用程式
- Azure Functions
- Azure Kubernetes Service (AKS)
- Azure Spring Apps
支援的驗證和客戶端類型
下表顯示使用服務連接器將計算服務連線到 Azure Cache for Redis 時,支援驗證方法和客戶端的組合。 “Yes” 表示支持組合。 「否」表示不支援。
用戶端類型 |
系統指派的受控識別 |
使用者指派的受控識別 |
祕密 / 連接字串 |
服務主體 |
.NET |
Yes |
Yes |
Yes |
Yes |
Go |
不 |
不 |
Yes |
否 |
Java |
Yes |
Yes |
Yes |
Yes |
Java - Spring Boot |
不 |
否 |
Yes |
否 |
Node.js |
Yes |
Yes |
Yes |
Yes |
Python |
Yes |
Yes |
Yes |
Yes |
無 |
Yes |
Yes |
Yes |
Yes |
預設環境變數名稱或應用程式屬性和範例程式碼
使用下列環境變數名稱和應用程式屬性,將計算服務連線到您的 Redis 伺服器。 若要深入瞭解命名慣例,請參閱 Service Connector 內部文章 。
系統指派的受控識別
預設環境變數名稱 |
描述 |
範例值 |
AZURE_REDIS_HOST |
Redis 端點 |
<RedisName>.redis.cache.windows.net |
範例指令碼
下列步驟和程式代碼會示範如何使用系統指派的受控識別來聯機到 Redis。
安裝依賴項目。
dotnet add package Microsoft.Azure.StackExchangeRedis --version 3.2.0
使用 Service Connector 所設定的環境變數來新增驗證邏輯。 如需詳細資訊,請參閱 Microsoft.Azure.StackExchangeRedis 擴充功能。
using StackExchange.Redis;
var cacheHostName = Environment.GetEnvironmentVariable("AZURE_REDIS_HOST");
var configurationOptions = ConfigurationOptions.Parse($"{cacheHostName}:6380");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
// For user-assigned identity.
// var managedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// await configurationOptions.ConfigureForAzureWithUserAssignedManagedIdentityAsync(managedIdentityClientId);
// Service principal secret.
// var clientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// var tenantId = Environment.GetEnvironmentVariable("AZURE_REDIS_TENANTID");
// var secret = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTSECRET");
// await configurationOptions.ConfigureForAzureWithServicePrincipalAsync(clientId, tenantId, secret);
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
在您的 pom.xml
檔案中新增下列依賴項:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.11.2</version> <!-- {x-version-update;com.azure:azure-identity;dependency} -->
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>5.1.0</version> <!-- {x-version-update;redis.clients:jedis;external_dependency} -->
</dependency>
使用 Service Connector 所設定的環境變數來新增驗證邏輯。 如需詳細資訊,請參閱 Azure-AAD-Authentication-With-Jedis。
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import java.net.URI;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
// For user-assigned identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().managedIdentityClientId(clientId).build();
// For AKS workload identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().workloadIdentityClientId(clientId).build();
// For service principal.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// String secret = System.getenv("AZURE_REDIS_CLIENTSECRET");
// String tenant = System.getenv("AZURE_REDIS_TENANTID");
// ClientSecretCredential defaultAzureCredential = new ClientSecretCredentialBuilder().tenantId(tenant).clientId(clientId).clientSecret(secret).build();
String token = defaultAzureCredential
.getToken(new TokenRequestContext()
.addScopes("https://redis.azure.com/.default")).block().getToken();
// SSL connection is required.
boolean useSsl = true;
// TODO: Replace Host Name with Azure Cache for Redis Host Name.
String username = extractUsernameFromToken(token);
String cacheHostname = System.getenv("AZURE_REDIS_HOST");
// Create Jedis client and connect to Azure Cache for Redis over the TLS/SSL port using the access token as password.
// Note, Redis Cache host name and port are required below.
Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
.password(token) // Microsoft Entra access token as password is required.
.user(username) // Username is Required
.ssl(useSsl) // SSL Connection is Required
.build());
// Set a value against your key in the Redis cache.
jedis.set("Az:key", "testValue");
System.out.println(jedis.get("Az:key"));
// Close the Jedis Client
jedis.close();
安裝相依性。
pip install redis azure-identity
使用 Service Connector 所設定的環境變數來新增驗證邏輯。 如需詳細資訊,請參閱 azure-aad-auth-with-redis-py。
import os
import time
import logging
import redis
import base64
import json
from azure.identity import DefaultAzureCredential
host = os.getenv('AZURE_REDIS_HOST')
scope = "https://redis.azure.com/.default"
port = 6380 # Required
def extract_username_from_token(token):
parts = token.split('.')
base64_str = parts[1]
if len(base64_str) % 4 == 2:
base64_str += "=="
elif len(base64_str) % 4 == 3:
base64_str += "="
json_bytes = base64.b64decode(base64_str)
json_str = json_bytes.decode('utf-8')
jwt = json.loads(json_str)
return jwt['oid']
def re_authentication():
_LOGGER = logging.getLogger(__name__)
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For service principal.
# tenant_id = os.getenv("AZURE_TENANT_ID")
# client_id = os.getenv("AZURE_CLIENT_ID")
# client_secret = os.getenv("AZURE_CLIENT_SECRET")
# cred = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
token = cred.get_token(scope)
user_name = extract_username_from_token(token.token)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
max_retry = 3
for index in range(max_retry):
try:
if _need_refreshing(token):
_LOGGER.info("Refreshing token...")
tmp_token = cred.get_token(scope)
if tmp_token:
token = tmp_token
r.execute_command("AUTH", user_name, token.token)
r.set("Az:key1", "value1")
t = r.get("Az:key1")
print(t)
break
except redis.ConnectionError:
_LOGGER.info("Connection lost. Reconnecting.")
token = cred.get_token(scope)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
except Exception:
_LOGGER.info("Unknown failures.")
break
def _need_refreshing(token, refresh_offset=300):
return not token or token.expires_on - time.time() < refresh_offset
if __name__ == '__main__':
re_authentication()
安裝相依性。
npm install redis @azure/identity
使用 Service Connector 所設定的環境變數來新增驗證邏輯。 如需詳細資訊,請參閱 Azure Cache for Redis: 搭配 Microsoft Entra ID 的 node-redis 用戶端程式庫。
import { createClient } from "redis";
import { DefaultAzureCredential } from "@azure/identity";
function extractUsernameFromToken(accessToken: AccessToken): string{
const base64Metadata = accessToken.token.split(".")[1];
const { oid } = JSON.parse(
Buffer.from(base64Metadata, "base64").toString("utf8"),
);
return oid;
}
async function main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_REDIS_TENANTID;
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const clientSecret = process.env.AZURE_REDIS_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
const redisScope = "https://redis.azure.com/.default";
let accessToken = await credential.getToken(redisScope);
console.log("access Token", accessToken);
const host = process.env.AZURE_REDIS_HOST;
// Create redis client and connect to Azure Cache for Redis over the TLS port using the access token as password.
const client = createClient({
username: extractUsernameFromToken(accessToken),
password: accessToken.token,
url: `redis://${host}:6380`,
pingInterval: 100000,
socket: {
tls: true,
keepAlive: 0
},
});
client.on("error", (err) => console.log("Redis Client Error", err));
await client.connect();
// Set a value against your key in Azure Redis Cache.
await client.set("Az:key", "value1312");
// Get value of your key in Azure Redis Cache.
console.log("value-", await client.get("Az:key"));
}
main().catch((err) => {
console.log("error code: ", err.code);
console.log("error message: ", err.message);
console.log("error stack: ", err.stack);
});
針對其他語言,您可以使用 Azure 身分識別用戶端連結庫(以及 Service Connector 設定為環境變數的連線資訊)來連線到 Azure Cache for Redis。
使用者指派的管理識別
預設環境變數名稱 |
描述 |
範例值 |
AZURE_REDIS_HOST |
Redis 端點 |
<RedisName>.redis.cache.windows.net |
AZURE_REDIS_CLIENTID |
受控識別用戶端識別碼 |
<client-ID> |
範例指令碼
下列步驟和程式代碼會示範如何使用使用者指派的受控識別來聯機到 Redis。
安裝相依性。
dotnet add package Microsoft.Azure.StackExchangeRedis --version 3.2.0
使用 Service Connector 所設定的環境變數來新增驗證邏輯。 如需詳細資訊,請參閱 Microsoft.Azure.StackExchangeRedis 擴充功能。
using StackExchange.Redis;
var cacheHostName = Environment.GetEnvironmentVariable("AZURE_REDIS_HOST");
var configurationOptions = ConfigurationOptions.Parse($"{cacheHostName}:6380");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
// For user-assigned identity.
// var managedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// await configurationOptions.ConfigureForAzureWithUserAssignedManagedIdentityAsync(managedIdentityClientId);
// Service principal secret.
// var clientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// var tenantId = Environment.GetEnvironmentVariable("AZURE_REDIS_TENANTID");
// var secret = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTSECRET");
// await configurationOptions.ConfigureForAzureWithServicePrincipalAsync(clientId, tenantId, secret);
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
在您的 pom.xml
檔案中新增下列相依性:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.11.2</version> <!-- {x-version-update;com.azure:azure-identity;dependency} -->
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>5.1.0</version> <!-- {x-version-update;redis.clients:jedis;external_dependency} -->
</dependency>
使用 Service Connector 所設定的環境變數來新增驗證邏輯。 如需詳細資訊,請參閱 Azure-AAD-Authentication-With-Jedis。
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import java.net.URI;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
// For user-assigned identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().managedIdentityClientId(clientId).build();
// For AKS workload identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().workloadIdentityClientId(clientId).build();
// For service principal.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// String secret = System.getenv("AZURE_REDIS_CLIENTSECRET");
// String tenant = System.getenv("AZURE_REDIS_TENANTID");
// ClientSecretCredential defaultAzureCredential = new ClientSecretCredentialBuilder().tenantId(tenant).clientId(clientId).clientSecret(secret).build();
String token = defaultAzureCredential
.getToken(new TokenRequestContext()
.addScopes("https://redis.azure.com/.default")).block().getToken();
// SSL connection is required.
boolean useSsl = true;
// TODO: Replace Host Name with Azure Cache for Redis Host Name.
String username = extractUsernameFromToken(token);
String cacheHostname = System.getenv("AZURE_REDIS_HOST");
// Create Jedis client and connect to Azure Cache for Redis over the TLS/SSL port using the access token as password.
// Note, Redis Cache host name and port are required below.
Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
.password(token) // Microsoft Entra access token as password is required.
.user(username) // Username is Required
.ssl(useSsl) // SSL Connection is Required
.build());
// Set a value against your key in the Redis cache.
jedis.set("Az:key", "testValue");
System.out.println(jedis.get("Az:key"));
// Close the Jedis Client
jedis.close();
安裝相依性。
pip install redis azure-identity
使用 Service Connector 所設定的環境變數來新增驗證邏輯。 如需詳細資訊,請參閱 azure-aad-auth-with-redis-py。
import os
import time
import logging
import redis
import base64
import json
from azure.identity import DefaultAzureCredential
host = os.getenv('AZURE_REDIS_HOST')
scope = "https://redis.azure.com/.default"
port = 6380 # Required
def extract_username_from_token(token):
parts = token.split('.')
base64_str = parts[1]
if len(base64_str) % 4 == 2:
base64_str += "=="
elif len(base64_str) % 4 == 3:
base64_str += "="
json_bytes = base64.b64decode(base64_str)
json_str = json_bytes.decode('utf-8')
jwt = json.loads(json_str)
return jwt['oid']
def re_authentication():
_LOGGER = logging.getLogger(__name__)
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For service principal.
# tenant_id = os.getenv("AZURE_TENANT_ID")
# client_id = os.getenv("AZURE_CLIENT_ID")
# client_secret = os.getenv("AZURE_CLIENT_SECRET")
# cred = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
token = cred.get_token(scope)
user_name = extract_username_from_token(token.token)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
max_retry = 3
for index in range(max_retry):
try:
if _need_refreshing(token):
_LOGGER.info("Refreshing token...")
tmp_token = cred.get_token(scope)
if tmp_token:
token = tmp_token
r.execute_command("AUTH", user_name, token.token)
r.set("Az:key1", "value1")
t = r.get("Az:key1")
print(t)
break
except redis.ConnectionError:
_LOGGER.info("Connection lost. Reconnecting.")
token = cred.get_token(scope)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
except Exception:
_LOGGER.info("Unknown failures.")
break
def _need_refreshing(token, refresh_offset=300):
return not token or token.expires_on - time.time() < refresh_offset
if __name__ == '__main__':
re_authentication()
安裝相依性。
npm install redis @azure/identity
使用 Service Connector 所設定的環境變數來新增驗證邏輯。 如需詳細資訊,請參閱 Azure Cache for Redis:Microsoft Entra ID 搭配 node-redis 用戶端程式庫。
import { createClient } from "redis";
import { DefaultAzureCredential } from "@azure/identity";
function extractUsernameFromToken(accessToken: AccessToken): string{
const base64Metadata = accessToken.token.split(".")[1];
const { oid } = JSON.parse(
Buffer.from(base64Metadata, "base64").toString("utf8"),
);
return oid;
}
async function main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_REDIS_TENANTID;
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const clientSecret = process.env.AZURE_REDIS_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
const redisScope = "https://redis.azure.com/.default";
let accessToken = await credential.getToken(redisScope);
console.log("access Token", accessToken);
const host = process.env.AZURE_REDIS_HOST;
// Create redis client and connect to Azure Cache for Redis over the TLS port using the access token as password.
const client = createClient({
username: extractUsernameFromToken(accessToken),
password: accessToken.token,
url: `redis://${host}:6380`,
pingInterval: 100000,
socket: {
tls: true,
keepAlive: 0
},
});
client.on("error", (err) => console.log("Redis Client Error", err));
await client.connect();
// Set a value against your key in Azure Redis Cache.
await client.set("Az:key", "value1312");
// Get value of your key in Azure Redis Cache.
console.log("value-", await client.get("Az:key"));
}
main().catch((err) => {
console.log("error code: ", err.code);
console.log("error message: ", err.message);
console.log("error stack: ", err.stack);
});
針對其他語言,您可以使用 Azure 身分識別用戶端連結庫(以及 Service Connector 設定為環境變數的連線資訊)來連線到 Azure Cache for Redis。
連接字串
警告
我們建議您使用最安全的驗證流程。 此處所述的驗證流程需要應用程式中非常高度的信任,而且具有在其他流程中不存在的風險。 只有當更安全的流程,例如受控識別無法運作時,才應該使用此流程。
預設環境變數名稱 |
描述 |
範例值 |
AZURE_REDIS_CONNECTIONSTRING |
StackExchange.Redis 連接字串 |
<redis-server-name>.redis.cache.windows.net:6380,password=<redis-key>,ssl=True,defaultDatabase=0 |
預設環境變數名稱 |
描述 |
範例值 |
AZURE_REDIS_CONNECTIONSTRING |
Jedis 連接字串 |
rediss://:<redis-key>@<redis-server-name>.redis.cache.windows.net:6380/0 |
應用程式屬性 |
描述 |
範例值 |
spring.redis.host |
Redis 主機 |
<redis-server-name>.redis.cache.windows.net |
spring.redis.port |
Redis 連接埠 |
6380 |
spring.redis.database |
Redis 資料庫 |
0 |
spring.redis.password |
Redis 金鑰 |
<redis-key> |
spring.redis.ssl |
SSL 設定 |
true |
預設環境變數名稱 |
描述 |
範例值 |
AZURE_REDIS_CONNECTIONSTRING |
redis-py 連接字串 |
rediss://:<redis-key>@<redis-server-name>.redis.cache.windows.net:6380/0 |
預設環境變數名稱 |
描述 |
範例值 |
AZURE_REDIS_CONNECTIONSTRING |
redis-py 連接字串 |
rediss://:<redis-key>@<redis-server-name>.redis.cache.windows.net:6380/0 |
預設環境變數名稱 |
描述 |
範例值 |
AZURE_REDIS_CONNECTIONSTRING |
node-redis 連接字串 |
rediss://:<redis-key>@<redis-server-name>.redis.cache.windows.net:6380/0 |
預設環境變數名稱 |
描述 |
範例值 |
AZURE_REDIS_HOST |
Redis 主機 |
<redis-server-name>.redis.cache.windows.net |
AZURE_REDIS_PORT |
Redis 連接埠 |
6380 |
AZURE_REDIS_DATABASE |
Redis 資料庫 |
0 |
AZURE_REDIS_PASSWORD |
Redis 金鑰 |
<redis-key> |
AZURE_REDIS_SSL |
SSL 設定 |
true |
範例指令碼
下列步驟和程式代碼會示範如何使用 連接字串 來聯機到 Azure Cache for Redis。
安裝依賴項。
dotnet add package StackExchange.Redis --version 2.6.122
從服務連接器新增的環境變數取得連接字串。
using StackExchange.Redis;
var connectionString = Environment.GetEnvironmentVariable("AZURE_REDIS_CONNECTIONSTRING");
var _redisConnection = await RedisConnection.InitializeAsync(connectionString: connectionString);
- 在您的
pom.xml
檔案中新增下列相依性:<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.1.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
- 從服務連接器新增的環境變數取得連接字串。
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import java.net.URI;
String connectionString = System.getenv("AZURE_REDIS_CONNECTIONSTRING");
URI uri = new URI(connectionString);
JedisShardInfo shardInfo = new JedisShardInfo(uri);
shardInfo.setSsl(true);
Jedis jedis = new Jedis(shardInfo);
若要設定 Spring 應用程式,請參閱 在 Spring 中使用 Azure Redis 快取。 Service Connector 會將組態屬性新增至 Spring Apps。
- 安裝依賴項。
pip install redis
- 從服務連接器新增的環境變數取得連接字串。
import os
import redis
url = os.getenv('AZURE_REDIS_CONNECTIONSTRING')
url_connection = redis.from_url(url)
url_connection.ping()
- 安裝相依性。
go get github.com/redis/go-redis/v9
- 從服務連接器新增的環境變數取得連接字串。
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
connectionString := os.Getenv("AZURE_REDIS_CONNECTIONSTRING")
opt, err := redis.ParseURL(connectionString)
if err != nil {
panic(err)
}
client := redis.NewClient(opt)
安裝依賴項。
npm install redis
從服務連接器新增的環境變數取得連接字串。
const redis = require("redis");
const connectionString = process.env.AZURE_REDIS_CONNECTIONSTRING;
const cacheConnection = redis.createClient({
url: connectionString,
});
await cacheConnection.connect();
對於其他語言,您可以使用服務連接器設定到環境變數的連線資訊,來連線到 Azure Cache for Redis。
服務主體
預設環境變數名稱 |
描述 |
範例值 |
AZURE_REDIS_HOST |
Redis 端點 |
<RedisName>.redis.cache.windows.net |
AZURE_REDIS_CLIENTID |
服務主體的用戶端識別碼 |
<client-ID> |
AZURE_REDIS_CLIENTSECRET |
服務主體的秘密 |
<client-secret> |
AZURE_REDIS_TENANTID |
服務主體的租用戶識別碼 |
<tenant-id> |
範例指令碼
下列步驟和程式代碼會示範如何使用服務主體來連線到 Redis。
安裝依賴項。
dotnet add package Microsoft.Azure.StackExchangeRedis --version 3.2.0
使用 Service Connector 所設定的環境變數來新增驗證邏輯。 如需詳細資訊,請參閱 Microsoft.Azure.StackExchangeRedis 擴充功能。
using StackExchange.Redis;
var cacheHostName = Environment.GetEnvironmentVariable("AZURE_REDIS_HOST");
var configurationOptions = ConfigurationOptions.Parse($"{cacheHostName}:6380");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
// For user-assigned identity.
// var managedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// await configurationOptions.ConfigureForAzureWithUserAssignedManagedIdentityAsync(managedIdentityClientId);
// Service principal secret.
// var clientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// var tenantId = Environment.GetEnvironmentVariable("AZURE_REDIS_TENANTID");
// var secret = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTSECRET");
// await configurationOptions.ConfigureForAzureWithServicePrincipalAsync(clientId, tenantId, secret);
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
在您的pom.xml
檔案中新增下列相依性:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.11.2</version> <!-- {x-version-update;com.azure:azure-identity;dependency} -->
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>5.1.0</version> <!-- {x-version-update;redis.clients:jedis;external_dependency} -->
</dependency>
使用 Service Connector 所設定的環境變數來新增驗證邏輯。 如需詳細資訊,請參閱 Azure-AAD-Authentication-With-Jedis。
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import java.net.URI;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
// For user-assigned identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().managedIdentityClientId(clientId).build();
// For AKS workload identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().workloadIdentityClientId(clientId).build();
// For service principal.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// String secret = System.getenv("AZURE_REDIS_CLIENTSECRET");
// String tenant = System.getenv("AZURE_REDIS_TENANTID");
// ClientSecretCredential defaultAzureCredential = new ClientSecretCredentialBuilder().tenantId(tenant).clientId(clientId).clientSecret(secret).build();
String token = defaultAzureCredential
.getToken(new TokenRequestContext()
.addScopes("https://redis.azure.com/.default")).block().getToken();
// SSL connection is required.
boolean useSsl = true;
// TODO: Replace Host Name with Azure Cache for Redis Host Name.
String username = extractUsernameFromToken(token);
String cacheHostname = System.getenv("AZURE_REDIS_HOST");
// Create Jedis client and connect to Azure Cache for Redis over the TLS/SSL port using the access token as password.
// Note, Redis Cache host name and port are required below.
Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
.password(token) // Microsoft Entra access token as password is required.
.user(username) // Username is Required
.ssl(useSsl) // SSL Connection is Required
.build());
// Set a value against your key in the Redis cache.
jedis.set("Az:key", "testValue");
System.out.println(jedis.get("Az:key"));
// Close the Jedis Client
jedis.close();
安裝相依性。
pip install redis azure-identity
使用 Service Connector 所設定的環境變數來新增驗證邏輯。 如需詳細資訊,請參閱 azure-aad-auth-with-redis-py。
import os
import time
import logging
import redis
import base64
import json
from azure.identity import DefaultAzureCredential
host = os.getenv('AZURE_REDIS_HOST')
scope = "https://redis.azure.com/.default"
port = 6380 # Required
def extract_username_from_token(token):
parts = token.split('.')
base64_str = parts[1]
if len(base64_str) % 4 == 2:
base64_str += "=="
elif len(base64_str) % 4 == 3:
base64_str += "="
json_bytes = base64.b64decode(base64_str)
json_str = json_bytes.decode('utf-8')
jwt = json.loads(json_str)
return jwt['oid']
def re_authentication():
_LOGGER = logging.getLogger(__name__)
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For service principal.
# tenant_id = os.getenv("AZURE_TENANT_ID")
# client_id = os.getenv("AZURE_CLIENT_ID")
# client_secret = os.getenv("AZURE_CLIENT_SECRET")
# cred = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
token = cred.get_token(scope)
user_name = extract_username_from_token(token.token)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
max_retry = 3
for index in range(max_retry):
try:
if _need_refreshing(token):
_LOGGER.info("Refreshing token...")
tmp_token = cred.get_token(scope)
if tmp_token:
token = tmp_token
r.execute_command("AUTH", user_name, token.token)
r.set("Az:key1", "value1")
t = r.get("Az:key1")
print(t)
break
except redis.ConnectionError:
_LOGGER.info("Connection lost. Reconnecting.")
token = cred.get_token(scope)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
except Exception:
_LOGGER.info("Unknown failures.")
break
def _need_refreshing(token, refresh_offset=300):
return not token or token.expires_on - time.time() < refresh_offset
if __name__ == '__main__':
re_authentication()
安裝相依性。
npm install redis @azure/identity
使用 Service Connector 所設定的環境變數來新增驗證邏輯。 如需詳細資訊,請參閱 Azure Cache for Redis:Microsoft Entra ID 與 node-redis 用戶端程式庫。
import { createClient } from "redis";
import { DefaultAzureCredential } from "@azure/identity";
function extractUsernameFromToken(accessToken: AccessToken): string{
const base64Metadata = accessToken.token.split(".")[1];
const { oid } = JSON.parse(
Buffer.from(base64Metadata, "base64").toString("utf8"),
);
return oid;
}
async function main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_REDIS_TENANTID;
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const clientSecret = process.env.AZURE_REDIS_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
const redisScope = "https://redis.azure.com/.default";
let accessToken = await credential.getToken(redisScope);
console.log("access Token", accessToken);
const host = process.env.AZURE_REDIS_HOST;
// Create redis client and connect to Azure Cache for Redis over the TLS port using the access token as password.
const client = createClient({
username: extractUsernameFromToken(accessToken),
password: accessToken.token,
url: `redis://${host}:6380`,
pingInterval: 100000,
socket: {
tls: true,
keepAlive: 0
},
});
client.on("error", (err) => console.log("Redis Client Error", err));
await client.connect();
// Set a value against your key in Azure Redis Cache.
await client.set("Az:key", "value1312");
// Get value of your key in Azure Redis Cache.
console.log("value-", await client.get("Az:key"));
}
main().catch((err) => {
console.log("error code: ", err.code);
console.log("error message: ", err.message);
console.log("error stack: ", err.stack);
});
針對其他語言,您可以使用 Azure 身分識別用戶端連結庫(以及 Service Connector 設定為環境變數的連線資訊)來連線到 Azure Cache for Redis。
相關內容