我昨晚创建了一个小项目来学习这个。我使用了 1.0 alpha,它是直截了当的。我创建了一个 Hub 并从那里开始工作:)
我的项目有 N 个计算单元(一些服务器处理工作),当它们启动时,它们会调用 ComputeUnitRegister。
await HubProxy.Invoke("ComputeUnitReqisted", _ComputeGuid);
每次他们做某事时他们都会打电话
HubProxy.Invoke("Running", _ComputeGuid);
HubProxy 在哪里:
HubConnection Hub = new HubConnection(RoleEnvironment.IsAvailable ?
RoleEnvironment.GetConfigurationSettingValue("SignalREndPoint"):
"http://taskqueue.cloudapp.net/");
IHubProxy HubProxy = Hub.CreateHubProxy("ComputeUnits");
我使用 RoleEnviroment.IsAvailable 是因为我现在可以将其作为 Azure Role、控制台应用程序或 .NET 4.5 中的任何内容运行。 Hub 被放置在一个 MVC4 网站项目中,并像这样启动:
GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(50);
RouteTable.Routes.MapHubs();
public class ComputeUnits : Hub
{
public Task Running(Guid MyGuid)
{
return Clients.Group(MyGuid.ToString()).ComputeUnitHeartBeat(MyGuid,
DateTime.UtcNow.ToEpochMilliseconds());
}
public Task ComputeUnitReqister(Guid MyGuid)
{
Groups.Add(Context.ConnectionId, "ComputeUnits").Wait();
return Clients.Others.ComputeUnitCameOnline(new { Guid = MyGuid,
HeartBeat = DateTime.UtcNow.ToEpochMilliseconds() });
}
public void SubscribeToHeartBeats(Guid MyGuid)
{
Groups.Add(Context.ConnectionId, MyGuid.ToString());
}
}
我的客户是 Javascript 客户,它们有方法(如果您还需要查看此代码,请告诉我)。但基本上他们监听ComputeUnitCameOnline,当它运行时他们调用服务器SubscribeToHeartBeats。这意味着无论何时服务器计算单元正在执行某些工作,它都会调用 Running,这将在 JavaScript 客户端上触发 ComputeUnitHeartBeat。
我希望您可以使用它来了解如何使用组和连接。最后,它还通过添加几行代码来扩展多个 azure 角色:
GlobalHost.HubPipeline.EnableAutoRejoiningGroups();
GlobalHost.DependencyResolver.UseServiceBus(
serviceBusConnectionString,
2,
3,
GetRoleInstanceNumber(),
topicPathPrefix /* the prefix applied to the name of each topic used */
);
您可以在 azure 上获取服务总线上的连接字符串,记住 Provider=SharedSecret。但是在添加 nuget 打包时,连接字符串语法也会粘贴到您的 web.config 中。
2 是要拆分多少个主题。主题可以包含 1Gb 的数据,因此您可以根据性能增加它。
3 是拆分它的节点数。我使用了 3,因为我有 2 个 Azure 实例和我的本地主机。您可以像这样获得 RoleNumber(请注意,我将 localhost 硬编码为 2)。
private static int GetRoleInstanceNumber()
{
if (!RoleEnvironment.IsAvailable)
return 2;
var roleInstanceId = RoleEnvironment.CurrentRoleInstance.Id;
var li1 = roleInstanceId.LastIndexOf(".");
var li2 = roleInstanceId.LastIndexOf("_");
var roleInstanceNo = roleInstanceId.Substring(Math.Max(li1, li2) + 1);
return Int32.Parse(roleInstanceNo);
}
你可以在http://taskqueue.cloudapp.net/#/compute-units看到这一切。