简体   繁体   English

无法使用 Microsoft.EntityFrameworkCore.Cosmos 连接到 Azure Cosmos Db 帐户 - 响应状态代码

[英]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");
        });
    }
}

Packages套餐

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 :什么工作对我来说是变化ConnectionModeConnectionMode.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.这意味着连接被拒绝。

  • Either your Cosmos DB account has Firewall/VPN enabled and the application is not able to establish a connection due not not being in a whitelisted IP/Network : Try checking your account configuration.您的 Cosmos DB 帐户启用了防火墙/VPN,并且由于不在白名单 IP/网络中,应用程序无法建立连接:尝试检查您的帐户配置。
  • The environment you are executing the code is restricting connections (some corporate Firewall or network might be blocking port ranges): Try running the app in a different network, or use GatewayMode .您正在执行代码的环境限制了连接(某些公司防火墙或网络可能会阻止端口范围):尝试在不同的网络中运行应用程序,或使用GatewayMode If that works, then this is related to the network.如果可行,则这与网络有关。
  • The machine might be running low on sockets or high on CPU.机器可能在套接字上运行低或在 CPU 上运行高。

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:解决方法:

  1. Open firewall打开防火墙
  2. Use Gateway Mode.使用网关模式。 This uses https/443 only by forwarding internally instead of redirecting to other ports.这仅通过内部转发而不是重定向到其他端口来使用 https/443。

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.

相关问题 Azure Cosmos DB 数据迁移工具无法连接到 Cosmos DB - Azure Cosmos DB Data Migration Tool unable to connect to Cosmos DB 使用Azure托管服务身份连接到Cosmos DB帐户 - Connect to Cosmos DB account using Azure Managed Service Identity 如何在不使用主键的情况下连接到 ac# 代码中的 azure cosmos db 帐户 - How to connect to azure cosmos db account in a c# code without using primary key 无法从 Azure Function 连接到 Azure Cosmos DB。 获取“Microsoft.Azure.Cosmos.Direct:Object 引用未设置为 object 的实例 - Unable to Connect from Azure Function to Azure Cosmos DB. Getting "Microsoft.Azure.Cosmos.Direct: Object reference not set to an instance of an object Mongoshell无法连接到Cosmos DB - Mongoshell unable to connect to Cosmos DB Azure Function V4 Do.net隔离无法连接cosmos db - Azure Function V4 Dotnet Isolated unable to connect to cosmos db 无法使用MongoDB驱动程序.Net C#连接到Azure Cosmos DB - Unable to connect to Azure Cosmos DB using the MongoDB Driver .Net C# 无法使用 Mongo 连接到运行 Docker 的 Azure Cosmos DB 模拟器 - Failed to Connect to the Azure Cosmos DB Emulator running Docker using Mongo 无法使用 ScalarDB 连接到我自己的 azure cosmos db 实例 - Failed to connect to my own azure cosmos db instance using ScalarDB 并行连接到 Microsoft Azure Cosmos DB - Parallel connection to Microsoft Azure Cosmos DB
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM