生活随笔
收集整理的這篇文章主要介紹了
Dapr牵手.NET学习笔记:Actor一个场景
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
接上一篇最后的場景,為了解決相同帳戶并發引起的數據庫行級鎖,可以引入Actor的串機制,相同ActorID的實例,串行,這樣就能在應用層把讀取余額的資源爭搶解決掉,剩下的工作就是一定時間間隔,把內存中的數據批量更新到數據庫中,大大減少了數據庫的資源占用。
不廢話了,看實現代碼吧。
IAccountActor接口
public interface IAccountActor : IActor
{Task<decimal> ChargeAsync(decimal amount);
}
AccountActor實現
using Dapr.Actors.Runtime;
using IOrderFactoryActory.Interfaces;namespace OrderFactoryService
{public class AccountActor : Actor, IAccountActor{public AccountActor(ActorHost host) : base(host){}public async Task<decimal> ChargeAsync(decimal amount){var balance = 0m;var balanceValue = await this.StateManager.TryGetStateAsync<decimal>("balance");if (balanceValue.HasValue){balance = balanceValue.Value;}balance += amount;await this.StateManager.SetStateAsync<decimal>("balance", balance);return balance;}}
}
asp.net?6引入dapr.actor
using OrderFactoryService;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddActors(options =>
{options.HttpEndpoint = "http://localhost:3999"; options.Actors.RegisterActor<AccountActor>();
});var app = builder.Build();if (app.Environment.IsDevelopment())
{app.UseSwagger();app.UseSwaggerUI();
}
app.UseAuthorization();app.UseRouting();
app.UseEndpoints(endpoints =>
{ endpoints.MapActorsHandlers();
});
app.MapControllers();
app.Run();
客戶端調用我是模擬一次50并發,當然也可以也可以換成web api,自動同步用了一個Job框架Quartz.Net,與Charge操作分離。
using Dapr.Actors;
using Dapr.Actors.Client;
using IOrderFactoryActory.Interfaces;
using Quartz;
using Quartz.Impl;
using System.Security.Cryptography;Console.WriteLine("回車開始");
Console.ReadLine();
var scheduler = await RunJobAsync();
var factory = new ActorProxyFactory(new ActorProxyOptions { HttpEndpoint = "http://localhost:3999" });
var accountNo = "808080808080808080";
var account = CreateActor(factory, accountNo);
var total = 0m;
while (true)
{var tasks = new List<Task>();for (var i = 0; i < 50; i++){var amount = RandomNumberGenerator.GetInt32(100, 5000);var chargeTask = new Task(async () =>{var balance = await account.ChargeAsync(amount);Console.WriteLine($"**** 賬戶:{accountNo} 本次存款:{amount} 緩存余額:{balance} ****");});tasks.Add(chargeTask);total += amount;}foreach (var task in tasks){task.Start();}Console.WriteLine($"全部存款匯總:{total}"); Console.WriteLine("回車繼續發一批,退出按E");if (Console.ReadLine() == "E"){break;}
}
await?scheduler.Shutdown();static IAccountActor CreateActor(ActorProxyFactory factory, string accountNo)
{var actorType = "AccountActor";var actorId = new ActorId(accountNo);return factory.CreateActorProxy<IAccountActor>(actorId, actorType);
}
static async Task<IScheduler> RunJobAsync()
{var factory = new StdSchedulerFactory();var scheduler = await factory.GetScheduler();await scheduler.Start();var job = JobBuilder.Create<SavaAccountJob>().WithIdentity("SavaAccountJob", "SavaAccountGroup").Build();var trigger = TriggerBuilder.Create().WithIdentity("SavaAccountTrigger", "SavaAccountGroup").StartNow().WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever()).Build();await scheduler.ScheduleJob(job, trigger);return scheduler;
}class SavaAccountJob : IJob
{static decimal total = 0;public async Task Execute(IJobExecutionContext context){var accountNo = "808080808080808080";var actorType = "AccountActor";var actorId = new ActorId(accountNo);var factory = new ActorProxyFactory(new ActorProxyOptions { HttpEndpoint = "http://localhost:3999" });var account = factory.CreateActorProxy<IAccountActor>(actorId, actorType);var balance = await account.ChargeAsync(0m);total += balance;var newBalance = account.ChargeAsync(-balance).Result;Console.ForegroundColor = ConsoleColor.Green;Console.WriteLine($"賬戶:{accountNo} 處理余額:{balance} 定時處理完后余額:{newBalance} 總體余額:{total}");Console.ResetColor();}
}
測試時,不停的按回車,一段時間后查看“全部存款匯總”和后臺任務處理的“總體余額”是否相等,相等的話說明多批次存款和多批次保存余額的數值相等,沒有丟失敗數據。
本質上,這里是把數據庫的行級鎖,轉換成了調用方法的串行(方法里緩存計算數據)化。
總結
以上是生活随笔為你收集整理的Dapr牵手.NET学习笔记:Actor一个场景的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。