W tym artykule opisano obsługiwane metody uwierzytelniania, klientów i przykładowy kod, którego można użyć do łączenia aplikacji z usługą Azure Cache for Redis przy użyciu usługi Service Connector.In tym artykule, znajdziesz również domyślne nazwy zmiennych środowiskowych, wartości i konfigurację uzyskaną podczas tworzenia połączeń usług.
Obsługiwane usługi obliczeniowe
Łącznik usługi umożliwia połączenie następujących usług obliczeniowych z usługą Azure Cache for Redis:
- Azure App Service
- Azure Container Apps
- Azure Functions (Funkcje Azure)
- Azure Kubernetes Service (AKS)
- Azure Spring Apps
Obsługiwane typy uwierzytelniania i klientów
W poniższej tabeli przedstawiono kombinacje metod uwierzytelniania i klientów obsługiwanych do łączenia usługi obliczeniowej z usługą Azure Cache for Redis przy użyciu łącznika usługi Service Connector. Wartość "Tak" oznacza, że kombinacja jest obsługiwana. Wartość "Nie" oznacza, że nie jest obsługiwana.
Typ klienta |
Zarządzana tożsamość przypisana przez system |
Tożsamość zarządzana przypisana przez użytkownika |
Klucz tajny/parametry połączenia |
Główny identyfikator usługi |
.NET |
Tak |
Tak |
Tak |
Tak |
Idź |
Nie |
Nie |
Tak |
Nie |
Jawa |
Tak |
Tak |
Tak |
Tak |
Java — Spring Boot |
Nie |
Nie |
Tak |
Nie |
Node.js |
Tak |
Tak |
Tak |
Tak |
Pyton |
Tak |
Tak |
Tak |
Tak |
Brak |
Tak |
Tak |
Tak |
Tak |
Domyślne nazwy zmiennych środowiskowych lub właściwości aplikacji i przykładowy kod
Użyj następujących nazw zmiennych środowiskowych i właściwości aplikacji, aby połączyć usługi obliczeniowe z serwerem Redis. Aby dowiedzieć się więcej na temat konwencji nazewnictwa, zapoznaj się z artykułem o wewnętrznych mechanizmach Service Connector.
Zarządzana tożsamość przypisana przez system
Domyślna nazwa zmiennej środowiskowej |
opis |
Przykładowa wartość |
AZURE_REDIS_HOST |
Punkt końcowy usługi Redis |
<RedisName>.redis.cache.windows.net |
Przykładowy kod
Poniższe kroki i kod pokazują, jak używać przypisanej przez system tożsamości zarządzanej w celu nawiązania połączenia z usługą Redis.
Instalowanie zależności.
dotnet add package Microsoft.Azure.StackExchangeRedis --version 3.2.0
Dodaj logikę uwierzytelniania ze zmiennymi środowiskowymi ustawionymi przez łącznik usługi. Aby uzyskać więcej informacji, zobacz Rozszerzenie 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);
Dodaj następującą zależność w pom.xml
pliku:
<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>
Dodaj logikę uwierzytelniania ze zmiennymi środowiskowymi ustawionymi przez łącznik usługi. Aby uzyskać więcej informacji, zobacz 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();
Instalowanie zależności.
pip install redis azure-identity
Dodaj logikę uwierzytelniania ze zmiennymi środowiskowymi ustawionymi przez łącznik usługi. Aby uzyskać więcej informacji, zobacz 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()
Instalowanie zależności.
npm install redis @azure/identity
Dodaj logikę uwierzytelniania ze zmiennymi środowiskowymi ustawionymi przez łącznik usługi. Aby uzyskać więcej informacji, zobacz Azure Cache for Redis: Microsoft Entra ID za pomocą biblioteki klienta 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);
});
W przypadku innych języków możesz użyć biblioteki klienta Azure Identity (i informacji o połączeniu ustawianych w zmiennych środowiskowych przez Service Connector), aby nawiązać połączenie z usługą Azure Cache for Redis.
Tożsamość zarządzana przypisana przez użytkownika
Domyślna nazwa zmiennej środowiskowej |
opis |
Przykładowa wartość |
AZURE_REDIS_HOST |
Punkt końcowy usługi Redis |
<RedisName>.redis.cache.windows.net |
AZURE_REDIS_CLIENTID |
Identyfikator klienta zarządzanej tożsamości |
<client-ID> |
Przykładowy kod
Poniższe kroki i kod pokazują, jak używać tożsamości zarządzanej przypisanej przez użytkownika do nawiązywania połączenia z usługą Redis.
Instalowanie zależności.
dotnet add package Microsoft.Azure.StackExchangeRedis --version 3.2.0
Dodaj logikę uwierzytelniania ze zmiennymi środowiskowymi ustawionymi przez łącznik usługi. Aby uzyskać więcej informacji, zobacz Rozszerzenie 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);
Dodaj następującą zależność w pom.xml
pliku:
<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>
Dodaj logikę uwierzytelniania ze zmiennymi środowiskowymi ustawionymi przez łącznik usługi. Aby uzyskać więcej informacji, zobacz 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();
Instalowanie zależności.
pip install redis azure-identity
Dodaj logikę uwierzytelniania ze zmiennymi środowiskowymi ustawionymi przez łącznik usługi. Aby uzyskać więcej informacji, zobacz 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()
Instalowanie zależności.
npm install redis @azure/identity
Dodaj logikę uwierzytelniania ze zmiennymi środowiskowymi ustawionymi przez łącznik usługi. Aby uzyskać więcej informacji, zobacz Azure Cache for Redis: Microsoft Entra ID za pomocą biblioteki klienta 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);
});
W przypadku innych języków możesz użyć biblioteki klienta Azure Identity (i informacji o połączeniu ustawianych w zmiennych środowiskowych przez Service Connector), aby nawiązać połączenie z usługą Azure Cache for Redis.
ciąg połączenia
Ostrzeżenie
Zalecamy korzystanie z najbezpieczniejszego dostępnego przepływu uwierzytelniania. Opisany tutaj przepływ uwierzytelniania wymaga bardzo wysokiego poziomu zaufania w aplikacji i niesie ze sobą ryzyko, które nie są obecne w innych przepływach. Tego przepływu należy używać tylko wtedy, gdy bardziej bezpieczne przepływy, takie jak tożsamości zarządzane, nie są opłacalne.
Domyślna nazwa zmiennej środowiskowej |
opis |
Przykładowa wartość |
AZURE_REDIS_CONNECTIONSTRING |
StackExchange.Redis łańcuch połączenia |
<redis-server-name>.redis.cache.windows.net:6380,password=<redis-key>,ssl=True,defaultDatabase=0 |
Domyślna nazwa zmiennej środowiskowej |
opis |
Przykładowa wartość |
AZURE_REDIS_CONNECTIONSTRING |
Łańcuch połączenia Jedis |
rediss://:<redis-key>@<redis-server-name>.redis.cache.windows.net:6380/0 |
Właściwości aplikacji |
opis |
Przykładowa wartość |
spring.redis.host |
Host usługi Redis |
<redis-server-name>.redis.cache.windows.net |
spring.redis.port |
Port Redis |
6380 |
spring.redis.database |
Baza danych Redis |
0 |
spring.redis.password |
Klucz usługi Redis |
<redis-key> |
spring.redis.ssl |
Ustawienie protokołu SSL |
true |
Domyślna nazwa zmiennej środowiskowej |
opis |
Przykładowa wartość |
AZURE_REDIS_CONNECTIONSTRING |
redis-py łańcuch połączenia |
rediss://:<redis-key>@<redis-server-name>.redis.cache.windows.net:6380/0 |
Domyślna nazwa zmiennej środowiskowej |
opis |
Przykładowa wartość |
AZURE_REDIS_CONNECTIONSTRING |
redis-py łańcuch połączenia |
rediss://:<redis-key>@<redis-server-name>.redis.cache.windows.net:6380/0 |
Domyślna nazwa zmiennej środowiskowej |
opis |
Przykładowa wartość |
AZURE_REDIS_CONNECTIONSTRING |
node-redis łańcuch połączenia |
rediss://:<redis-key>@<redis-server-name>.redis.cache.windows.net:6380/0 |
Domyślna nazwa zmiennej środowiskowej |
opis |
Przykładowa wartość |
AZURE_REDIS_HOST |
Host usługi Redis |
<redis-server-name>.redis.cache.windows.net |
AZURE_REDIS_PORT |
Port Redis |
6380 |
AZURE_REDIS_DATABASE |
Baza danych Redis |
0 |
AZURE_REDIS_PASSWORD |
Klucz usługi Redis |
<redis-key> |
AZURE_REDIS_SSL |
Ustawienie protokołu SSL |
true |
Przykładowy kod
Poniższe kroki i kod pokazują, jak używać ciągu połączenia, aby połączyć się z usługą Azure Cache for Redis.
Instalowanie zależności.
dotnet add package StackExchange.Redis --version 2.6.122
Pobierz parametry połączenia ze zmiennej środowiskowej dodanej przez łącznik usługi.
using StackExchange.Redis;
var connectionString = Environment.GetEnvironmentVariable("AZURE_REDIS_CONNECTIONSTRING");
var _redisConnection = await RedisConnection.InitializeAsync(connectionString: connectionString);
- Dodaj następującą zależność w
pom.xml
pliku: <dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.1.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
- Pobierz parametry połączenia ze zmiennej środowiskowej dodanej przez łącznik usługi.
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);
- Instalowanie zależności.
pip install redis
- Pobierz parametry połączenia ze zmiennej środowiskowej dodanej przez łącznik usługi.
import os
import redis
url = os.getenv('AZURE_REDIS_CONNECTIONSTRING')
url_connection = redis.from_url(url)
url_connection.ping()
- Instalowanie zależności.
go get github.com/redis/go-redis/v9
- Pobierz parametry połączenia ze zmiennej środowiskowej dodanej przez łącznik usługi.
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)
Instalowanie zależności.
npm install redis
Pobierz parametry połączenia ze zmiennej środowiskowej dodanej przez łącznik usługi.
const redis = require("redis");
const connectionString = process.env.AZURE_REDIS_CONNECTIONSTRING;
const cacheConnection = redis.createClient({
url: connectionString,
});
await cacheConnection.connect();
W przypadku innych języków można użyć informacji o połączeniu, które łącznik usługi ustawia na zmienne środowiskowe w celu nawiązania połączenia z usługą Azure Cache for Redis.
Główny identyfikator usługi
Domyślna nazwa zmiennej środowiskowej |
opis |
Przykładowa wartość |
AZURE_REDIS_HOST |
Punkt końcowy usługi Redis |
<RedisName>.redis.cache.windows.net |
AZURE_REDIS_CLIENTID |
Identyfikator klienta zleceniodawcy usługi |
<client-ID> |
AZURE_REDIS_CLIENTSECRET |
Sekret głównego obiektu usługi |
<client-secret> |
AZURE_REDIS_TENANTID |
Identyfikator dzierżawy podmiotu usługi |
<tenant-id> |
Przykładowy kod
Poniższe kroki i kod pokazują, jak używać głównego konta usługi do łączenia się z Redis.
Instalowanie zależności.
dotnet add package Microsoft.Azure.StackExchangeRedis --version 3.2.0
Dodaj logikę uwierzytelniania ze zmiennymi środowiskowymi ustawionymi przez łącznik usługi. Aby uzyskać więcej informacji, zobacz Rozszerzenie 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);
Dodaj następującą zależność w pom.xml
pliku:
<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>
Dodaj logikę uwierzytelniania ze zmiennymi środowiskowymi ustawionymi przez łącznik usługi. Aby uzyskać więcej informacji, zobacz 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();
Instalowanie zależności.
pip install redis azure-identity
Dodaj logikę uwierzytelniania ze zmiennymi środowiskowymi ustawionymi przez łącznik usługi. Aby uzyskać więcej informacji, zobacz 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()
Instalowanie zależności.
npm install redis @azure/identity
Dodaj logikę uwierzytelniania ze zmiennymi środowiskowymi ustawionymi przez łącznik usługi. Aby uzyskać więcej informacji, zobacz Azure Cache for Redis: Microsoft Entra ID za pomocą biblioteki klienta 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);
});
W przypadku innych języków możesz użyć biblioteki klienta Azure Identity (i informacji o połączeniu ustawianych w zmiennych środowiskowych przez Service Connector), aby nawiązać połączenie z usługą Azure Cache for Redis.
Powiązana zawartość