本文介绍支持的身份验证方法、客户端和示例代码,你可通过它们使用服务连接器将应用连接到 Azure Cache for Redis。在本文中,你还将找到创建服务连接时获取的默认环境变量名称、值和配置。
受支持的计算服务
可使用服务连接器将以下计算服务连接到 Azure Cache for Redis:
- Azure 应用服务
- Azure 容器应用
- Azure Functions
- Azure Kubernetes 服务 (AKS)
- Azure Spring Apps
受支持的身份验证和客户端类型
下表显示了使用服务连接器将计算服务连接到 Azure Cache for Redis 时所支持的身份验证方法与客户端的组合。 “是”表示组合受到支持。 “否”表示不受支持。
客户端类型 |
系统分配的托管标识 |
用户分配的托管标识 |
机密/连接字符串 |
服务主体 |
.NET |
是 |
是 |
是 |
是 |
Go |
否 |
否 |
是 |
否 |
Java |
是 |
是 |
是 |
是 |
Java - Spring Boot |
否 |
否 |
是 |
否 |
Node.js |
是 |
是 |
是 |
是 |
Python |
是 |
是 |
是 |
是 |
无 |
是 |
是 |
是 |
是 |
默认环境变量名称或应用程序属性和示例代码
使用下面的环境变量名称和应用程序属性将计算服务连接到 Redis 服务器。 若要详细了解命名约定,请参阅服务连接器内部一文。
系统分配的托管标识
默认环境变量名称 |
说明 |
示例值 |
AZURE_REDIS_HOST |
Redis 终结点 |
<RedisName>.redis.cache.windows.net |
示例代码
下面的步骤和代码显示如何使用系统分配的托管标识连接到 Redis。
安装依赖项。
dotnet add package Microsoft.Azure.StackExchangeRedis --version 3.2.0
使用服务连接器设置的环境变量添加身份验证逻辑。 有关详细信息,请参阅 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>
使用服务连接器设置的环境变量添加身份验证逻辑。 有关详细信息,请参阅 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
使用服务连接器设置的环境变量添加身份验证逻辑。 有关详细信息,请参阅 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
使用服务连接器设置的环境变量添加身份验证逻辑。 有关详细信息,请参阅 Azure Cache for Redis:使用 node-redis 客户端库的 Microsoft Entra ID。
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 标识客户端库和连接信息来连接到 Azure Cache for Redis。
用户分配的托管标识
默认环境变量名称 |
说明 |
示例值 |
AZURE_REDIS_HOST |
Redis 终结点 |
<RedisName>.redis.cache.windows.net |
AZURE_REDIS_CLIENTID |
托管标识客户端 ID |
<client-ID> |
示例代码
下面的步骤和代码显示如何使用用户分配的托管标识连接到 Redis。
安装依赖项。
dotnet add package Microsoft.Azure.StackExchangeRedis --version 3.2.0
使用服务连接器设置的环境变量添加身份验证逻辑。 有关详细信息,请参阅 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>
使用服务连接器设置的环境变量添加身份验证逻辑。 有关详细信息,请参阅 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
使用服务连接器设置的环境变量添加身份验证逻辑。 有关详细信息,请参阅 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
使用服务连接器设置的环境变量添加身份验证逻辑。 有关详细信息,请参阅 Azure Cache for Redis:使用 node-redis 客户端库的 Microsoft Entra ID。
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 标识客户端库和连接信息来连接到 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);
- 安装依赖项。
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 |
服务主体的客户端 ID |
<client-ID> |
AZURE_REDIS_CLIENTSECRET |
服务主体的机密 |
<client-secret> |
AZURE_REDIS_TENANTID |
服务主体的租户 ID |
<tenant-id> |
示例代码
下面的步骤和代码显示如何使用服务主体连接到 Redis。
安装依赖项。
dotnet add package Microsoft.Azure.StackExchangeRedis --version 3.2.0
使用服务连接器设置的环境变量添加身份验证逻辑。 有关详细信息,请参阅 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>
使用服务连接器设置的环境变量添加身份验证逻辑。 有关详细信息,请参阅 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
使用服务连接器设置的环境变量添加身份验证逻辑。 有关详细信息,请参阅 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
使用服务连接器设置的环境变量添加身份验证逻辑。 有关详细信息,请参阅 Azure Cache for Redis:使用 node-redis 客户端库的 Microsoft Entra ID。
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 标识客户端库和连接信息来连接到 Azure Cache for Redis。
相关内容