Как реализовать повторное использование клиентских экземпляров документов Azure в c # для функций Azure - PullRequest
0 голосов
/ 21 сентября 2018

Я получил сообщение об ошибке при выделении моей функции Azure, это связано с ограничением в 300 соединений: https://github.com/projectkudu/kudu/wiki/Azure-Web-App-sandbox#numerical-sandbox-limits

Решение состоит в том, чтобы использовать статических клиентов, поэтому, когда функция запрашивается несколько раз, одинклиент всегда используется, а не новый клиент каждый раз.Я оцепенел на C # и программировании, поэтому я даже не понимаю, что делать.

Можете ли вы помочь мне реализовать то, что предлагается здесь .Это мой код:

    [FunctionName("Search")]
    public static async Task<HttpResponseMessage> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req,
        TraceWriter log)
    {
        log.Info("C# HTTP trigger function processed a request.");

        // the person objects will be free-form in structure
        List<dynamic> results = new List<dynamic>();

        // open the client's connection
        using (DocumentClient client = new DocumentClient(
            new Uri(endpoint),
            authKey,
            new ConnectionPolicy
            {
                ConnectionMode = ConnectionMode.Direct,
                ConnectionProtocol = Protocol.Tcp
            }))
           {
            // get a reference to the database the console app created
                Database database = await client.CreateDatabaseIfNotExistsAsync(
                new Database
                {
                    Id = "cloudcasegraph"
                });

            // get an instance of the database's graph

            DocumentCollection graph = await client.CreateDocumentCollectionIfNotExistsAsync(
                UriFactory.CreateDatabaseUri("cloudcasegraph"),
                new DocumentCollection { Id = "poc-graph1" },
                new RequestOptions { OfferThroughput = 400 }
                );

            // Get the gremlinquery from the headers
            IEnumerable<string> headerValues = req.Headers.GetValues("gremlinquery");
            var gremlinquery = headerValues.FirstOrDefault();
            //Make the query against the graph
            IDocumentQuery<dynamic> query = client.CreateGremlinQuery<dynamic>(graph, string.Format("{0}", gremlinquery));

            // iterate over all the results and add them to the list
            while (query.HasMoreResults)
                foreach (dynamic result in await query.ExecuteNextAsync())
                    results.Add(result);
        }

        // return the list with an OK response
        return req.CreateResponse<List<dynamic>>(HttpStatusCode.OK, results);
    }
}

Ответы [ 2 ]

0 голосов
/ 22 сентября 2018

Я наконец-то понял, как это сделать.Я следил за этой замечательной статьей: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ Короткая история: вместо того, чтобы открывать новое соединение с БД документа для каждого выполнения, я открываю его один раз.

// open the client's connection
        private static DocumentClient client = new DocumentClient(
            new Uri(endpoint),authKey,
            new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp });

[FunctionName("Search")]
0 голосов
/ 21 сентября 2018

На основе Вики-функции Azure вы можете сделать что-то вроде:

public static class YourFunction
{
    private static Lazy<DocumentClient> lazyClient = new Lazy<DocumentClient>(InitializeDocumentClient);
    private static DocumentClient client => lazyClient.Value;
    private static DocumentCollection graph;

    private static DocumentClient InitializeDocumentClient()
    {
        // Perform any initialization here
        var uri = new Uri("example");
        var authKey = "authKey";

        var client = new DocumentClient(uri, authKey, new ConnectionPolicy
                {
                    ConnectionMode = ConnectionMode.Direct,
                    ConnectionProtocol = Protocol.Tcp
                });

        // get a reference to the database the console app created
        Database database = client.CreateDatabaseIfNotExistsAsync(
        new Database
        {
            Id = "cloudcasegraph"
        }).Result;

        graph = client.CreateDocumentCollectionIfNotExistsAsync(
            UriFactory.CreateDatabaseUri("cloudcasegraph"),
            new DocumentCollection { Id = "poc-graph1" },
            new RequestOptions { OfferThroughput = 400 }
            ).Result;

        return client;
    }


    [FunctionName("Search")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            // the person objects will be free-form in structure
            List<dynamic> results = new List<dynamic>();



            // Get the gremlinquery from the headers
            IEnumerable<string> headerValues = req.Headers.GetValues("gremlinquery");
            var gremlinquery = headerValues.FirstOrDefault();
            //Make the query against the graph
            IDocumentQuery<dynamic> query = client.CreateGremlinQuery<dynamic>(graph, string.Format("{0}", gremlinquery));

            // iterate over all the results and add them to the list
            while (query.HasMoreResults)
                foreach (dynamic result in await query.ExecuteNextAsync())
                    results.Add(result);


            // return the list with an OK response
            return req.CreateResponse<List<dynamic>>(HttpStatusCode.OK, results);
        }
}
...