Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ The `CodeCargo.Nats.HybridCacheExtensions` package provides an extension method

```bash
dotnet add package CodeCargo.Nats.HybridCacheExtensions
dotnet add package NATS.Net
dotnet add package NATS.Extensions.Microsoft.DependencyInjection
```

### Example
Expand All @@ -38,30 +38,36 @@ using CodeCargo.Nats.HybridCacheExtensions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NATS.Client.Core;
using NATS.Client.Hosting;
using NATS.Client.KeyValueStore;
using NATS.Extensions.Microsoft.DependencyInjection;
using NATS.Net;

// Set the NATS URL, this normally comes from configuration
const string natsUrl = "nats://localhost:4222";

// Create a host builder for a Console application
// For a Web Application you can use WebApplication.CreateBuilder(args)
var builder = Host.CreateDefaultBuilder(args);
builder.ConfigureServices(services =>
{
services.AddNats(configureOpts: options => options with { Url = natsUrl });

services.AddNatsClient(natsBuilder => natsBuilder.ConfigureOptions(opts => opts with { Url = natsUrl }));
services.AddNatsHybridCache(options =>
{
options.BucketName = "cache";
});
});

var host = builder.Build();

// Ensure that the KV Store is created
var natsConnection = host.Services.GetRequiredService<INatsConnection>();
var kvContext = natsConnection.CreateKeyValueStoreContext();
await kvContext.CreateOrUpdateStoreAsync(new NatsKVConfig("cache")
{
LimitMarkerTTL = TimeSpan.FromSeconds(1)
});

