最简单的 Service Fabric 可靠集合(字典)示例
Simplest Service Fabric Reliable Collection (Dictionary) example
我正在尝试实施 Azure 的 Service Fabric Reliable Collection 的最简单用法 --- 一个 Hello World
示例,因为它是 ---一个 IReliableDictionary
.
In this link an example is given. Yet this example requires a StateManager
object, which I'm unsure how to create or even what it is. It seems an Actor 是必需的,我希望暂时避免使用 Actors。
谁能举个例子?
非常感谢
没关系,我找到了答案。
关键是无法在无状态服务中创建可靠的集合,我们必须创建一个有状态服务,如果我们想利用 Reliable Collections。
Here 我找到了一个 Reliable Dictionary 的实现示例。接下来我粘贴代码,它应该放在 MyStatefulService.cs
class:
protected override async Task RunAsync(CancellationToken cancellationToken)
{
var myDictionary = await this.StateManager.GetOrAddAsync<IReliableDictionary<string, long>>("myDictionary");
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
using (var tx = this.StateManager.CreateTransaction())
{
var result = await myDictionary.TryGetValueAsync(tx, "Counter");
ServiceEventSource.Current.ServiceMessage(this, "Current Counter Value: {0}",
result.HasValue ? result.Value.ToString() : "Value does not exist.");
await myDictionary.AddOrUpdateAsync(tx, "Counter", 0, (key, value) => ++value);
// If an exception is thrown before calling CommitAsync, the transaction aborts, all changes are
// discarded, and nothing is saved to the secondary replicas.
await tx.CommitAsync();
}
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
我正在尝试实施 Azure 的 Service Fabric Reliable Collection 的最简单用法 --- 一个 Hello World
示例,因为它是 ---一个 IReliableDictionary
.
In this link an example is given. Yet this example requires a StateManager
object, which I'm unsure how to create or even what it is. It seems an Actor 是必需的,我希望暂时避免使用 Actors。
谁能举个例子?
非常感谢
没关系,我找到了答案。
关键是无法在无状态服务中创建可靠的集合,我们必须创建一个有状态服务,如果我们想利用 Reliable Collections。
Here 我找到了一个 Reliable Dictionary 的实现示例。接下来我粘贴代码,它应该放在 MyStatefulService.cs
class:
protected override async Task RunAsync(CancellationToken cancellationToken)
{
var myDictionary = await this.StateManager.GetOrAddAsync<IReliableDictionary<string, long>>("myDictionary");
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
using (var tx = this.StateManager.CreateTransaction())
{
var result = await myDictionary.TryGetValueAsync(tx, "Counter");
ServiceEventSource.Current.ServiceMessage(this, "Current Counter Value: {0}",
result.HasValue ? result.Value.ToString() : "Value does not exist.");
await myDictionary.AddOrUpdateAsync(tx, "Counter", 0, (key, value) => ++value);
// If an exception is thrown before calling CommitAsync, the transaction aborts, all changes are
// discarded, and nothing is saved to the secondary replicas.
await tx.CommitAsync();
}
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}