第一个Azure应用
https://www.azure.cn/zh-cn/
学习Azure,首先看的是官网Azure介绍,因为用到了虚拟机及存储等因此,着重看这两块。
本文Demo是通过API发送消息,当收到消息后新建虚拟机并启动虚拟机。
详细步骤:
1.新建Azure Cloud应用程序,添加WebRole以及WorkerRole,WebRole对应的是WebAPI
2.具体代码
WebRole中实现发送消息
public class AzureMessageController : ApiController
{
// POST api/AzureMessage
[HttpGet]
[Route ("api/AzureMessage")]
public Dictionary<string, string> Get([FromBody]string value)
{
Dictionary<string, string> item = new Dictionary<string, string>();
item.Add("name", "Jerry");
QueueClient client = QueueClient.Create("queue", ReceiveMode.ReceiveAndDelete);
BrokeredMessage msg = new BrokeredMessage(item);
try
{
client.Send(msg);
}
catch
{
throw;
}
finally
{
client.Close();
}
return item;
}
}
WorkerRole中在WorkerRole.cs中实现接收消息并新建虚拟机,开启虚拟机,及Stop动作
private static QueueClient client;
private IComputeManagementClient csClient;
private INetworkManagementClient netClient;
a. OnStart()中开启消息队列客户端
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = ; // For information on handling configuration changes
// see the MSDN topic at https://go.microsoft.com/fwlink/?LinkId=166357. client = QueueClient.Create("queue", ReceiveMode.ReceiveAndDelete);
Trace.TraceInformation("MyWorkerRole has been started"); return base.OnStart();
}
b. OnStop()中关闭消息队列客户端
public override void OnStop()
{
Trace.TraceInformation("MyWorkerRole is stopping"); //this.cancellationTokenSource.Cancel();
//this.runCompleteEvent.WaitOne();
client.Close();
base.OnStop(); Trace.TraceInformation("MyWorkerRole has stopped");
}
c. Run()接收消息后,对虚拟机操作
public override void Run()
{
Trace.TraceInformation("MyWorkerRole is running");
//while (true)
//{
BrokeredMessage msg = client.Receive(TimeSpan.FromSeconds());
if (msg != null)
{
Dictionary<string, string> item = msg.GetBody<Dictionary<string,string>>();
Trace.TraceInformation("Messages received name: "+item["name"]);
//Create VM
#region 1. create certificattion to client
X509Certificate2 certificate = null;
string thumbprint = "这里是证书所需要的thumbprint";
certificate = new X509Certificate2(Convert.FromBase64String(thumbprint));
Microsoft.Azure.SubscriptionCloudCredentials CloudCredential = new Microsoft.Azure.CertificateCloudCredentials("这里是云服务证书序列", certificate);
csClient = new ComputeManagementClient(CloudCredential);
#endregion
#region 2. create cloudservice---serviceName
var list = csClient.HostedServices.List();
csClient.HostedServices.BeginDeletingAll("serviceName");
var hostServicesPar = new Microsoft.WindowsAzure.Management.Compute.Models.HostedServiceCreateParameters("serviceName", "label")
{
Location = "West US"
}; csClient.HostedServices.Create(hostServicesPar); #endregion
#region 3. osVHD
OSVirtualHardDisk osVHD = null;
//osVHD = csClient.VirtualMachineOSImages.CreateOSVHD(_parameters.CloudServiceName, _parameters.NodeName, _parameters.Image);
var res = csClient.VirtualMachineOSImages.Get("imageName"); //提前定制好的Image
Uri ur = res.MediaLinkUri;
string UrlPath = ur.AbsoluteUri;
string Result = UrlPath.Substring(, UrlPath.LastIndexOf('/')); osVHD = new OSVirtualHardDisk
{
MediaLink = VMClass.GetVhdUri(Result,"serviceName", "vmName"),
SourceImageName = "imageName",
};
#endregion
#region 4. vnet
netClient = new NetworkManagementClient(CloudCredential);
var netlist = netClient.Networks.List();
ConfigurationSet conset = new ConfigurationSet
{
ConfigurationSetType = ConfigurationSetTypes.NetworkConfiguration,
SubnetNames = new List<string> { "Subnet-1" }
}; #endregion
#region 5. Role List <ConfigurationSet> Configurations = new List<ConfigurationSet>();
Configurations.Add(conset); Configurations.Add(new ConfigurationSet
{
AdminUserName = "userName",
AdminPassword = "userPWD",
ConfigurationSetType = ConfigurationSetTypes.WindowsProvisioningConfiguration,
EnableAutomaticUpdates = true,
ResetPasswordOnFirstLogon = false,
ComputerName = "MyComputerName", });
//}
Microsoft.WindowsAzure.Management.Compute.Models.Role vmRole = new Microsoft.WindowsAzure.Management.Compute.Models.Role
{
RoleType = VirtualMachineRoleType.PersistentVMRole.ToString(),
RoleName = "MyRoleName",
Label = "label",
RoleSize = "Standard_DS1_v2",
// VMImageName = imageName,
OSVirtualHardDisk = osVHD,
ProvisionGuestAgent = true,
ConfigurationSets = Configurations
};
#endregion
#region 6. check demployment
//check demployment
DeploymentGetResponse demployment = null;
try
{
demployment = csClient.Deployments.GetBySlot("serviceName", DeploymentSlot.Production);
}
catch { } if (demployment != null)
{
//csClient.VirtualMachines.CreateVM(_parameters.HostSvcName, _parameters.HostSvcName, vmRole);
VirtualMachineCreateParameters parameters = new VirtualMachineCreateParameters()
{
ConfigurationSets = vmRole.ConfigurationSets,
ProvisionGuestAgent = true,
RoleName = vmRole.RoleName,
RoleSize = vmRole.RoleSize,
OSVirtualHardDisk = vmRole.OSVirtualHardDisk,
//VMImageName = vmRole.VMImageName,
ResourceExtensionReferences = vmRole.ResourceExtensionReferences, };
if (parameters.OSVirtualHardDisk == null)
{
parameters.VMImageName = vmRole.VMImageName;
};
csClient.VirtualMachines.Create("serviceName", "deploymentName", parameters);
}
else
{
//csClient.VirtualMachines.CreateVMDeployment(_parameters.HostSvcName, _parameters.HostSvcName, _parameters.VirtualNetworkName, new List<Role>() { vmRole });
VirtualMachineCreateDeploymentParameters createDeploymentParams = new VirtualMachineCreateDeploymentParameters
{
Name = "deploymentName",
Label = "serviceName",
Roles = new List<Microsoft.WindowsAzure.Management.Compute.Models.Role>() { vmRole },
DeploymentSlot = DeploymentSlot.Production,
VirtualNetworkName = "WDSOQASubCVnet01"
};
Trace.TraceInformation("Begin creating VM: " + item["name"]);
csClient.VirtualMachines.CreateDeployment("serviceName", createDeploymentParams);
Trace.TraceInformation("End : " + item["name"]);
Trace.TraceInformation("VM information : " );
Trace.TraceInformation("VM information Cloudservice: xx");
Trace.TraceInformation("VM information Name: xx");
Trace.TraceInformation("VM information VNet: WDSOQASubCVnet01");
Trace.TraceInformation("VM information Size: Standard_DS1_v2");
}
#endregion
}
}
用到的自定义的类
public static class VMClass
{
public static Uri GetVhdUri(string blobcontainerAddress, string cloudServiceName, string vmName,
bool cacheDisk = false, bool https = false)
{
var now = DateTime.UtcNow;
string dateString = now.Year + "-" + now.Month + "-" + now.Day;
string timeString = now.Hour + "-" + now.Second;
var address = string.Format("{0}/{1}-{2}-{3}-{4}-650.vhd", blobcontainerAddress, cloudServiceName, vmName, cacheDisk ? "-CacheDisk" : timeString, dateString);
return new Uri(address);
}
}
第一个Azure应用的更多相关文章
- ASP.NET Core 中文文档 第二章 指南(3)用 Visual Studio 发布一个 Azure 云 Web 应用程序
原文:Getting Started 作者:Rick Anderson 翻译:谢炀(Kiler) 校对:孟帅洋(书缘).刘怡(AlexLEWIS).何镇汐 设置开发环境 安装最新版本的 Azure S ...
- 初码-Azure系列-存储队列的使用与一个Azure小工具(蓝天助手)
初码Azure系列文章目录 将消息队列技术模型简化,并打造成更适合互联网+与敏捷开发的云服务模式,好像已经是行业趋势,阿里云也在推荐使用消息服务(HTTP协议为主)而来替代消息队列(TCP协议.MQT ...
- 一个Azure VM RDP连接问题
由于Azure上的VM都是通过同一个镜像文件创建的,有时会需要修改SID. 在给一台VM修改SID重启后,就无法通过RDP连接到虚机了,从Azure管理界面的启动诊断界面上可以看到虚拟停在一个要求用户 ...
- 落地Azure CosmosDb的一个项目分享
我们遇到了什么? 我们有这么一个业务场景,就是某供应商会去爬取某些数据,爬到后会发到一个FTP上,然后我们定时去获取这些数据 这个数据有大有小,小的30多M数据量百万级,大的数据量能到数百M上千万数据 ...
- Azure Queue Storage 基本用法 -- Azure Storage 之 Queue
Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob.Queue.File 和 Table. 笔者在<Azure File Storage 基 ...
- Azure File Storage 基本用法 -- Azure Storage 之 File
Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob.Queue.File 和 Table. 笔者在<Azure Blob Storage 基 ...
- Azure机器学习入门(二)创建Azure机器学习工作区
我们将开始深入了解如何使用Azure机器学习的基本功能,帮助您开始迈向Azure机器学习的数据科学家之路. Azure ML Studio (Azure Machine Learning Studio ...
- 迁移 SQL Server 数据库到 Azure SQL 实战
最近有个维护的项目需要把 SQL Server 2012 的数据库迁移到 Azure SQL 上去,迁移过程可谓一波三折,故在此分享这次迁移中碰到的点点滴滴,希望对朋友们有所帮助. 文章来源:葡萄城产 ...
- Azure的负载均衡机制
负载均衡一直是一个比较重要的议题,几乎所有的Azure案例或者场景都不可避免,鉴于经常有客户会问,所以笔者觉得有必要总结一下. Azure提供的负载均衡机制,按照功能,可以分为三种:Azure Loa ...
随机推荐
- (cvpr2019 ) Better Version of SRMD
SRMD的内容上篇,已经介绍,本文主要介绍SRMD的升级版,解决SRMD的诸多问题, 并进行模拟实验. 进行双三次差值(bicubic)===>对应matlab imresize() %% re ...
- Linux基础命令---dmeg显示内核输出
dmesg dmesg指令用来打印和控制内核的输出信息,这些信息保存早ring buffer中. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora.SUSE.open ...
- jquery的cookie插件
一.JS文件 /*! * jQuery Cookie Plugin v1.4.1 * https://github.com/carhartl/jquery-cookie * * Copyright 2 ...
- mysql查看所有触发器以及存储过程等操作集合
今天在做每个月定时扣费的功能 用到了Mysql的Event Scheduler 昨完之后发现一个问题 Event Scheduler 默认是不开启的 要在mysql内执行SET GLOBAL even ...
- Exp5 MSF基础应用 20164303景圣
一.实践内容 本实践目标是掌握metasploit的基本应用方式,重点常用的三种攻击方式的思路.具体需要完成: 1.一个主动攻击实践,如ms08_067; (成功) 2.一个针对浏览器的攻击,如ms1 ...
- graph easy绘制ascii简易流程图
graph-easy 日常我们经常需要画一些简易流程图,但是如果使用visio等工具来作图,一则略显大材小用,二则图片导出后再要粘贴.相比下,如果可以简单的用一些text的图来表达,则会简单的多.比如 ...
- 立即执行函数(自执行函数) IIFE
// 最常用的两种写法 (function(){ /* code */ }()); // 老道推荐写法 (function(){ /* code */ })(); // 当然这种也可以 // 括号和J ...
- 王之泰201771010131《面向对象程序设计(java)》第十四周学习总结
第一部分:理论知识学习部分 第12章 Swing用户界面组件 12.1.Swing和MVC设计模式 a 设计模式初识b 模型—视图—控制器模式c Swing组件的模型—视图—控制器分析 12.2布局管 ...
- ES6中的类和继承
class的写法及继承 JavaScript 语言中,生成实例对象的传统方法是通过构造函数.下面是一个例子 function Point(x, y) { this.x = x; this. ...
- windows cannot find powershell.exe windows 7
This can happen when the environment variables are missing an entry for Powershell. $env:path must i ...