public TEntity CacheRead<TEntity>(string cacheKey) where TEntity : class { var cacheEntity = HttpRuntime.Cache.Get(cacheKey) as TEntity; return cacheEntity; }
1 2 3 4 5 6 7 8 9 10 11
publicvoid CacheWrite<TEntity>(string cacheKey, TEntity cacheEntity) where TEntity : class { HttpRuntime.Cache.Add( cacheKey, cacheEntity, null, DateTime.Now.AddDays(1), Cache.NoSlidingExpiration, CacheItemPriority.High, null); }
讀寫Cache中的訊息
結合剛剛提到的訊息類別,就可以簡單的使用Cache做訊息的讀寫了。
1 2 3 4
public List<ChatsResponseModel> Read() { var chats = CacheRead<List<ChatsResponseModel>>(this.CacheKey) ?? new List<ChatsResponseModel>(); return chats; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public ChatsResponseModel Write(MessageRequestModel model, string userId, bool sce = false) { var chats = this.Read() ?? new List<ChatsResponseModel>(); var newChat = new ChatsResponseModel() { Id = Guid.NewGuid().ToString(), Message = model.Message, User = ApplicationDbContext.Users.FirstOrDefault(s => s.Id == userId).UserName, Create = DateTime.Now.ToString("H:mm:ss"), Sce = sce }; chats.Add(newChat); CacheWrite(this.CacheKey, chats); return newChat; }
publicvoidSlackPostMessage(string message, string name) { var pureMsg = SanitizeHtml(message); if (!string.IsNullOrEmpty(pureMsg)) { var url = $"https://slack.com/api/chat.postMessage?token={this.token}&channel={this.channel}&text={pureMsg}&username={name}"; var client = new RestClient(url); var request = new RestRequest(Method.GET); client.ExecuteTaskAsync(request); } }