68 lines
2.1 KiB
C#
68 lines
2.1 KiB
C#
using Hopetry.Provider;
|
||
using Newtonsoft.Json;
|
||
using StackExchange.Redis;
|
||
|
||
namespace Hopetry.Services
|
||
{
|
||
public class RedisService : IDisposable
|
||
{
|
||
private readonly ConnectionMultiplexer _redis;
|
||
private readonly IDatabase _db;
|
||
private const string Prefix = "client:";
|
||
|
||
public RedisService(string connectionString)
|
||
{
|
||
var config = ConfigurationOptions.Parse(connectionString);
|
||
config.AbortOnConnectFail = false;
|
||
config.ConnectTimeout = 5000;
|
||
_redis = ConnectionMultiplexer.Connect(config);
|
||
_db = _redis.GetDatabase();
|
||
}
|
||
|
||
// 存储客户端信息(自动过期30天)
|
||
public async Task StoreClientInfoAsync(SystemInfo info)
|
||
{
|
||
var key = $"{Prefix}{info.MachineId}";
|
||
var json = JsonConvert.SerializeObject(info);
|
||
await _db.StringSetAsync(key, json, TimeSpan.FromDays(30));
|
||
}
|
||
|
||
// 获取单个客户端信息
|
||
public async Task<SystemInfo> GetClientInfoAsync(string machineId)
|
||
{
|
||
var json = await _db.StringGetAsync($"{Prefix}{machineId}");
|
||
return json.HasValue ? JsonConvert.DeserializeObject<SystemInfo>(json) : null;
|
||
}
|
||
|
||
// 获取所有客户端信息
|
||
public async Task<List<SystemInfo>> GetAllClientsAsync()
|
||
{
|
||
var endpoints = _redis.GetEndPoints();
|
||
var server = _redis.GetServer(endpoints.First());
|
||
var keys = server.Keys(pattern: $"{Prefix}*").ToArray();
|
||
|
||
var results = new List<SystemInfo>();
|
||
foreach (var key in keys)
|
||
{
|
||
var json = await _db.StringGetAsync(key);
|
||
if (json.HasValue)
|
||
{
|
||
results.Add(JsonConvert.DeserializeObject<SystemInfo>(json));
|
||
}
|
||
}
|
||
return results;
|
||
}
|
||
|
||
// 删除客户端信息
|
||
public async Task<bool> DeleteClientAsync(string machineId)
|
||
{
|
||
return await _db.KeyDeleteAsync($"{Prefix}{machineId}");
|
||
}
|
||
|
||
public void Dispose()
|
||
{
|
||
_redis?.Dispose();
|
||
}
|
||
}
|
||
}
|