// Start the host
await host.RunAsync();
```

Expand All @@ -71,7 +77,7 @@ await host.RunAsync();

```bash
dotnet add package CodeCargo.Nats.DistributedCache
dotnet add package NATS.Net
dotnet add package NATS.Extensions.Microsoft.DependencyInjection
```

### Example
Expand All @@ -81,30 +87,33 @@ using CodeCargo.Nats.DistributedCache;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NATS.Client.Core;
using NATS.Client.Hosting;
using NATS.Client.KeyValueStore;
using NATS.Extensions.Microsoft.DependencyInjection;
using NATS.Net;

// Set the NATS URL, this normally comes from configuration
const string natsUrl = "nats://localhost:4222";

// Create a host builder for a Console application
// For a Web Application you can use WebApplication.CreateBuilder(args)
var builder = Host.CreateDefaultBuilder(args);
builder.ConfigureServices(services =>
{
services.AddNats(configureOpts: options => options with { Url = natsUrl });

services.AddNatsClient(natsBuilder => natsBuilder.ConfigureOptions(opts => opts with { Url = natsUrl }));
services.AddNatsDistributedCache(options =>
{
options.BucketName = "cache";
});
});

var host = builder.Build();

// Ensure that the KV Store is created
var natsConnection = host.Services.GetRequiredService<INatsConnection>();
var kvContext = natsConnection.CreateKeyValueStoreContext();
await kvContext.CreateOrUpdateStoreAsync(new NatsKVConfig("cache")
{
LimitMarkerTTL = TimeSpan.FromSeconds(1)
});
await kvContext.CreateOrUpdateStoreAsync(new NatsKVConfig("cache") { LimitMarkerTTL = TimeSpan.FromSeconds(1) });

// Start the host
await host.RunAsync();
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NATS.Client.Core;
using NATS.Client.Hosting;
using NATS.Client.KeyValueStore;
using NATS.Extensions.Microsoft.DependencyInjection;
using NATS.Net;

// The abbreviated example put into the README.md
// Based on Program.cs
public static class Abbreviated
// Example used in the README.md "Use `IDistributedCache` Directly" section
public static class DistributedCacheExample
{
public static async Task Run(string[] args)
{
Expand All @@ -18,39 +17,21 @@ public static async Task Run(string[] args)
// Create a host builder for a Console application
// For a Web Application you can use WebApplication.CreateBuilder(args)
var builder = Host.CreateDefaultBuilder(args);

// Add services to the container
builder.ConfigureServices(services =>
{
// Add NATS client
services.AddNats(configureOpts: options => options with { Url = natsUrl });

// Add a NATS distributed cache
services.AddNatsClient(natsBuilder => natsBuilder.ConfigureOptions(opts => opts with { Url = natsUrl }));
services.AddNatsDistributedCache(options =>
{
options.BucketName = "cache";
});

// (Optional) Add HybridCache
var hybridCacheServices = services.AddHybridCache();

// (Optional) Use NATS Serializer for HybridCache
hybridCacheServices.AddSerializerFactory(
NatsOpts.Default.SerializerRegistry.ToHybridCacheSerializerFactory());

// Add other services as needed
});

// Build the host
var host = builder.Build();

// Ensure that the KV Store is created
var natsConnection = host.Services.GetRequiredService<INatsConnection>();
var kvContext = natsConnection.CreateKeyValueStoreContext();
await kvContext.CreateOrUpdateStoreAsync(new NatsKVConfig("cache")
{
LimitMarkerTTL = TimeSpan.FromSeconds(1)
});
await kvContext.CreateOrUpdateStoreAsync(new NatsKVConfig("cache") { LimitMarkerTTL = TimeSpan.FromSeconds(1) });

// Start the host
await host.RunAsync();
Expand Down
36 changes: 16 additions & 20 deletions util/ReadmeExample/DistributedCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NATS.Client.Core;
using NATS.Client.Hosting;
using NATS.Client.KeyValueStore;
using NATS.Extensions.Microsoft.DependencyInjection;
using NATS.Net;

namespace CodeCargo.ReadmeExample;
Expand Down Expand Up @@ -36,10 +36,12 @@ public static async Task RunAsync(string[] args)
throw new InvalidOperationException("Cannot find connection string for NATS");
}

// Create a host builder for a Console application
// For a Web Application you can use WebApplication.CreateBuilder(args)
var builder = Host.CreateDefaultBuilder(args);
builder.ConfigureServices(services =>
{
services.AddNats(configureOpts: options => options with { Url = natsConnectionString });
services.AddNatsClient(natsBuilder => natsBuilder.ConfigureOptions(opts => opts with { Url = natsConnectionString }));
services.AddNatsDistributedCache(options =>
{
options.BucketName = "cache";
Expand All @@ -51,13 +53,15 @@ public static async Task RunAsync(string[] args)
var host = builder.Build();
var lifetime = host.Services.GetRequiredService<IHostApplicationLifetime>();

// Ensure that the KV Store is created
Console.WriteLine("Creating KV store...");
var natsConnection = host.Services.GetRequiredService<INatsConnection>();
var kvContext = natsConnection.CreateKeyValueStoreContext();
await kvContext.CreateOrUpdateStoreAsync(
new NatsKVConfig("cache") { LimitMarkerTTL = TimeSpan.FromSeconds(1) }, startupCts.Token);
Console.WriteLine("KV store created");

// Start the host
Console.WriteLine("Starting app...");
using var appCts = new CancellationTokenSource();
var appTask = Task.Run(async () =>
Expand Down Expand Up @@ -117,34 +121,26 @@ private static async Task WaitForApplicationStartAsync(IHostApplicationLifetime
}
}

public class DistributedCacheService
public class DistributedCacheService(IDistributedCache cache, ILogger<DistributedCacheService> logger)
{
private readonly IDistributedCache _cache;
private readonly ILogger<DistributedCacheService> _logger;

public DistributedCacheService(IDistributedCache cache, ILogger<DistributedCacheService> logger)
{
_cache = cache;
_logger = logger;
}

public async Task Run()
{
_logger.LogInformation("------------------------------------------");
_logger.LogInformation("DistributedCache example");
logger.LogInformation("------------------------------------------");
logger.LogInformation("DistributedCache example");

const string cacheKey = "distributed-cache-greeting";
const string value = "Hello from NATS Distributed Cache!";
await _cache.SetStringAsync(
await cache.SetStringAsync(
cacheKey,
value,
new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1) });
_logger.LogInformation("Set value in cache: {Value}", value);
logger.LogInformation("Set value in cache: {Value}", value);

var retrievedValue = await _cache.GetStringAsync(cacheKey);
_logger.LogInformation("Retrieved value from cache: {Value}", retrievedValue);
var retrievedValue = await cache.GetStringAsync(cacheKey);
logger.LogInformation("Retrieved value from cache: {Value}", retrievedValue);

await _cache.RemoveAsync(cacheKey);
_logger.LogInformation("Removed value from cache");
await cache.RemoveAsync(cacheKey);
logger.LogInformation("Removed value from cache");
logger.LogInformation("------------------------------------------");
}
}
39 changes: 39 additions & 0 deletions util/ReadmeExample/HybridCache.Example.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using CodeCargo.Nats.HybridCacheExtensions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NATS.Client.Core;
using NATS.Client.KeyValueStore;
using NATS.Extensions.Microsoft.DependencyInjection;
using NATS.Net;

// Example used in the README.md "Use with `HybridCache`" section
public static class HybridCacheExample
{
public static async Task Run(string[] args)
{
// Set the NATS URL, this normally comes from configuration
const string natsUrl = "nats://localhost:4222";

// Create a host builder for a Console application
// For a Web Application you can use WebApplication.CreateBuilder(args)
var builder = Host.CreateDefaultBuilder(args);
builder.ConfigureServices(services =>
{
services.AddNatsClient(natsBuilder => natsBuilder.ConfigureOptions(opts => opts with { Url = natsUrl }));
services.AddNatsHybridCache(options =>
{
options.BucketName = "cache";
});
});

var host = builder.Build();

// Ensure that the KV Store is created
var natsConnection = host.Services.GetRequiredService<INatsConnection>();
var kvContext = natsConnection.CreateKeyValueStoreContext();
await kvContext.CreateOrUpdateStoreAsync(new NatsKVConfig("cache") { LimitMarkerTTL = TimeSpan.FromSeconds(1) });

// Start the host
await host.RunAsync();
}
}
36 changes: 17 additions & 19 deletions util/ReadmeExample/HybridCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NATS.Client.Core;
using NATS.Client.Hosting;
using NATS.Client.KeyValueStore;
using NATS.Extensions.Microsoft.DependencyInjection;
using NATS.Net;

namespace CodeCargo.ReadmeExample;
Expand Down Expand Up @@ -36,10 +36,12 @@ public static async Task RunAsync(string[] args)
throw new InvalidOperationException("Cannot find connection string for NATS");
}

// Create a host builder for a Console application
// For a Web Application you can use WebApplication.CreateBuilder(args)
var builder = Host.CreateDefaultBuilder(args);
builder.ConfigureServices(services =>
{
services.AddNats(configureOpts: options => options with { Url = natsConnectionString });
services.AddNatsClient(natsBuilder => natsBuilder.ConfigureOptions(opts => opts with { Url = natsConnectionString }));
services.AddNatsHybridCache(options =>
{
options.BucketName = "cache";
Expand All @@ -51,13 +53,15 @@ public static async Task RunAsync(string[] args)
var host = builder.Build();
var lifetime = host.Services.GetRequiredService<IHostApplicationLifetime>();

// Ensure that the KV Store is created
Console.WriteLine("Creating KV store...");
var natsConnection = host.Services.GetRequiredService<INatsConnection>();
var kvContext = natsConnection.CreateKeyValueStoreContext();
await kvContext.CreateOrUpdateStoreAsync(
new NatsKVConfig("cache") { LimitMarkerTTL = TimeSpan.FromSeconds(1) }, startupCts.Token);
Console.WriteLine("KV store created");

// Start the host
Console.WriteLine("Starting app...");
using var appCts = new CancellationTokenSource();
var appTask = Task.Run(async () =>
Expand Down Expand Up @@ -117,31 +121,25 @@ private static async Task WaitForApplicationStartAsync(IHostApplicationLifetime
}
}

public class HybridCacheService
public class HybridCacheService(HybridCache cache, ILogger<HybridCacheService> logger)
{
private readonly HybridCache _cache;
private readonly ILogger<HybridCacheService> _logger;

public HybridCacheService(HybridCache cache, ILogger<HybridCacheService> logger)
{
_cache = cache;
_logger = logger;
}

public async Task Run()
{
_logger.LogInformation("------------------------------------------");
_logger.LogInformation("HybridCache example");
logger.LogInformation("------------------------------------------");
logger.LogInformation("HybridCache example");

const string key = "hybrid-cache-greeting";

var result = await _cache.GetOrCreateAsync<string>(
var result = await cache.GetOrCreateAsync<Person>(
key,
_ => ValueTask.FromResult("Hello from NATS Hybrid Cache!"),
_ => ValueTask.FromResult(new Person("John Doe", 30)),
new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(1) });
_logger.LogInformation("Got/created value from cache: {Result}", result);
logger.LogInformation("Got/created value from cache: {Result}", result);

await _cache.RemoveAsync(key);
_logger.LogInformation("Removed value from cache");
await cache.RemoveAsync(key);
logger.LogInformation("Removed value from cache");
logger.LogInformation("------------------------------------------");
}

private record Person(string Name, int Age);
}
2 changes: 1 addition & 1 deletion util/ReadmeExample/ReadmeExample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

<ItemGroup>
<PackageReference Include="Aspire.Hosting.Testing" Version="9.2.1" />
<PackageReference Include="NATS.Net" Version="2.6.0" />
<PackageReference Include="NATS.Extensions.Microsoft.DependencyInjection" Version="2.6.0" />
</ItemGroup>

<ItemGroup>
Expand Down
Loading