この記事では、Service Connector を使用してアプリを Azure Cache for Redis に接続するために使用できるサポートされている認証方法、クライアント、サンプル コードについて説明します。また、この記事では、サービス接続の作成時に取得される既定の環境変数の名前、値、構成についても説明します。
サポートされているコンピューティング サービス
Service Connector を使うと、次のコンピューティング サービスを Azure Cache for Redis に接続できます。
- Azure App Service
- Azure コンテナ アプリ
- Azure Functions (アジュール ファンクションズ)
- Azure Kubernetes Service (AKS)
- Azure Spring Apps
サポートされている認証とクライアントの種類
次の表は、Service Connector を使った Azure Cache for Redis へのコンピューティング サービスの接続でサポートされている認証方法とクライアントの組み合わせを示したものです。 "はい" は、組み合わせがサポートされていることを意味します。 "いいえ" は、サポートされていないことを意味します。
クライアントの種類 |
システム割り当てマネージド ID |
ユーザー割り当てマネージド ID |
シークレット/接続文字列 |
サービス プリンシパル |
.NET |
はい |
はい |
はい |
はい |
Go |
いいえ |
いいえ |
はい |
いいえ |
ジャワ |
はい |
はい |
はい |
はい |
Java - Spring Boot |
いいえ |
いいえ |
はい |
いいえ |
Node.js |
はい |
はい |
はい |
はい |
Python(プログラミング言語) |
はい |
はい |
はい |
はい |
なし |
はい |
はい |
はい |
はい |
既定の環境変数名またはアプリケーション プロパティとサンプル コード
コンピューティング サービスを Redis サーバーに接続するには、次の環境変数名とアプリケーション プロパティを使用します。 名前付け規則の詳細については、「Service Connector の内部構造」の記事を参照してください。
システム割り当てマネージド ID
既定の環境変数名 |
説明 |
値の例 |
AZURE_REDIS_HOST |
Redis エンドポイント |
<RedisName>.redis.cache.windows.net |
サンプル コード
次の手順とコードは、システム割り当てマネージド ID を使って Redis に接続する方法を示しています。
依存関係をインストールします。
dotnet add package Microsoft.Azure.StackExchangeRedis --version 3.2.0
Service Connector によって設定された環境変数を使用して認証ロジックを追加します。 詳しくは、Microsoft.Azure.StackExchangeRedis 拡張機能のページを参照してください。
using StackExchange.Redis;
var cacheHostName = Environment.GetEnvironmentVariable("AZURE_REDIS_HOST");
var configurationOptions = ConfigurationOptions.Parse($"{cacheHostName}:6380");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
// For user-assigned identity.
// var managedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// await configurationOptions.ConfigureForAzureWithUserAssignedManagedIdentityAsync(managedIdentityClientId);
// Service principal secret.
// var clientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// var tenantId = Environment.GetEnvironmentVariable("AZURE_REDIS_TENANTID");
// var secret = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTSECRET");
// await configurationOptions.ConfigureForAzureWithServicePrincipalAsync(clientId, tenantId, secret);
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
pom.xml
ファイルに次の依存関係を追加します。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.11.2</version> <!-- {x-version-update;com.azure:azure-identity;dependency} -->
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>5.1.0</version> <!-- {x-version-update;redis.clients:jedis;external_dependency} -->
</dependency>
Service Connector によって設定された環境変数を使用して認証ロジックを追加します。 詳しくは、Azure-AAD-Authentication-With-Jedis を参照してください。
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import java.net.URI;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
// For user-assigned identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().managedIdentityClientId(clientId).build();
// For AKS workload identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().workloadIdentityClientId(clientId).build();
// For service principal.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// String secret = System.getenv("AZURE_REDIS_CLIENTSECRET");
// String tenant = System.getenv("AZURE_REDIS_TENANTID");
// ClientSecretCredential defaultAzureCredential = new ClientSecretCredentialBuilder().tenantId(tenant).clientId(clientId).clientSecret(secret).build();
String token = defaultAzureCredential
.getToken(new TokenRequestContext()
.addScopes("https://redis.azure.com/.default")).block().getToken();
// SSL connection is required.
boolean useSsl = true;
// TODO: Replace Host Name with Azure Cache for Redis Host Name.
String username = extractUsernameFromToken(token);
String cacheHostname = System.getenv("AZURE_REDIS_HOST");
// Create Jedis client and connect to Azure Cache for Redis over the TLS/SSL port using the access token as password.
// Note, Redis Cache host name and port are required below.
Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
.password(token) // Microsoft Entra access token as password is required.
.user(username) // Username is Required
.ssl(useSsl) // SSL Connection is Required
.build());
// Set a value against your key in the Redis cache.
jedis.set("Az:key", "testValue");
System.out.println(jedis.get("Az:key"));
// Close the Jedis Client
jedis.close();
依存関係をインストールします。
pip install redis azure-identity
Service Connector によって設定された環境変数を使用して認証ロジックを追加します。 詳しくは、azure-aad-auth-with-redis-py を参照してください。
import os
import time
import logging
import redis
import base64
import json
from azure.identity import DefaultAzureCredential
host = os.getenv('AZURE_REDIS_HOST')
scope = "https://redis.azure.com/.default"
port = 6380 # Required
def extract_username_from_token(token):
parts = token.split('.')
base64_str = parts[1]
if len(base64_str) % 4 == 2:
base64_str += "=="
elif len(base64_str) % 4 == 3:
base64_str += "="
json_bytes = base64.b64decode(base64_str)
json_str = json_bytes.decode('utf-8')
jwt = json.loads(json_str)
return jwt['oid']
def re_authentication():
_LOGGER = logging.getLogger(__name__)
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For service principal.
# tenant_id = os.getenv("AZURE_TENANT_ID")
# client_id = os.getenv("AZURE_CLIENT_ID")
# client_secret = os.getenv("AZURE_CLIENT_SECRET")
# cred = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
token = cred.get_token(scope)
user_name = extract_username_from_token(token.token)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
max_retry = 3
for index in range(max_retry):
try:
if _need_refreshing(token):
_LOGGER.info("Refreshing token...")
tmp_token = cred.get_token(scope)
if tmp_token:
token = tmp_token
r.execute_command("AUTH", user_name, token.token)
r.set("Az:key1", "value1")
t = r.get("Az:key1")
print(t)
break
except redis.ConnectionError:
_LOGGER.info("Connection lost. Reconnecting.")
token = cred.get_token(scope)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
except Exception:
_LOGGER.info("Unknown failures.")
break
def _need_refreshing(token, refresh_offset=300):
return not token or token.expires_on - time.time() < refresh_offset
if __name__ == '__main__':
re_authentication()
依存関係をインストールします。
npm install redis @azure/identity
Service Connector によって設定された環境変数を使用して認証ロジックを追加します。 詳しくは、「Azure Cache for Redis: Microsoft Entra ID と node-redis クライアント ライブラリ」を参照してください。
import { createClient } from "redis";
import { DefaultAzureCredential } from "@azure/identity";
function extractUsernameFromToken(accessToken: AccessToken): string{
const base64Metadata = accessToken.token.split(".")[1];
const { oid } = JSON.parse(
Buffer.from(base64Metadata, "base64").toString("utf8"),
);
return oid;
}
async function main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_REDIS_TENANTID;
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const clientSecret = process.env.AZURE_REDIS_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
const redisScope = "https://redis.azure.com/.default";
let accessToken = await credential.getToken(redisScope);
console.log("access Token", accessToken);
const host = process.env.AZURE_REDIS_HOST;
// Create redis client and connect to Azure Cache for Redis over the TLS port using the access token as password.
const client = createClient({
username: extractUsernameFromToken(accessToken),
password: accessToken.token,
url: `redis://${host}:6380`,
pingInterval: 100000,
socket: {
tls: true,
keepAlive: 0
},
});
client.on("error", (err) => console.log("Redis Client Error", err));
await client.connect();
// Set a value against your key in Azure Redis Cache.
await client.set("Az:key", "value1312");
// Get value of your key in Azure Redis Cache.
console.log("value-", await client.get("Az:key"));
}
main().catch((err) => {
console.log("error code: ", err.code);
console.log("error message: ", err.message);
console.log("error stack: ", err.stack);
});
他の言語の場合は、Azure ID クライアント ライブラリ (および Service Connector が環境変数に設定する接続情報) を使って、Azure Cache for Redis に接続できます。
ユーザー割り当てマネージド ID
既定の環境変数名 |
説明 |
値の例 |
AZURE_REDIS_HOST |
Redis エンドポイント |
<RedisName>.redis.cache.windows.net |
AZURE_REDIS_CLIENTID |
マネージド ID のクライアント ID |
<client-ID> |
サンプル コード
次の手順とコードは、ユーザー割り当てマネージド ID を使って Redis に接続する方法を示しています。
依存関係をインストールします。
dotnet add package Microsoft.Azure.StackExchangeRedis --version 3.2.0
Service Connector によって設定された環境変数を使用して認証ロジックを追加します。 詳しくは、Microsoft.Azure.StackExchangeRedis 拡張機能のページを参照してください。
using StackExchange.Redis;
var cacheHostName = Environment.GetEnvironmentVariable("AZURE_REDIS_HOST");
var configurationOptions = ConfigurationOptions.Parse($"{cacheHostName}:6380");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
// For user-assigned identity.
// var managedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// await configurationOptions.ConfigureForAzureWithUserAssignedManagedIdentityAsync(managedIdentityClientId);
// Service principal secret.
// var clientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// var tenantId = Environment.GetEnvironmentVariable("AZURE_REDIS_TENANTID");
// var secret = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTSECRET");
// await configurationOptions.ConfigureForAzureWithServicePrincipalAsync(clientId, tenantId, secret);
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
pom.xml
ファイルに次の依存関係を追加します。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.11.2</version> <!-- {x-version-update;com.azure:azure-identity;dependency} -->
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>5.1.0</version> <!-- {x-version-update;redis.clients:jedis;external_dependency} -->
</dependency>
Service Connector によって設定された環境変数を使用して認証ロジックを追加します。 詳しくは、Azure-AAD-Authentication-With-Jedis を参照してください。
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import java.net.URI;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
// For user-assigned identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().managedIdentityClientId(clientId).build();
// For AKS workload identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().workloadIdentityClientId(clientId).build();
// For service principal.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// String secret = System.getenv("AZURE_REDIS_CLIENTSECRET");
// String tenant = System.getenv("AZURE_REDIS_TENANTID");
// ClientSecretCredential defaultAzureCredential = new ClientSecretCredentialBuilder().tenantId(tenant).clientId(clientId).clientSecret(secret).build();
String token = defaultAzureCredential
.getToken(new TokenRequestContext()
.addScopes("https://redis.azure.com/.default")).block().getToken();
// SSL connection is required.
boolean useSsl = true;
// TODO: Replace Host Name with Azure Cache for Redis Host Name.
String username = extractUsernameFromToken(token);
String cacheHostname = System.getenv("AZURE_REDIS_HOST");
// Create Jedis client and connect to Azure Cache for Redis over the TLS/SSL port using the access token as password.
// Note, Redis Cache host name and port are required below.
Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
.password(token) // Microsoft Entra access token as password is required.
.user(username) // Username is Required
.ssl(useSsl) // SSL Connection is Required
.build());
// Set a value against your key in the Redis cache.
jedis.set("Az:key", "testValue");
System.out.println(jedis.get("Az:key"));
// Close the Jedis Client
jedis.close();
依存関係をインストールします。
pip install redis azure-identity
Service Connector によって設定された環境変数を使用して認証ロジックを追加します。 詳しくは、azure-aad-auth-with-redis-py を参照してください。
import os
import time
import logging
import redis
import base64
import json
from azure.identity import DefaultAzureCredential
host = os.getenv('AZURE_REDIS_HOST')
scope = "https://redis.azure.com/.default"
port = 6380 # Required
def extract_username_from_token(token):
parts = token.split('.')
base64_str = parts[1]
if len(base64_str) % 4 == 2:
base64_str += "=="
elif len(base64_str) % 4 == 3:
base64_str += "="
json_bytes = base64.b64decode(base64_str)
json_str = json_bytes.decode('utf-8')
jwt = json.loads(json_str)
return jwt['oid']
def re_authentication():
_LOGGER = logging.getLogger(__name__)
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For service principal.
# tenant_id = os.getenv("AZURE_TENANT_ID")
# client_id = os.getenv("AZURE_CLIENT_ID")
# client_secret = os.getenv("AZURE_CLIENT_SECRET")
# cred = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
token = cred.get_token(scope)
user_name = extract_username_from_token(token.token)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
max_retry = 3
for index in range(max_retry):
try:
if _need_refreshing(token):
_LOGGER.info("Refreshing token...")
tmp_token = cred.get_token(scope)
if tmp_token:
token = tmp_token
r.execute_command("AUTH", user_name, token.token)
r.set("Az:key1", "value1")
t = r.get("Az:key1")
print(t)
break
except redis.ConnectionError:
_LOGGER.info("Connection lost. Reconnecting.")
token = cred.get_token(scope)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
except Exception:
_LOGGER.info("Unknown failures.")
break
def _need_refreshing(token, refresh_offset=300):
return not token or token.expires_on - time.time() < refresh_offset
if __name__ == '__main__':
re_authentication()
依存関係をインストールします。
npm install redis @azure/identity
Service Connector によって設定された環境変数を使用して認証ロジックを追加します。 詳しくは、「Azure Cache for Redis: Microsoft Entra ID と node-redis クライアント ライブラリ」を参照してください。
import { createClient } from "redis";
import { DefaultAzureCredential } from "@azure/identity";
function extractUsernameFromToken(accessToken: AccessToken): string{
const base64Metadata = accessToken.token.split(".")[1];
const { oid } = JSON.parse(
Buffer.from(base64Metadata, "base64").toString("utf8"),
);
return oid;
}
async function main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_REDIS_TENANTID;
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const clientSecret = process.env.AZURE_REDIS_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
const redisScope = "https://redis.azure.com/.default";
let accessToken = await credential.getToken(redisScope);
console.log("access Token", accessToken);
const host = process.env.AZURE_REDIS_HOST;
// Create redis client and connect to Azure Cache for Redis over the TLS port using the access token as password.
const client = createClient({
username: extractUsernameFromToken(accessToken),
password: accessToken.token,
url: `redis://${host}:6380`,
pingInterval: 100000,
socket: {
tls: true,
keepAlive: 0
},
});
client.on("error", (err) => console.log("Redis Client Error", err));
await client.connect();
// Set a value against your key in Azure Redis Cache.
await client.set("Az:key", "value1312");
// Get value of your key in Azure Redis Cache.
console.log("value-", await client.get("Az:key"));
}
main().catch((err) => {
console.log("error code: ", err.code);
console.log("error message: ", err.message);
console.log("error stack: ", err.stack);
});
他の言語の場合は、Azure ID クライアント ライブラリ (および Service Connector が環境変数に設定する接続情報) を使って、Azure Cache for Redis に接続できます。
接続文字列
警告
使用可能な最も安全な認証フローを使用することをお勧めします。 ここで示される認証フローでは、アプリケーションで非常に高い信頼度が要求されるため、他のフローには存在しないリスクが伴います。 このフローは、マネージド ID などのより安全なフローが実行可能ではない場合にのみ使用してください。
既定の環境変数名 |
説明 |
値の例 |
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
Service Connector によって追加された環境変数から接続文字列を取得します。
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>
- Service Connector によって追加された環境変数から接続文字列を取得します。
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
- Service Connector によって追加された環境変数から接続文字列を取得します。
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
- Service Connector によって追加された環境変数から接続文字列を取得します。
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
Service Connector によって追加された環境変数から接続文字列を取得します。
const redis = require("redis");
const connectionString = process.env.AZURE_REDIS_CONNECTIONSTRING;
const cacheConnection = redis.createClient({
url: connectionString,
});
await cacheConnection.connect();
他の言語の場合は、Service Connector が環境変数に設定する接続情報を使って、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
Service Connector によって設定された環境変数を使用して認証ロジックを追加します。 詳しくは、Microsoft.Azure.StackExchangeRedis 拡張機能のページを参照してください。
using StackExchange.Redis;
var cacheHostName = Environment.GetEnvironmentVariable("AZURE_REDIS_HOST");
var configurationOptions = ConfigurationOptions.Parse($"{cacheHostName}:6380");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
// For user-assigned identity.
// var managedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// await configurationOptions.ConfigureForAzureWithUserAssignedManagedIdentityAsync(managedIdentityClientId);
// Service principal secret.
// var clientId = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTID");
// var tenantId = Environment.GetEnvironmentVariable("AZURE_REDIS_TENANTID");
// var secret = Environment.GetEnvironmentVariable("AZURE_REDIS_CLIENTSECRET");
// await configurationOptions.ConfigureForAzureWithServicePrincipalAsync(clientId, tenantId, secret);
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
pom.xml
ファイルに次の依存関係を追加します。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.11.2</version> <!-- {x-version-update;com.azure:azure-identity;dependency} -->
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>5.1.0</version> <!-- {x-version-update;redis.clients:jedis;external_dependency} -->
</dependency>
Service Connector によって設定された環境変数を使用して認証ロジックを追加します。 詳しくは、Azure-AAD-Authentication-With-Jedis を参照してください。
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import java.net.URI;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
// For user-assigned identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().managedIdentityClientId(clientId).build();
// For AKS workload identity.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().workloadIdentityClientId(clientId).build();
// For service principal.
// String clientId = System.getenv("AZURE_REDIS_CLIENTID");
// String secret = System.getenv("AZURE_REDIS_CLIENTSECRET");
// String tenant = System.getenv("AZURE_REDIS_TENANTID");
// ClientSecretCredential defaultAzureCredential = new ClientSecretCredentialBuilder().tenantId(tenant).clientId(clientId).clientSecret(secret).build();
String token = defaultAzureCredential
.getToken(new TokenRequestContext()
.addScopes("https://redis.azure.com/.default")).block().getToken();
// SSL connection is required.
boolean useSsl = true;
// TODO: Replace Host Name with Azure Cache for Redis Host Name.
String username = extractUsernameFromToken(token);
String cacheHostname = System.getenv("AZURE_REDIS_HOST");
// Create Jedis client and connect to Azure Cache for Redis over the TLS/SSL port using the access token as password.
// Note, Redis Cache host name and port are required below.
Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
.password(token) // Microsoft Entra access token as password is required.
.user(username) // Username is Required
.ssl(useSsl) // SSL Connection is Required
.build());
// Set a value against your key in the Redis cache.
jedis.set("Az:key", "testValue");
System.out.println(jedis.get("Az:key"));
// Close the Jedis Client
jedis.close();
依存関係をインストールします。
pip install redis azure-identity
Service Connector によって設定された環境変数を使用して認証ロジックを追加します。 詳しくは、azure-aad-auth-with-redis-py を参照してください。
import os
import time
import logging
import redis
import base64
import json
from azure.identity import DefaultAzureCredential
host = os.getenv('AZURE_REDIS_HOST')
scope = "https://redis.azure.com/.default"
port = 6380 # Required
def extract_username_from_token(token):
parts = token.split('.')
base64_str = parts[1]
if len(base64_str) % 4 == 2:
base64_str += "=="
elif len(base64_str) % 4 == 3:
base64_str += "="
json_bytes = base64.b64decode(base64_str)
json_str = json_bytes.decode('utf-8')
jwt = json.loads(json_str)
return jwt['oid']
def re_authentication():
_LOGGER = logging.getLogger(__name__)
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For user-assigned identity.
# client_id = os.getenv('AZURE_REDIS_CLIENTID')
# cred = DefaultAzureCredential(managed_identity_client_id=client_id)
# For service principal.
# tenant_id = os.getenv("AZURE_TENANT_ID")
# client_id = os.getenv("AZURE_CLIENT_ID")
# client_secret = os.getenv("AZURE_CLIENT_SECRET")
# cred = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
token = cred.get_token(scope)
user_name = extract_username_from_token(token.token)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
max_retry = 3
for index in range(max_retry):
try:
if _need_refreshing(token):
_LOGGER.info("Refreshing token...")
tmp_token = cred.get_token(scope)
if tmp_token:
token = tmp_token
r.execute_command("AUTH", user_name, token.token)
r.set("Az:key1", "value1")
t = r.get("Az:key1")
print(t)
break
except redis.ConnectionError:
_LOGGER.info("Connection lost. Reconnecting.")
token = cred.get_token(scope)
r = redis.Redis(host=host,
port=port,
ssl=True, # ssl connection is required.
username=user_name,
password=token.token,
decode_responses=True)
except Exception:
_LOGGER.info("Unknown failures.")
break
def _need_refreshing(token, refresh_offset=300):
return not token or token.expires_on - time.time() < refresh_offset
if __name__ == '__main__':
re_authentication()
依存関係をインストールします。
npm install redis @azure/identity
Service Connector によって設定された環境変数を使用して認証ロジックを追加します。 詳しくは、「Azure Cache for Redis: Microsoft Entra ID と node-redis クライアント ライブラリ」を参照してください。
import { createClient } from "redis";
import { DefaultAzureCredential } from "@azure/identity";
function extractUsernameFromToken(accessToken: AccessToken): string{
const base64Metadata = accessToken.token.split(".")[1];
const { oid } = JSON.parse(
Buffer.from(base64Metadata, "base64").toString("utf8"),
);
return oid;
}
async function main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_REDIS_TENANTID;
// const clientId = process.env.AZURE_REDIS_CLIENTID;
// const clientSecret = process.env.AZURE_REDIS_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
const redisScope = "https://redis.azure.com/.default";
let accessToken = await credential.getToken(redisScope);
console.log("access Token", accessToken);
const host = process.env.AZURE_REDIS_HOST;
// Create redis client and connect to Azure Cache for Redis over the TLS port using the access token as password.
const client = createClient({
username: extractUsernameFromToken(accessToken),
password: accessToken.token,
url: `redis://${host}:6380`,
pingInterval: 100000,
socket: {
tls: true,
keepAlive: 0
},
});
client.on("error", (err) => console.log("Redis Client Error", err));
await client.connect();
// Set a value against your key in Azure Redis Cache.
await client.set("Az:key", "value1312");
// Get value of your key in Azure Redis Cache.
console.log("value-", await client.get("Az:key"));
}
main().catch((err) => {
console.log("error code: ", err.code);
console.log("error message: ", err.message);
console.log("error stack: ", err.stack);
});
他の言語の場合は、Azure ID クライアント ライブラリ (および Service Connector が環境変数に設定する接続情報) を使って、Azure Cache for Redis に接続できます。
関連コンテンツ