Integrace služby Azure Cache for Redis s konektorem služby
Článek
Azure Cache for Redis můžete připojit k dalším cloudovým službám pomocí konektoru služby. Tento článek popisuje podporované metody ověřování a klienty a poskytuje vzorový kód. Zobrazí se také výchozí názvy proměnných prostředí a hodnoty (nebo konfigurace Spring Bootu), které získáte při vytváření připojení služby.
Podporované výpočetní služby
Konektor služby můžete použít k připojení následujících výpočetních služeb ke službě Azure Cache for Redis:
Azure App Service
Azure Container Apps
Azure Functions
Azure Kubernetes Service (AKS)
Azure Spring Apps
Podporované typy ověřování a klientů
Následující tabulka ukazuje, které kombinace metod ověřování a klientů se podporují pro připojení výpočetní služby ke službě Azure Cache for Redis pomocí konektoru služby. "Ano" znamená, že kombinace je podporovaná. "Ne" znamená, že se nepodporuje.
Typ klienta
Spravovaná identita přiřazená systémem
Spravovaná identita přiřazená uživatelem
Tajný kód / připojovací řetězec
Instanční objekt
.NET
Ano
Ano
Ano
Yes
Go
No
No
Ano
No
Java
Ano
Ano
Ano
Yes
Java – Spring Boot
No
No
Ano
No
Node.js
Ano
Ano
Ano
Yes
Python
Ano
Ano
Ano
Yes
Nic
Ano
Ano
Ano
Yes
Všechny typy klientů, s výjimkou Go a Java – Spring Boot, můžou použít některou z metod ověřování odkazovaných v tabulce k připojení ke službě Azure Cache for Redis pomocí konektoru služby. Jediné podporované metody ověřování pro Go a Javu – Spring Boot jsou tajné kódy nebo připojovací řetězec nebo instanční objekt.
Výchozí názvy proměnných prostředí nebo vlastnosti aplikace a ukázkový kód
Pomocí následujících názvů proměnných prostředí a vlastností aplikace připojte výpočetní služby k serveru Redis. Další informace o konvencích vytváření názvů najdete v interním článku o konektoru služby.
Spravovaná identita přiřazená systémem
Výchozí název proměnné prostředí
Popis
Ukázková hodnota
AZURE_REDIS_HOST
Koncový bod Redis
<RedisName>.redis.cache.windows.net
Ukázkový kód
Následující kroky a kód ukazují, jak použít spravovanou identitu přiřazenou systémem pro připojení k Redisu.
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);
Do souboru přidejte následující závislost pom.xml :
Přidejte logiku ověřování s proměnnými prostředí nastavenými konektorem Service Connector. Další informace najdete v tématu 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();
Zatím není podporováno.
Nainstalujte závislosti.
pip install redis azure-identity
Přidejte logiku ověřování s proměnnými prostředí nastavenými konektorem Service Connector. Další informace najdete v tématu 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()
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);
});
V jiných jazycích můžete pro připojení ke službě Azure Cache for Redis použít klientskou knihovnu Azure Identity (a informace o připojení, které Service Connector nastaví na proměnné prostředí).
Spravovaná identita přiřazená uživatelem
Výchozí název proměnné prostředí
Popis
Ukázková hodnota
AZURE_REDIS_HOST
Koncový bod Redis
<RedisName>.redis.cache.windows.net
AZURE_REDIS_CLIENTID
ID klienta spravované identity
<client-ID>
Ukázkový kód
Následující kroky a kód ukazují, jak se pomocí spravované identity přiřazené uživatelem připojit k Redisu.
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);
Do souboru přidejte následující závislost pom.xml :
Přidejte logiku ověřování s proměnnými prostředí nastavenými konektorem Service Connector. Další informace najdete v tématu 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();
Zatím není podporováno.
Nainstalujte závislosti.
pip install redis azure-identity
Přidejte logiku ověřování s proměnnými prostředí nastavenými konektorem Service Connector. Další informace najdete v tématu 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()
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);
});
V jiných jazycích můžete pro připojení ke službě Azure Cache for Redis použít klientskou knihovnu Azure Identity (a informace o připojení, které Service Connector nastaví na proměnné prostředí).
Connection string
Upozorňující
Doporučujeme používat nejbezpečnější dostupný tok ověřování. Zde popsaný tok ověřování vyžaduje velmi vysoký stupeň důvěryhodnosti v aplikaci a nese rizika, která nejsou přítomna v jiných tocích. Tento tok byste měli použít jenom v případě, že bezpečnější toky, jako jsou spravované identity, nejsou přijatelné.
Získejte připojovací řetězec z proměnné prostředí přidané konektorem služby.
using StackExchange.Redis;
var connectionString = Environment.GetEnvironmentVariable("AZURE_REDIS_CONNECTIONSTRING");
var _redisConnection = await RedisConnection.InitializeAsync(connectionString: connectionString);
Do souboru přidejte následující závislost pom.xml :
Získejte připojovací řetězec z proměnné prostředí přidané konektorem služby.
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);
Pokud chcete nastavit aplikaci Spring, přečtěte si článek o použití Azure Redis Cache na Springu. Service Connector přidá vlastnosti konfigurace do aplikace Spring Apps.
Nainstalujte závislosti.
pip install redis
Získejte připojovací řetězec z proměnné prostředí přidané konektorem služby.
V jiných jazycích můžete použít informace o připojení, které Service Connector nastaví na proměnné prostředí pro připojení ke službě Azure Cache for Redis.
Instanční objekt
Výchozí název proměnné prostředí
Popis
Ukázková hodnota
AZURE_REDIS_HOST
Koncový bod Redis
<RedisName>.redis.cache.windows.net
AZURE_REDIS_CLIENTID
ID klienta instančního objektu.
<client-ID>
AZURE_REDIS_CLIENTSECRET
Tajný kód instančního objektu
<client-secret>
AZURE_REDIS_TENANTID
ID tenanta instančního objektu
<tenant-id>
Ukázkový kód
Následující kroky a kód ukazují, jak se pomocí instančního objektu připojit k Redis.
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);
Do souboru přidejte následující závislost pom.xml :
Přidejte logiku ověřování s proměnnými prostředí nastavenými konektorem Service Connector. Další informace najdete v tématu 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();
Zatím není podporováno.
Nainstalujte závislosti.
pip install redis azure-identity
Přidejte logiku ověřování s proměnnými prostředí nastavenými konektorem Service Connector. Další informace najdete v tématu 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()
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);
});
V jiných jazycích můžete pro připojení ke službě Azure Cache for Redis použít klientskou knihovnu Azure Identity (a informace o připojení, které Service Connector nastaví na proměnné prostředí).