第一个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 ...
随机推荐
- spring-boot集成activiti的model遇到问题汇总
按照网上的七拼八凑整合网页版的部署将遇到的问题归置如下: 本人的springboot版本是:1.5.13.RELEASE 工作流相关: <!--工作流--> <dependency& ...
- jquery的优良继承方法
说一下好处:这个封装函数可以可以实现子类继承父类原型对象里面的所有方法和属性,但是也留了第二条路,去继承父类构造函数的里面的东西. 两个参数分别是子类的构造函数,后面是父类构造函数 $.inherit ...
- springboot整合redis(简单整理)
Redis安装与开启 我这里是在windows上练习,所以这里的安装是指在windows上的安装,操作非常简单,点击https://github.com/MicrosoftArchive/redis/ ...
- WindowsService调用API
本文着重于WindowsServic如何调用API以及出现部分问题的解决方案 本文Windows Service 创建摘自JasperXu的博客 链接:http://www.cnblogs.com ...
- xtrabackup 2.4.3 BUG
用XtraBackup对备份集进行apply log 的时候,卡在 xtrabackup 版本:2.4.3 InnoDB: Waited for 1535930 seconds for 128 pen ...
- 【题解】Luogu P4381 [IOI2008]Island
原题传送门 题意:求基环树森林的直径(所有基环树直径之和) 首先,我们要对环上所有点的子树求出它们的直径和最大深度.然后,我们只用考虑在环上至少经过一条边的路径.那么,这种路径在环上一定有起始点和终点 ...
- 2.裴波那契(Fibonacci)数列
裴波那契(Fibonacci)数列 f(n)= ⎧⎩⎨0,1,f(n−1)+f(n−2),n =0n =1n>1 求裴波那契数列的第n项.(题目来自剑指offer) 1.递归解法,效率很低的解法 ...
- lsyncd+rsync配置图片资源双向同步
需求:为保证国内外图片加载速度,国内请求上传图片资源地址阿里云oss,国外请求上传图片资源地址aws s3,为保证图片资源的一致性,需定时进行oss和s3图片双向同步 调研方案:由于之前配置过inot ...
- webpack4 系列教程(十六):开发模式和生产模式·实战
好文章 https://www.jianshu.com/p/f2d30d02b719
- zabbix触发器表达式
zabbix触发器表达式 触发器使用逻辑表达式来评估通过item获取的数据是处于哪种状态, 触发器中的表达式使用很灵活,我们可以创建一个复杂的逻辑测试监控,触发器表达式形式如下: {<serve ...