Commit bab0aefb by lcx

no message

parent 19e7f588
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Performance.Infrastructure
{
public class MemoryCacheHelper
{
private static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions());
/// <summary>
/// 验证缓存项是否存在
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public bool Exists(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return Cache.TryGetValue(key, out _);
}
/// <summary>
/// 时间转时间戳Unix-时间戳精确到秒
/// </summary>
public TimeSpan ToUnixTimestampBySeconds(DateTime dt)
{
DateTimeOffset dto = new DateTimeOffset(dt);
return TimeSpan.FromSeconds(dto.ToUnixTimeSeconds());
}
/// <summary>
/// 添加缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="value">缓存Value</param>
/// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
/// <param name="expiressAbsoulte">绝对过期时长</param>
/// <returns></returns>
public bool Set(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
Cache.Set(key, value,
new MemoryCacheEntryOptions().SetSlidingExpiration(expiresSliding)
.SetAbsoluteExpiration(expiressAbsoulte));
return Exists(key);
}
/// <summary>
/// 添加缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="value">缓存Value</param>
/// <param name="expiresIn">缓存时长</param>
/// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
/// <returns></returns>
public bool Set(string key, object value, TimeSpan expiresIn, bool isSliding = false)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
if (value == null)
throw new ArgumentNullException(nameof(value));
Cache.Set(key, value,
isSliding
? new MemoryCacheEntryOptions().SetSlidingExpiration(expiresIn)
: new MemoryCacheEntryOptions().SetAbsoluteExpiration(expiresIn));
return Exists(key);
}
#region 删除缓存
/// <summary>
/// 删除缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public void Remove(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
Cache.Remove(key);
}
/// <summary>
/// 批量删除缓存
/// </summary>
/// <returns></returns>
public void RemoveAll(IEnumerable<string> keys)
{
if (keys == null)
throw new ArgumentNullException(nameof(keys));
keys.ToList().ForEach(item => Cache.Remove(item));
}
#endregion
#region 获取缓存
/// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public T Get<T>(string key) where T : class
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return Cache.Get(key) as T;
}
/// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public object Get(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return Cache.Get(key);
}
/// <summary>
/// 获取缓存集合
/// </summary>
/// <param name="keys">缓存Key集合</param>
/// <returns></returns>
public IDictionary<string, object> GetAll(IEnumerable<string> keys)
{
if (keys == null)
throw new ArgumentNullException(nameof(keys));
var dict = new Dictionary<string, object>();
keys.ToList().ForEach(item => dict.Add(item, Cache.Get(item)));
return dict;
}
#endregion
/// <summary>
/// 删除所有缓存
/// </summary>
public void RemoveCacheAll()
{
var l = GetCacheKeys();
foreach (var s in l)
{
Remove(s);
}
}
/// <summary>
/// 删除匹配到的缓存
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
public void RemoveCacheRegex(string pattern)
{
IList<string> l = SearchCacheRegex(pattern);
foreach (var s in l)
{
Remove(s);
}
}
/// <summary>
/// 搜索 匹配到的缓存
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
public IList<string> SearchCacheRegex(string pattern)
{
var cacheKeys = GetCacheKeys();
var l = cacheKeys.Where(k => Regex.IsMatch(k, pattern)).ToList();
return l.AsReadOnly();
}
/// <summary>
/// 获取所有缓存键
/// </summary>
/// <returns></returns>
public List<string> GetCacheKeys()
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
var entries = Cache.GetType().GetField("_entries", flags).GetValue(Cache);
var cacheItems = entries as IDictionary;
var keys = new List<string>();
if (cacheItems == null) return keys;
foreach (DictionaryEntry cacheItem in cacheItems)
{
keys.Add(cacheItem.Key.ToString());
}
return keys;
}
}
}
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" /> <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="2.2.0" /> <PackageReference Include="Microsoft.Extensions.Options" Version="2.2.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" /> <PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Performance.Infrastructure;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
...@@ -9,69 +10,48 @@ ...@@ -9,69 +10,48 @@
namespace Performance.Services namespace Performance.Services
{ {
public class HubGroupInfo
{
public DateTime AddTime { get; set; }
public string ConnectionId { get; set; }
}
public class AllotLogHub : Hub public class AllotLogHub : Hub
{ {
private readonly ILogger<AllotLogHub> logger;
private readonly IMemoryCache cache; private readonly IMemoryCache cache;
private readonly ILogger<AllotLogHub> logger;
private readonly NotificationsService service;
public AllotLogHub( public AllotLogHub(
IMemoryCache cache,
ILogger<AllotLogHub> logger, ILogger<AllotLogHub> logger,
IMemoryCache cache) NotificationsService service
)
{ {
this.logger = logger;
this.cache = cache; this.cache = cache;
this.logger = logger;
this.service = service;
} }
private readonly MemoryCacheHelper helper = new MemoryCacheHelper();
public override Task OnConnectedAsync() public override Task OnConnectedAsync()
{ {
logger.LogDebug($"日志推送 连接{Context.ConnectionId}"); var task = base.OnConnectedAsync();
return base.OnConnectedAsync(); Clients.Caller.SendAsync("ReceiveMessage", Context.ConnectionId);
return task;
} }
public override Task OnDisconnectedAsync(Exception exception)
{
var connectionId = Context.ConnectionId;
logger.LogDebug($"日志推送 断开连接{connectionId}");
string key = $"AllotLogGroup_{connectionId}"; public override Task OnDisconnectedAsync(Exception exception)
//1 查询用户分组信息
var groupName = "";
//2 删除数据库中用户分组数据
if (cache.TryGetValue(key, out string value))
{ {
cache.Remove(key);
}
logger.LogDebug($"日志推送 断开连接{connectionId}-{groupName}");
//3 分组中删除用户
Groups.RemoveFromGroupAsync(connectionId, groupName);
return base.OnDisconnectedAsync(exception); return base.OnDisconnectedAsync(exception);
} }
public async Task AddGroup(string token, string groupName) public void LoginService(int userId)
{ {
var connectionId = Context.ConnectionId; //var dateTime = DateTime.Now;
string key = $"AllotLogGroup_{connectionId}"; //var slidingtimespan = helper.ToUnixTimestampBySeconds(dateTime.AddMinutes(30));
if (cache.TryGetValue(key, out string value)) //var absolutetimespan = helper.ToUnixTimestampBySeconds(dateTime.AddHours(2));
{ //helper.Set(userId.ToString(), Context.ConnectionId, slidingtimespan, absolutetimespan);
cache.Remove(key);
}
cache.Set(key, groupName, new TimeSpan(1, 0, 0));
logger.LogDebug($"日志推送 添加用户组{connectionId}-{groupName}");
//2 将用户插入分组
await Groups.AddToGroupAsync(connectionId, groupName);
} }
public async Task SendMessage(string groupName, string message) public void LogoutService(int userId)
{ {
await Clients.Group(groupName).SendAsync("ReceiveMessage", "测试", message); //if (helper.Exists(userId.ToString()))
// helper.Remove(userId.ToString());
} }
} }
} }
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace Performance.Services
{
public enum Classify
{
/// <summary>
/// 通知
/// </summary>
[Description("通知")]
Notification = 0,
/// <summary>
/// 进度条
/// </summary>
[Description("进度条")]
Progress = 1,
}
public enum NoticeType
{
/// <summary>
/// 成功
/// </summary>
[Description("成功")]
success = 0,
/// <summary>
/// 消息
/// </summary>
[Description("消息")]
info = 1,
/// <summary>
/// 警告
/// </summary>
[Description("警告")]
warning = 2,
/// <summary>
/// 错误
/// </summary>
[Description("错误")]
error = 3,
/// <summary>
/// 异常
/// </summary>
[Description("异常")]
exception = 4,
}
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.Services
{
public class MessageInfo
{
public MessageInfo(NoticeType typeValue)
{
TypeValue = typeValue;
}
/// <summary>
/// 分类
/// </summary>
public Classify Classify { get; set; } = Classify.Notification;
/// <summary>
/// 类型
/// </summary>
public string Type
{
get
{
return TypeValue.ToString();
}
}
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 消息
/// </summary>
public string Message { get; set; }
/// <summary>
/// 百分比
/// </summary>
public decimal Percentage { get; set; }
/// <summary>
/// 类型值
/// </summary>
[JsonIgnore]
public NoticeType TypeValue { get; set; }
}
}
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Performance.Infrastructure;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Performance.Services
{
public class NotificationsService : IAutoInjection
{
private readonly ILogger logger;
private readonly IHubContext<AllotLogHub> hubContext;
private readonly MemoryCacheHelper helper;
public NotificationsService(
ILogger<NotificationsService> logger,
IHubContext<AllotLogHub> hubContext,
MemoryCacheHelper helper
)
{
this.logger = logger;
this.hubContext = hubContext;
this.helper = helper;
}
public void SendMessage(int userId, MessageInfo data)
{
string key = userId.ToString();
if (helper.Exists(key) && helper.Get(key) is string connectionId && !string.IsNullOrEmpty(connectionId))
{
SendMessageToClient(connectionId, data);
}
}
private void SaveLogToDataBase()
{
}
private void SendMessageToClient(string connectionId, MessageInfo data, string method = "ReceiveMessage")
{
hubContext.Clients.Client(connectionId).SendAsync(method, data.Title, data);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment