이 문서에서는 서비스 커넥터를 사용하여 앱을 Azure Cache for Redis에 연결하는 데 사용할 수 있는 지원되는 인증 방법, 클라이언트 및 샘플 코드에 대해 설명합니다. 이 문서에서는 서비스 연결을 만들 때 가져오는 기본 환경 변수 이름, 값 및 구성도 찾을 수 있습니다.
지원되는 컴퓨팅 서비스
서비스 커넥터를 사용하여 다음 컴퓨팅 서비스를 Azure Cache for Redis에 연결할 수 있습니다.
- Azure App Service
- Azure Container Apps
- Azure Functions
- AKS(Azure Kubernetes Service)
- Azure Spring Apps
지원되는 인증 및 클라이언트 유형
다음 표에서는 서비스 커넥터를 사용하여 컴퓨팅 서비스를 Azure Cache for Redis에 연결하는 데 지원되는 인증 방법과 클라이언트 조합을 보여 줍니다. "예"는 해당 조합이 지원된다는 것을 의미합니다. "아니요"는 지원되지 않는다는 것을 의미합니다.
| 클라이언트 유형 |
시스템 할당 관리 ID |
사용자 할당 관리 ID |
비밀/연결 문자열 |
서비스 주체 |
| .NET |
예 |
예 |
예 |
예 |
| Go |
아니요 |
아니요 |
예 |
아니요 |
| Java |
예 |
예 |
예 |
예 |
| Java - Spring Boot |
아니요 |
아니요 |
예 |
아니요 |
| Node.js |
예 |
예 |
예 |
예 |
| Python |
예 |
예 |
예 |
예 |
| None |
예 |
예 |
예 |
예 |
기본 환경 변수 이름 또는 애플리케이션 속성과 샘플 코드
다음 환경 변수 이름과 애플리케이션 속성을 사용하여 컴퓨팅 서비스를 Redis 서버에 연결합니다. 명명 규칙에 대해 자세히 알아보려면 서비스 커넥터 내부 문서를 확인합니다.
시스템 할당 관리 ID
| 기본 환경 변수 이름 |
설명 |
샘플 값 |
AZURE_REDIS_HOST |
Redis 엔드포인트 |
<RedisName>.redis.cache.windows.net |
예제 코드
다음 단계와 코드는 시스템에서 할당한 관리 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 ID 클라이언트 라이브러리(및 서비스 커넥터가 환경 변수에 설정하는 연결 정보)를 사용하여 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
서비스 커넥터에서 설정한 환경 변수를 사용하여 인증 논리를 추가합니다. 자세한 내용은 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 ID 클라이언트 라이브러리(및 서비스 커넥터가 환경 변수에 설정하는 연결 정보)를 사용하여 Azure Cache for Redis에 연결할 수 있습니다.
연결 문자열
Warning
가능한 가장 안전한 인증 흐름을 사용하는 것이 좋습니다. 여기에 설명된 인증 흐름은 애플리케이션에 대한 매우 높은 수준의 신뢰를 요구하며 다른 흐름에는 존재하지 않는 위험을 수반합니다. 관리 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
서비스 커넥터에서 추가한 환경 변수에서 연결 문자열을 가져옵니다.
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 ID 클라이언트 라이브러리(및 서비스 커넥터가 환경 변수에 설정하는 연결 정보)를 사용하여 Azure Cache for Redis에 연결할 수 있습니다.
관련 콘텐츠