生活随笔
收集整理的這篇文章主要介紹了
Dapr牵手.NET学习笔记:Actor一个场景
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
接上一篇最后的場(chǎng)景,為了解決相同帳戶并發(fā)引起的數(shù)據(jù)庫(kù)行級(jí)鎖,可以引入Actor的串機(jī)制,相同ActorID的實(shí)例,串行,這樣就能在應(yīng)用層把讀取余額的資源爭(zhēng)搶解決掉,剩下的工作就是一定時(shí)間間隔,把內(nèi)存中的數(shù)據(jù)批量更新到數(shù)據(jù)庫(kù)中,大大減少了數(shù)據(jù)庫(kù)的資源占用。
不廢話了,看實(shí)現(xiàn)代碼吧。
IAccountActor接口
public interface IAccountActor : IActor
{Task<decimal> ChargeAsync(decimal amount);
}
AccountActor實(shí)現(xiàn)
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();
客戶端調(diào)用我是模擬一次50并發(fā),當(dāng)然也可以也可以換成web api,自動(dòng)同步用了一個(gè)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("回車?yán)^續(xù)發(fā)一批,退出按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} 定時(shí)處理完后余額:{newBalance} 總體余額:{total}");Console.ResetColor();}
}
測(cè)試時(shí),不停的按回車,一段時(shí)間后查看“全部存款匯總”和后臺(tái)任務(wù)處理的“總體余額”是否相等,相等的話說明多批次存款和多批次保存余額的數(shù)值相等,沒有丟失敗數(shù)據(jù)。
本質(zhì)上,這里是把數(shù)據(jù)庫(kù)的行級(jí)鎖,轉(zhuǎn)換成了調(diào)用方法的串行(方法里緩存計(jì)算數(shù)據(jù))化。
總結(jié)
以上是生活随笔為你收集整理的Dapr牵手.NET学习笔记:Actor一个场景的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。