Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

添加Starfish.Redis项目 #6

Merged
merged 1 commit into from
Dec 22, 2023
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
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
<PackageVersion Include="Euonia.Repository.EfCore" Version="$(EuoniaPackageVersion)" />
<PackageVersion Include="IdentityModel" Version="6.2.0" />
<PackageVersion Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.11" />
<PackageVersion Include="StackExchange.Redis" Version="2.7.10" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
<ItemGroup>
Expand Down
3 changes: 0 additions & 3 deletions Source/Starfish.Client/FodyWeavers.xml

This file was deleted.

30 changes: 0 additions & 30 deletions Source/Starfish.Client/FodyWeavers.xsd

This file was deleted.

9 changes: 2 additions & 7 deletions Source/Starfish.Client/Starfish.Client.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
<Import Project="..\common.props"/>

<PropertyGroup>
<Nullable>disable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>true</IsPackable>
<Description>A lightweight powerful distributed configuration server for .NET application.</Description>
</PropertyGroup>

<ItemGroup>
Expand Down Expand Up @@ -42,9 +42,4 @@
<Using Include="$(RootNamespace).Properties"/>
</ItemGroup>

<ItemGroup Condition="'$(Configuration)' == 'Release'">
<PackageReference Include="ConfigureAwait.Fody"/>
<PackageReference Include="Fody"/>
</ItemGroup>

</Project>
52 changes: 5 additions & 47 deletions Source/Starfish.Common/RandomUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,22 @@
namespace Nerosoft.Starfish.Common;

/// <summary>
/// 随机数工具类
/// A utility class for generating random numbers or strings.
/// </summary>
internal class RandomUtility : Random
{
private static readonly RandomNumberGenerator _generator = RandomNumberGenerator.Create();
private readonly byte[] _uint32Buffer = new byte[4];

/// <summary>
/// 创建随机数键值
/// Generate a random string with a given size.
/// </summary>
/// <param name="length">长度</param>
/// <param name="length"></param>
/// <returns></returns>
public static byte[] CreateRandomKey(int length)
{
var bytes = new byte[length];
_generator.GetBytes(bytes);

return bytes;
}

/// <summary>
/// 创建随机键值字符串
/// </summary>
/// <param name="length">长度</param>
/// <returns></returns>
public static string CreateRandomKeyString(int length)
{
var bytes = new byte[length];
_generator.GetBytes(bytes);

return Convert.ToBase64String(bytes);
}

/// <summary>
/// 创建唯一编号
/// </summary>
/// <param name="length">长度</param>
/// <returns></returns>
public static string CreateUniqueId(int length = 32)
public static string GenerateUniqueId(int length = 32)
{
var bytes = new byte[Convert.ToInt32(length / 2)];
_generator.GetBytes(bytes);
//转化为16进制
var hex = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
Expand All @@ -55,21 +28,6 @@ public static string CreateUniqueId(int length = 32)
return hex.ToString();
}

/// <summary>
/// Initializes a new instance of the <see cref="RandomUtility"/> class.
/// </summary>
public RandomUtility()
{
}

/// <summary>
/// Initializes a new instance of the <see cref="RandomUtility"/> class.
/// </summary>
/// <param name="ignoredSeed">seed (ignored)</param>
public RandomUtility(int ignoredSeed)
{
}

/// <summary>
/// Returns a nonnegative random number.
/// </summary>
Expand Down Expand Up @@ -158,4 +116,4 @@ public override void NextBytes(byte[] buffer)
throw new ArgumentNullException(nameof(buffer));
_generator.GetBytes(buffer);
}
}
}
95 changes: 95 additions & 0 deletions Source/Starfish.Redis/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Microsoft.Extensions.Configuration.Redis

