Мы используем Cosmos db в нашем API-интерфейсе ASP Net Core и поняли, что не видим рекламируемой низкой задержки при чтении точек. Для чтения точек стабильно около 20-25 мс. Я смотрю на информацию о космическом ресурсе.
Соглашение об уровне обслуживания гласит, что мы должны увидеть
Кто мы? отсутствует?
Вот пример нашего кода, который дает такие результаты:
using Azure.Monitor.OpenTelemetry.AspNetCore;
using Microsoft.Azure.Cosmos;
using System.Diagnostics;
namespace CosmosTest
{
public class Program
{
static string? _dbId;
static string? _containerId;
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(serviceProvider =>
{
var configuration = serviceProvider.GetRequiredService();
_dbId = configuration["CosmosDB:DatabaseId"];
_containerId = configuration["CosmosDB:ContainerId"];
var cosmosClientOptions = new CosmosClientOptions
{
SerializerOptions = new CosmosSerializationOptions
{
PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
},
ConnectionMode = ConnectionMode.Direct,
AllowBulkExecution = false,
};
var connectionString = configuration.GetConnectionString("Cosmos");
return new CosmosClient(connectionString);
});
builder.Services.AddOpenTelemetry().WithTracing(tracerProviderBuilder =>
{
tracerProviderBuilder.AddSource("Azure.Cosmos.Operation");
}).UseAzureMonitor();
builder.Services.AddApplicationInsightsTelemetry();
builder.Logging.AddApplicationInsights();
var app = builder.Build();
app.MapGet("/{partitionKey}/{id}", async (Guid id, Guid partitionKey, CosmosClient cosmosClient, ILogger
logger) =>
{
var container = cosmosClient.GetContainer(_dbId, _containerId);
var startTime = Stopwatch.GetTimestamp();
var itemResponse = await container.ReadItemAsync(id.ToString(), new PartitionKey(partitionKey.ToString()));
var elapsed = Stopwatch.GetElapsedTime(startTime);
logger.LogInformation("Read item {id} from container {container} in {elapsed} ms", id, _containerId, elapsed);
return Results.Ok(itemResponse.Resource);
});
app.MapGet("/{partitionKey}", async (Guid partitionKey, CosmosClient cosmosClient) =>
{
var container = cosmosClient.GetContainer(_dbId, _containerId);
var query = new QueryDefinition("SELECT * FROM c WHERE c.productBlueprintId = @productBlueprintId")
.WithParameter("@productBlueprintId", partitionKey);
var iterator = container.GetItemQueryIterator(query);
var results = new List();
while (iterator.HasMoreResults)
{
var response = await iterator.ReadNextAsync();
results.AddRange(response.ToList());
}
return Results.Ok(results);
});
app.MapPost("/", async (Product product, CosmosClient cosmosClient) =>
{
var container = cosmosClient.GetContainer(_dbId, _containerId);
var response = await container.CreateItemAsync(product, new PartitionKey(product.productBlueprintId.ToString()));
return;
});
app.UseDeveloperExceptionPage();
app.Run();
}
}
public record Product(string id, Guid productBlueprintId, string Name, Guid OwnerId, DateTime createdUtc, Guid createdBy);
}
Изменить: во время дополнительного тестирования этого репродукции я обнаружил, что запись на самом деле каждый раз занимает менее 10 мс, медленным является только чтение.
Мы используем Cosmos db в нашем API-интерфейсе ASP Net Core и поняли, что не видим рекламируемой низкой задержки при чтении точек. Для чтения точек стабильно около 20-25 мс. Я смотрю на информацию о космическом ресурсе. Соглашение об уровне обслуживания гласит, что мы должны увидеть Кто мы? отсутствует? Вот пример нашего кода, который дает такие результаты: [code]using Azure.Monitor.OpenTelemetry.AspNetCore; using Microsoft.Azure.Cosmos; using System.Diagnostics; namespace CosmosTest { public class Program { static string? _dbId; static string? _containerId; public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(serviceProvider => { var configuration = serviceProvider.GetRequiredService();
_dbId = configuration["CosmosDB:DatabaseId"]; _containerId = configuration["CosmosDB:ContainerId"]; var cosmosClientOptions = new CosmosClientOptions { SerializerOptions = new CosmosSerializationOptions { PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase }, ConnectionMode = ConnectionMode.Direct,
AllowBulkExecution = false, }; var connectionString = configuration.GetConnectionString("Cosmos"); return new CosmosClient(connectionString); });
var itemResponse = await container.ReadItemAsync(id.ToString(), new PartitionKey(partitionKey.ToString()));
var elapsed = Stopwatch.GetElapsedTime(startTime);
logger.LogInformation("Read item {id} from container {container} in {elapsed} ms", id, _containerId, elapsed);
return Results.Ok(itemResponse.Resource);
});
app.MapGet("/{partitionKey}", async (Guid partitionKey, CosmosClient cosmosClient) => { var container = cosmosClient.GetContainer(_dbId, _containerId); var query = new QueryDefinition("SELECT * FROM c WHERE c.productBlueprintId = @productBlueprintId") .WithParameter("@productBlueprintId", partitionKey); var iterator = container.GetItemQueryIterator(query); var results = new List(); while (iterator.HasMoreResults) { var response = await iterator.ReadNextAsync(); results.AddRange(response.ToList()); } return Results.Ok(results); });
app.MapPost("/", async (Product product, CosmosClient cosmosClient) => { var container = cosmosClient.GetContainer(_dbId, _containerId); var response = await container.CreateItemAsync(product, new PartitionKey(product.productBlueprintId.ToString())); return; });
app.UseDeveloperExceptionPage();
app.Run(); } }
public record Product(string id, Guid productBlueprintId, string Name, Guid OwnerId, DateTime createdUtc, Guid createdBy); } [/code] Изменить: во время дополнительного тестирования этого репродукции я обнаружил, что запись на самом деле каждый раз занимает менее 10 мс, медленным является только чтение.