【问题标题】:Programmatically start server and deploy API以编程方式启动服务器并部署 API
【发布时间】:2017-06-09 21:27:15
【问题描述】:

我正在使用 .NET Core (C#) 并创建 API。根据我们的应用程序,我们知道何时会有高峰和低谷时间,因此我们希望抢先启动具有额外 api 端点的服务器。有没有办法以编程方式部署新服务器并启动 API 并准备就绪?

我们将有一个(管理员/主)服务器持续运行,它将处理可能通过 cron 作业监视的部署。

任何提示都会有所帮助。我们是否创建了一个被克隆的基础服务器?我们是否有需要上传的压缩包中的 API?

【问题讨论】:

  • 听起来你在谈论自动缩放。你在使用 Azure 吗?然后你只需要configure it
  • @JohnWu 谢谢。我会研究一下,看看我是否可以使用它。

标签: c# azure .net-core


【解决方案1】:

首先,我建议你可以尝试使用 VMSS 来启用自动缩放。

虚拟机规模集是一种 Azure 计算资源,可用于部署和管理一组相同的 VM。在所有 VM 配置相同的情况下,规模集旨在支持真正的自动缩放,并且不需要预先设置 VM。因此,构建针对大计算、大数据和容器化工作负载的大规模服务变得更加容易。

更多细节,你可以参考这个article

有没有办法以编程方式部署新服务器,API 已启动并准备就绪?

据我所知,我们有多种方式来部署和启动新的虚拟机。

我建议你可以使用 azure fluent api 或 azure template deploy 使用 C# 代码来做。

更多细节,你可以参考这个fluent code sample

注意:无论使用 fluent api 还是 azure 模板,都需要先创建一个 Azure Active Directory 应用程序和服务主体。生成服务主体后,您可以获得应用程序ID、访问密钥和人才ID。更多细节,你可以参考这个article

我们是否创建了一个被克隆的基础服务器?我们是否有需要上传的压缩包中的 API?

在我看来,我建议您可以创建当前 VM 的托管映像。

然后可以使用该映像通过使用 fluent api 或 azure template deploy 创建多个 VM。所有这些虚拟机都将具有相同的 C 盘,因此它将包含所有相同的设置。

更多细节,您可以参考以下步骤:

1.您可以先安装并设置您的虚拟机。

2.你可以关注这个article创建图片。

创建图片后,你会发现图片资源如下:

3.点击图片资源,创建虚拟机。

4.注意:您需要选择与基础虚拟机的网络安全组相同的网络安全组。

5.下载模板。

6.然后你可以使用C#代码通过模板部署VM。

代码如下:

// Requires the following Azure NuGet packages and related dependencies:
// package id="Microsoft.Azure.Management.Authorization" version="2.0.0"
// package id="Microsoft.Azure.Management.ResourceManager" version="1.4.0-preview"
// package id="Microsoft.Rest.ClientRuntime.Azure.Authentication" version="2.2.8-preview"

using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Rest.Azure.Authentication;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;

namespace PortalGenerated
{
    /// <summary>
    /// This is a helper class for deploying an Azure Resource Manager template
    /// More info about template deployments can be found here https://go.microsoft.com/fwLink/?LinkID=733371
    /// </summary>
    class DeploymentHelper
    {
        string subscriptionId = "your-subscription-id";
        string clientId = "your-service-principal-clientId";
        string clientSecret = "your-service-principal-client-secret";
        string resourceGroupName = "resource-group-name";
        string deploymentName = "deployment-name";
        string resourceGroupLocation = "resource-group-location"; // must be specified for creating a new resource group
        string pathToTemplateFile = "path-to-template.json-on-disk";
        string pathToParameterFile = "path-to-parameters.json-on-disk";
        string tenantId = "tenant-id";

        public async void Run()
        {
            // Try to obtain the service credentials
            var serviceCreds = await ApplicationTokenProvider.LoginSilentAsync(tenantId, clientId, clientSecret);

            // Read the template and parameter file contents
            JObject templateFileContents = GetJsonFileContents(pathToTemplateFile);
            JObject parameterFileContents = GetJsonFileContents(pathToParameterFile);

            // Create the resource manager client
            var resourceManagementClient = new ResourceManagementClient(serviceCreds);
            resourceManagementClient.SubscriptionId = subscriptionId;

            // Create or check that resource group exists
            EnsureResourceGroupExists(resourceManagementClient, resourceGroupName, resourceGroupLocation);

            // Start a deployment
            DeployTemplate(resourceManagementClient, resourceGroupName, deploymentName, templateFileContents, parameterFileContents);
        }

        /// <summary>
        /// Reads a JSON file from the specified path
        /// </summary>
        /// <param name="pathToJson">The full path to the JSON file</param>
        /// <returns>The JSON file contents</returns>
        private JObject GetJsonFileContents(string pathToJson)
        {
            JObject templatefileContent = new JObject();
            using (StreamReader file = File.OpenText(pathToJson))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    templatefileContent = (JObject)JToken.ReadFrom(reader);
                    return templatefileContent;
                }
            }
        }

        /// <summary>
        /// Ensures that a resource group with the specified name exists. If it does not, will attempt to create one.
        /// </summary>
        /// <param name="resourceManagementClient">The resource manager client.</param>
        /// <param name="resourceGroupName">The name of the resource group.</param>
        /// <param name="resourceGroupLocation">The resource group location. Required when creating a new resource group.</param>
        private static void EnsureResourceGroupExists(ResourceManagementClient resourceManagementClient, string resourceGroupName, string resourceGroupLocation)
        {
            if (resourceManagementClient.ResourceGroups.CheckExistence(resourceGroupName) != true)
            {
                Console.WriteLine(string.Format("Creating resource group '{0}' in location '{1}'", resourceGroupName, resourceGroupLocation));
                var resourceGroup = new ResourceGroup();
                resourceGroup.Location = resourceGroupLocation;
                resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, resourceGroup);
            }
            else
            {
                Console.WriteLine(string.Format("Using existing resource group '{0}'", resourceGroupName));
            }
        }

        /// <summary>
        /// Starts a template deployment.
        /// </summary>
        /// <param name="resourceManagementClient">The resource manager client.</param>
        /// <param name="resourceGroupName">The name of the resource group.</param>
        /// <param name="deploymentName">The name of the deployment.</param>
        /// <param name="templateFileContents">The template file contents.</param>
        /// <param name="parameterFileContents">The parameter file contents.</param>
        private static void DeployTemplate(ResourceManagementClient resourceManagementClient, string resourceGroupName, string deploymentName, JObject templateFileContents, JObject parameterFileContents)
        {
            Console.WriteLine(string.Format("Starting template deployment '{0}' in resource group '{1}'", deploymentName, resourceGroupName));
            var deployment = new Deployment();

            deployment.Properties = new DeploymentProperties
            {
                Mode = DeploymentMode.Incremental,
                Template = templateFileContents,
                Parameters = parameterFileContents["parameters"].ToObject<JObject>()
            };

            var deploymentResult = resourceManagementClient.Deployments.CreateOrUpdate(resourceGroupName, deploymentName, deployment);
            Console.WriteLine(string.Format("Deployment status: {0}", deploymentResult.Properties.ProvisioningState));
        }
    }
}

【讨论】:

  • 感谢您使用模板部署脚本。我也在 azure 门户中找到的最后一段代码是我用来部署服务器的代码。稍加修改,我就可以从 github 进行部署。
  • 嗨,using Microsoft.Azure.Management.ResourceManager.Models 类在任何 Microsoft 框架中都不可用 :( 怎么办???。
猜你喜欢
  • 2018-10-07
  • 1970-01-01
  • 1970-01-01
  • 2011-10-03
  • 1970-01-01
  • 2019-07-15
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
相关资源
最近更新 更多