Redis configuration provider implementation for [Microsoft.Extensions.Configuration](https://www.nuget.org/packages/Microsoft.Extensions.Configuration/).

## Redis key/value

The Redis configuration provider requires a hash key in Redis. The following example shows how to store json settings to Redis hash structure.

> **Note:** The Redis configuration provider does not support nested values.

**Origin json data**

```json
{
"Settings": {
"Server": "localhost",
"Database": "master",
"Ports": [ "1433", "1434", "1435" ]
}
}
```

The Redis key/value pair structure is shown below.

**Redis key:**
`appsettings`

**Redis value:**
```text
Settings:Server = localhost
Settings:Database = master
Settings:Ports:0 = 1433
Settings:Ports:1 = 1434
Settings:Ports:2 = 1435
```

## How to?
The following example shows how to read application settings from the Redis.

### Install NuGet package

NuGet package: [Starfish.Redis](https://www.nuget.org/packages/Starfish.Redis/)

```bash
Install-Package Starfish.Redis
```

```powershell
dotnet add package Starfish.Redis
```

```xml
<PackageReference Include="Starfish.Redis" Version="$(StarfishVersion)" />
```

### Add Redis configuration provider

```cs
using System;
using Microsoft.Extensions.Configuration;

class Program
{
static void Main()
{
IConfiguration config = new ConfigurationBuilder()
.AddRedis("127.0.0.1:6379,ssl=False,allowAdmin=True,abortConnect=False,defaultDatabase=0,connectTimeout=500,connectRetry=3", "appsettings")
.Build();

// Get a configuration section
IConfigurationSection section = config.GetSection("Settings");

// Read simple values
Console.WriteLine($"Server: {section["Server"]}");
Console.WriteLine($"Database: {section["Database"]}");

// Read a collection
Console.WriteLine("Ports: ");
IConfigurationSection ports = section.GetSection("Ports");

foreach (IConfigurationSection child in ports.GetChildren())
{
Console.WriteLine(child.Value);
}
}
}
```

## Enable Redis Keyspace Notifications

The Redis configuration provider uses Redis keyspace notifications to invalidate the cache when the configuration changes. The Redis keyspace notifications are disabled by default. To enable the Redis keyspace notifications, set the `notify-keyspace-events` configuration option in the Redis configuration file to `AKE`.

1. Open terminal and run `redis-cli`.
2. Check the current configuration value use `CONFIG GET notify-keyspace-events`.
3. Set the `notify-keyspace-events` configuration option to `AKE` use `CONFIG SET notify-keyspace-events AKE`.
116 changes: 116 additions & 0 deletions Source/Starfish.Redis/RedisConfigurationClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
using Microsoft.Extensions.Primitives;
using StackExchange.Redis;

namespace Microsoft.Extensions.Configuration.Redis;

internal class RedisConfigurationClient : IAsyncDisposable
{
private readonly int _database;
private readonly string _key;
private readonly bool _keyspaceEnabled;

private readonly SemaphoreSlim _semaphoreSlim = new(0, 1);

private Timer _timer;
private ISubscriber _subscriber;

public RedisConfigurationClient(string connectionString, int database, string key, bool keyspaceEnabled)
{
_database = database;
_key = key;
_keyspaceEnabled = keyspaceEnabled;
Connect(connectionString);
}

private ConnectionMultiplexer Connection { get; set; }

private CancellationTokenSource CancellationSource { get; set; }

public async Task<Dictionary<string, string>> LoadAsync()
{
await _semaphoreSlim.WaitAsync();

if (Connection == null)
{
return [];
}

return await Connection.GetDatabase(_database)
.HashGetAllAsync(_key)
.ContinueWith(task =>
{
return task.Result.ToDictionary(x => x.Name.ToString(), x => ReadRedisValue(x.Value));
});
}

private async void Connect(string connectionString)
{
try
{
Connection = await ConnectionMultiplexer.ConnectAsync(connectionString);

if (_keyspaceEnabled)
{
var channel = RedisChannel.Pattern($"__keyspace@{_database}__:{_key}");

_subscriber = Connection.GetSubscriber();
await _subscriber.SubscribeAsync(channel, (_, _) =>
{
CancellationSource?.Cancel();
});
}
else
{
_timer = new Timer(_ => CancellationSource?.Cancel(), null, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(30));
}
}
catch
{
// ignored
}
finally
{
_semaphoreSlim.Release();
}
}

private static string ReadRedisValue(RedisValue value)
{
if (value.IsNull)
{
return null;
}

return value.IsNullOrEmpty ? string.Empty : value.ToString();
}

public async ValueTask DisposeAsync()
{
if (Connection != null)
{
await Connection.CloseAsync();
await Connection.DisposeAsync();
}

if (_timer != null)
{
await _timer.DisposeAsync();
}

if (_subscriber != null)
{
await _subscriber.UnsubscribeAllAsync();
_subscriber = null;
}

CancellationSource?.Dispose();
}

public IChangeToken Watch()
{
CancellationSource?.Dispose();
CancellationSource = new CancellationTokenSource();
var cancellationToken = new CancellationChangeToken(CancellationSource.Token);
return cancellationToken;
}
}
Loading
Loading