Skip to content

Instantly share code, notes, and snippets.

@profesor79
Last active March 4, 2023 17:30
Show Gist options
  • Save profesor79/d27c86404d5ca7a89fc82f1fdf8e36da to your computer and use it in GitHub Desktop.
Save profesor79/d27c86404d5ca7a89fc82f1fdf8e36da to your computer and use it in GitHub Desktop.
A class and an actor comparision
using System.Diagnostics;
using Akka.Actor;
using Akka.Cluster.Hosting;
using Akka.Event;
using Akka.Hosting;
using Akka.Remote.Hosting;
using ASimpleApiwithActor;
using Petabridge.Cmd.Cluster;
using Petabridge.Cmd.Cluster.Sharding;
using Petabridge.Cmd.Host;
using Petabridge.Cmd.Remote;
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
var builder = WebApplication.CreateBuilder(args);
builder.Configuration
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environment}.json", optional: true)
.AddEnvironmentVariables();
builder.Logging.ClearProviders().AddConsole();
builder.Services.AddControllers();
var app = builder.Build();
app.UseRouting();
var system = ActorSystem.Create("example");
var bookActor = system.ActorOf(Props.Create(() => new BookActor()), "book");
var bookWriterForClass = new BookWriter($"trash\\fromClass_{DateTime.UtcNow.Date.ToFileTimeUtc()}.txt");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapPost("/actor", async (HttpContext context, BookData bd) =>
{
bd.BookId = context.TraceIdentifier;
var resp = await bookActor.Ask<string>(bd);
await context.Response.WriteAsync(resp);
});
endpoints.MapPost("/class", async (HttpContext context, BookData bd) =>
{
bd.BookId = context.TraceIdentifier;
bookWriterForClass.WriteBook(bd);
await context.Response.WriteAsync(bd.BookId);
});
});
await app.RunAsync();
public class BookWriter
{
private readonly string _fileName;
public BookWriter(string fileName)
{
_fileName = fileName;
var s = File.Create(_fileName);
s.Close();
}
public void WriteBook(BookData bd)
{
File.AppendAllText(_fileName, $"{DateTime.UtcNow.ToFileTimeUtc()},{bd.BookId}, {bd.AuthorName}, {bd.Title}\n");
}
}
public sealed class BookActor : ReceiveActor
{
private readonly ILoggingAdapter _log = Context.GetLogger();
private BookWriter _bookWriter;
public BookActor()
{
_bookWriter = new BookWriter($"trash\\fromActor_{DateTime.UtcNow.Date.ToFileTimeUtc()}.txt");
Receive<BookData>(_ =>
{
_bookWriter.WriteBook(_);
Sender.Tell(_.BookId);
});
}
}
public class BookData
{
public string BookId { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string AuthorName { get; set; } = string.Empty;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment