using Furion;
|
using Furion.DependencyInjection;
|
using Microsoft.AspNetCore.DataProtection.KeyManagement;
|
using SqlSugar;
|
using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
|
namespace EzCoreNet.Redis
|
{
|
public class EzCoreNetRedisService : IEzCoreNetRedisService,IScoped
|
{
|
public bool Add(string key, object value, int expireSeconds)
|
{
|
return RedisHelper.Set(key, value, expireSeconds);
|
}
|
|
|
public bool DelKey(string key)
|
{
|
RedisHelper.Del(key);
|
return true;
|
}
|
|
public T? Get<T>(string key)
|
{
|
return RedisHelper.Get<T>(key);
|
}
|
|
public long GetTtl(string key)
|
{
|
|
return RedisHelper.Ttl(key);
|
}
|
|
public bool SetTtl(string key, int ttl)
|
{
|
return RedisHelper.Expire(key, ttl);
|
}
|
|
/// <summary>
|
/// 设置一个键值
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
/// <param name="key"></param>
|
/// <param name="value"></param>
|
/// <returns></returns>
|
public bool Add<T>(string key, T value, int expireSeconds = -1)
|
{
|
return RedisHelper.Set(key, value, expireSeconds);
|
}
|
|
public async Task<long> delegateAllKeyWith(string Prefix)
|
{
|
// 使用Scan模式匹配所有符合前缀的key
|
var keys = GetAllKey(Prefix);
|
|
// 批量删除找到的keys
|
if (keys != null && keys.Count() > 0)
|
{
|
return await RedisHelper.DelAsync(keys.ToArray());
|
}
|
|
return 0; // 如果没有找到匹配的key,返回0
|
}
|
|
public IEnumerable<string> GetAllKey(string Prefix)
|
{
|
return RedisHelper.Keys(Prefix + "*");
|
}
|
|
/// <summary>
|
/// 后去一个缓存,如果没有,则从数据库中获取,
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
/// <param name="key"></param>
|
/// <param name="DataFormSql">读取方法</param>
|
/// <param name="dc"> 读取的数据库服务</param>
|
/// <param name="expireSeconds"></param>
|
/// <returns></returns>
|
|
public T? GetAndRefCacheKey<T>(string key, Func<ISqlSugarClient, T> DataFormSql, ISqlSugarClient? dc = null, int? expireSeconds = 3600)
|
{
|
var Data = RedisHelper.Get<T>(key);
|
if (Data == null && DataFormSql != null)
|
{
|
if (dc == null)
|
dc = App.GetService<ISqlSugarClient>();
|
Data = DataFormSql.Invoke(dc);
|
|
// Data = DataFormSql.BeginInvoke(dc,ar=> DataFormSql.EndInvoke(ar),null);
|
if (expireSeconds == null)
|
expireSeconds = -1;
|
if (Data != null)
|
RedisHelper.Set(key, Data, (int)expireSeconds);
|
|
}
|
return Data;
|
}
|
|
public long Incrby(string key)
|
{
|
return RedisHelper.IncrBy(key);
|
}
|
|
public string Get32sn()
|
{
|
string formattedDate = DateTime.Now.ToString("yyyyMMdd");
|
|
|
var sn = Incrby($"CreatSnKey:{formattedDate}");
|
if(sn<1)
|
{
|
//设置有效期限为24小时
|
SetTtl($"CreatSnKey:{formattedDate}", 24 * 60 * 60);
|
}
|
string re = "Ez" + formattedDate + sn.ToString();
|
|
return re;
|
}
|
}
|
}
|