[英]Unable to connect to Azure Cosmos Db Account using Microsoft.EntityFrameworkCore.Cosmos - Response status code
The CosmosDb provider is sending this message: CosmosDb 提供程序正在发送此消息:
“Response status code does not indicate success: 503 Substatus: 0 Reason: (The request failed because the client was unable to establish connections to 3 endpoints across 1 regions. Please check for client resource starvation issues and verify connectivity between client and server.” “响应状态码不表示成功:503 子状态:0 原因:(请求失败,因为客户端无法跨 1 个区域建立与 3 个端点的连接。请检查客户端资源不足问题并验证客户端和服务器之间的连接。”
In my tests, it works (.net core 3.1):在我的测试中,它可以工作(.net core 3.1):
Task.Run(async () =>
{
var endpoint = “test”;
var masterKey = “test”;
using (var client = new DocumentClient(new Uri(endpoint), masterKey))
{
//Insert new Document
Console.WriteLine("\r\n>>>>>>>>>>>>>>>> Creating Document <<<<<<<<<<<<<<<<<<<");
dynamic candidato = new
{
Id = 1,
Nome = "Test"
};
var document1 = await client.CreateDocumentAsync(
UriFactory.CreateDocumentCollectionUri("Test", "Test"),
candidato);
Console.ReadKey();
}
}).Wait();
It does not:它不是:
Task.Run(async () =>
{
using (var context = new StudentsDbContext())
{
context.Add(new FamilyContainer(2, "Test"));
await context.SaveChangesAsync();
}
}).Wait();
public class FamilyContainer
{
public int Id { get; set; }
public string Nome { get; set; }
public FamilyContainer(int id, string nome)
{
Id = id;
Nome = nome;
}
}
public class StudentsDbContext : DbContext
{
public DbSet<FamilyContainer> FamilyContainer { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseCosmos(
"test",
"test",
"FamilyDatabase",
options =>
{ }
);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<FamilyContainer>(x =>
{
x.ToContainer("FamilyContainer");
});
}
}
Can anyone help me?谁能帮我? Thanks谢谢
fail: Microsoft.EntityFrameworkCore.Update[10000] An exception occurred in the database while saving changes for context type '...'.失败:Microsoft.EntityFrameworkCore.Update[10000] 保存上下文类型“...”的更改时数据库中发生异常。 Microsoft.EntityFrameworkCore.Storage.RetryLimitExceededException: Maximum number of retries (6) exceeded while executing database operations with 'CosmosExecutionStrategy'. Microsoft.EntityFrameworkCore.Storage.RetryLimitExceededException:使用“CosmosExecutionStrategy”执行数据库操作时超出最大重试次数 (6)。 See inner exception for the most recent failure.有关最近的失败,请参阅内部异常。 ---> Microsoft.Azure.Cosmos.CosmosException: Response status code does not indicate success: 503 Substatus: 0 Reason: (Microsoft.Azure.Documents.ServiceUnavailableException: Service is currently unavailable.ActivityId: 07fbf539-0d44-4e5a-89d0-cd46838ee605, {"RequestStartTimeUtc":"2020-02-21T16:34:09.1834993Z","RequestEndTimeUtc":"2020-02-21T16:34:41.3484203Z","RequestLatency":"00:00:32.1649210","IsCpuOverloaded":false,"NumberRegionsAttempted":1,"ResponseStatisticsList":[{"ResponseTime":"2020-02-21T16:34:11.5964152Z","ResourceType":2,"OperationType":0,"StoreResult":"StorePhysicalAddress: rntbd:.../, LSN: -1, GlobalCommittedLsn: -1, PartitionKeyRangeId: , IsValid: True, StatusCode: 410, SubStatusCode: 0, RequestCharge: 0, ItemLSN: -1, SessionToken: , UsingLocalLSN: False, TransportException: A client transport error occurred: Failed to connect to the remote endpoint. (Time: 2020-02-21T16:34:11.5298608Z, activity ID: 07fbf539-0d44- ---> Microsoft.Azure.Cosmos.CosmosException: Response status code does not indicate success: 503 Substatus: 0 Reason: (Microsoft.Azure.Documents.ServiceUnavailableException: Service is currently unavailable.ActivityId: 07fbf539-0d44-4e5a-89d0- cd46838ee605, {"RequestStartTimeUtc":"2020-02-21T16:34:09.1834993Z","RequestEndTimeUtc":"2020-02-21T16:34:41.3484203Z","RequestLatency":"00:00:32.1649210"," IsCpuOverloaded":false,"NumberRegionsAttempted":1,"ResponseStatisticsList":[{"ResponseTime":"2020-02-21T16:34:11.5964152Z","ResourceType":2,"OperationType":0,"StoreResult": “StorePhysicalAddress:rntbd:.../,LSN:-1,GlobalCommittedLsn:-1,PartitionKeyRangeId:,IsValid:True,StatusCode:410,SubStatusCode:0,RequestCharge:0,ItemLSN:-1,SessionToken:,UsingLocalLSN:False , TransportException: A client transport error occurred: Failed to connect to the remote endpoint. (时间: 2020-02-21T16:34:11.5298608Z, 活动 ID: 07fbf539-0d44- 4e5a-89d0-cd46838ee605, error code: ConnectFailed [0x0005], base error: socket error ConnectionRefused [0x0000274D]... --- End of inner exception stack trace --- 4e5a-89d0-cd46838ee605,错误代码:ConnectFailed [0x0005],基本错误:套接字错误 ConnectionRefused [0x0000274D]... --- 内部异常堆栈跟踪结束 ---
I was facing same issue.我面临同样的问题。
What worked for me is changing ConnectionMode
to ConnectionMode.Gateway
while initializing CosmosClient
like :什么工作对我来说是变化ConnectionMode
到ConnectionMode.Gateway
在初始化CosmosClient
这样的:
var options = new CosmosClientOptions() { ConnectionMode = ConnectionMode.Gateway };
var client = new CosmosClient(endpoint, key, options);
For more details on refer :有关更多详细信息,请参阅:
https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.cosmosclientoptions?view=azure-dotnet https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.cosmosclientoptions?view=azure-dotnet
https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.connectionmode?view=azure-dotnet https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.connectionmode?view=azure-dotnet
TransportException: A client transport error occurred: Failed to connect to the remote endpoint. TransportException:发生客户端传输错误:无法连接到远程端点。 (Time: 2020-02-21T16:34:11.5298608Z, activity ID: 07fbf539-0d44-4e5a-89d0-cd46838ee605, error code: ConnectFailed [0x0005], base error: socket error ConnectionRefused (时间:2020-02-21T16:34:11.5298608Z,活动ID:07fbf539-0d44-4e5a-89d0-cd46838ee605,错误代码:ConnectFailed [0x0005],基础错误:socket错误ConnectionRefused
This means that the Connection was refused.这意味着连接被拒绝。
My RCA for this is: Cosmos Partitions where served by individual processes on CosmosDB, each partition serving process has it's own TCP port.我对此的 RCA 是:Cosmos 分区由 CosmosDB 上的各个进程提供服务,每个分区服务进程都有自己的 TCP 端口。 When client connects to 443 (Using TCP Direct Mode), CosmosDB Proxy sends partition ports back to client so that client can talk to server-partitions in parallel.当客户端连接到 443(使用 TCP 直接模式)时,CosmosDB 代理将分区端口发送回客户端,以便客户端可以与服务器分区并行通信。 Partition ports are random (11000 upwards afaik).分区端口是随机的(11000 向上 afaik)。 Normal company firewall would allow outbound 443 (connection to cosmos works) but blocks the outbound random ports.正常的公司防火墙将允许出站 443(连接到 Cosmos 有效),但会阻止出站随机端口。 So at the end, access fails.所以最后,访问失败。 Workarounds:解决方法:
It is because Entity framework has a default connection mode of Direct.这是因为Entity框架默认的连接方式是Direct。 It worked for me after overriding it to Gateway.将其覆盖到 Gateway 后,它对我有用。
{
optionsBuilder.UseCosmos(
"test",
"test",
"FamilyDatabase",
options =>
{ options.ConnectionMode(ConnectionMode.Gateway); }
);
}
I just want to add this because it wasted a lot of my time.我只想添加这个,因为它浪费了我很多时间。 The following code would instantly die with an error message that led me to this SO post:以下代码将立即死亡,并显示一条错误消息,导致我看到这篇 SO 帖子:
var container = _client.Client.GetContainer(_databaseName, containername);
var result = await container.CreateItemAsync(dataitem, pk);
I disbelieved the error message because everything else has worked, upsert, read, etc. After messing with it for a while, I noticed the documentation shows a template type for CreateItemAsync.我不相信错误消息,因为其他一切都正常工作,更新插入,读取等。在弄乱了一段时间后,我注意到文档显示了 CreateItemAsync 的模板类型。
var container = _client.Client.GetContainer(_databaseName, containername);
var result = await container.CreateItemAsync<T>(dataitem, pk);
Changing the code to that fixed it (inside of a templated function).将代码更改为修复它的代码(在模板化函数内部)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.