Files
IM_NEW/FileService.Infrastructure/Storage/StorageCacheService.cs
T

66 lines
2.2 KiB
C#

using FileService.Application.Ports;
using FileService.Application.StorageContracts;
using IM.Commons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileService.Infrastructure.Storage
{
public class StorageCacheService:IStorageRedisCache
{
private readonly IRedisService redis;
public StorageCacheService(IRedisService redis)
{
this.redis = redis;
}
public async Task SetAsync(UploadRuntimeCache upload)
{
string key = RedisHelper.GetUploadInfoKey(upload.UploadSessionId);
// 过期时间取 UploadRuntimeCache 的 ExpireAt 字段,兜底默认 24 小时
var ttl = upload.ExpireAt > upload.CreatedAt
? upload.ExpireAt - upload.CreatedAt
: TimeSpan.FromHours(24);
await redis.SetAsync<UploadRuntimeCache>(key, upload, ttl);
// 维护 taskId → sessionId 映射,用于 DeleteByTaskId 快速定位
var mapKey = RedisHelper.GetUploadTaskSessionMapKey(upload.TaskId);
await redis.SetAsync(mapKey, upload.UploadSessionId, ttl);
}
public async Task DeleteAsync(string sessionId)
{
string key = RedisHelper.GetUploadInfoKey(sessionId);
// 先取出缓存以清理映射 key
var cache = await redis.GetAsync<UploadRuntimeCache>(key);
if (cache != null)
{
var mapKey = RedisHelper.GetUploadTaskSessionMapKey(cache.TaskId);
await redis.RemoveAsync(mapKey);
}
await redis.RemoveAsync(key);
}
public async Task DeleteByTaskIdAsync(string taskId)
{
var mapKey = RedisHelper.GetUploadTaskSessionMapKey(taskId);
var sessionId = await redis.GetAsync<string>(mapKey);
if (sessionId != null)
{
await DeleteAsync(sessionId);
}
}
public async Task<UploadRuntimeCache?> GetAsync(string sessionId)
{
var key = RedisHelper.GetUploadInfoKey(sessionId);
return await redis.GetAsync<UploadRuntimeCache>(key);
}
}
}