/// <summary> /// 依据EntityId获取单个实体 /// </summary> /// <remarks> /// 自动对实体进行缓存(除非实体配置为不允许缓存) /// </remarks> /// <param name="entityId">实体Id</param> public virtual TEntity Get(object entityId) { TEntity entity = null; if (RealTimeCacheHelper.EnableCache) { entity = cacheService.Get <TEntity>(RealTimeCacheHelper.GetCacheKeyOfEntity(entityId)); } if (entity == null) { entity = CreateDAO().SingleOrDefault <TEntity>(entityId); #region 处理缓存 if (RealTimeCacheHelper.EnableCache && entity != null) { if (RealTimeCacheHelper.PropertyNameOfBody != null) { //启用实体正文缓存时,不在实体缓存中存储实体正文 RealTimeCacheHelper.PropertyNameOfBody.SetValue(entity, null, null); } cacheService.Add(RealTimeCacheHelper.GetCacheKeyOfEntity(entity.EntityId), entity, RealTimeCacheHelper.CachingExpirationType); } #endregion } if (entity == null || entity.IsDeletedInDatabase) { return(null); } return(entity); }
public override int Delete(MicroblogEntity entity) { int affect = base.Delete(entity); if (affect > 0) { Sql sql = Sql.Builder; sql.Append("update spb_Microblogs set ForwardedCount = ForwardedCount - 1 where MicroblogId = @0 and ForwardedCount > 0", entity.ForwardedMicroblogId); if (CreateDAO().Execute(sql) > 0) { string cacheKey = RealTimeCacheHelper.GetCacheKeyOfEntity(entity.ForwardedMicroblogId); MicroblogEntity microblogEntity = cacheService.Get <MicroblogEntity>(cacheKey); if (microblogEntity != null) { if (microblogEntity.ForwardedCount > 0) { microblogEntity.ForwardedCount--; } cacheService.Set(cacheKey, microblogEntity, CachingExpirationType.SingleObject); } } } return(affect); }
/// <summary> /// 创建ContentItem /// </summary> /// <param name="contentItem"></param> /// <returns></returns> public override object Insert(ContentItem contentItem) { base.Insert(contentItem); ContentTypeDefinition contentType = contentItem.ContentType; if (contentType != null) { List <Sql> sqls = new List <Sql>(); StringBuilder sqlBuilder = new StringBuilder(); List <object> values = new List <object>(); sqlBuilder.AppendFormat("INSERT INTO {0} (", contentType.TableName); int columnIndex = 0; sqlBuilder.Append(contentType.ForeignKey); values.Add(contentItem.ContentItemId); foreach (var column in contentType.Columns) { if (contentType.ForeignKey == column.ColumnName) { continue; } if (contentItem.AdditionalProperties.Keys.Contains(column.ColumnName)) { columnIndex++; sqlBuilder.Append("," + column.ColumnName); if (contentItem.AdditionalProperties[column.ColumnName] == null) { values.Add(column.DefaultValue); } else { values.Add(contentItem.AdditionalProperties[column.ColumnName]); } } else { sqlBuilder.Append("," + column.ColumnName); values.Add(column.DefaultValue); } } sqlBuilder.Append(")"); sqls.Add(Sql.Builder.Append(sqlBuilder.Append("values (@0)").ToString(), values)); sqls.Add(Sql.Builder.Append("UPDATE spb_cms_ContentFolders SET ContentItemCount=ContentItemCount+1 WHERE ContentFolderId=@0", contentItem.ContentFolderId)); CreateDAO().Execute(sqls); } string cacheKey = "ContentItemAP:" + RealTimeCacheHelper.GetCacheKeyOfEntity(contentItem.ContentItemId); cacheService.Remove(cacheKey); return(contentItem.ContentItemId); }
/// <summary> /// 批量关注积分处理 /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> void BatchFollowPointModule_After(int sender, BatchFollowEventArgs eventArgs) { if (EventOperationType.Instance().Create() == eventArgs.EventOperationType && sender > 0) { string pointItemKey = string.Empty; pointItemKey = PointItemKeys.Instance().FollowUser(); PointService pointService = new PointService(); for (int i = 0; i < sender; i++) { pointService.GenerateByRole(eventArgs.UserId, pointItemKey, "批量添加关注"); } //更新用户缓存 ICacheService cacheService = DIContainer.Resolve <ICacheService>(); RealTimeCacheHelper realTimeCacheHelper = EntityData.ForType(typeof(User)).RealTimeCacheHelper; if (cacheService.EnableDistributedCache) { realTimeCacheHelper.IncreaseEntityCacheVersion(eventArgs.UserId); } else { string cacheKey = realTimeCacheHelper.GetCacheKeyOfEntity(eventArgs.UserId); User user = cacheService.Get <User>(cacheKey); if (user != null) { user.FollowedCount = user.FollowedCount + sender; } } } }
public override object Insert(MicroblogEntity entity) { object oId = base.Insert(entity); long id = 0; long.TryParse(oId.ToString(), out id); if (id > 0) { Sql sql = Sql.Builder; int affect = CreateDAO().Execute(sql.Append("update spb_Microblogs set ForwardedCount = ForwardedCount + 1 where MicroblogId = @0", entity.ForwardedMicroblogId)); if (affect > 0) { string cacheKey = RealTimeCacheHelper.GetCacheKeyOfEntity(entity.ForwardedMicroblogId); MicroblogEntity microblogEntity = cacheService.Get <MicroblogEntity>(cacheKey); if (microblogEntity != null) { microblogEntity.ForwardedCount++; cacheService.Set(cacheKey, microblogEntity, CachingExpirationType.SingleObject); } } } return(oId); }
/// <summary> /// 取消关注后更新缓存 /// </summary> /// <param name="sender">关注实体</param> /// <param name="eventArgs">事件参数</param> void CancelFollowEventModule_After(FollowEntity sender, CommonEventArgs eventArgs) { if (eventArgs.EventOperationType == EventOperationType.Instance().Delete()) { CategoryService service = new CategoryService(); service.ClearCategoriesFromItem(sender.Id, sender.UserId, TenantTypeIds.Instance().User()); //更新用户缓存 ICacheService cacheService = DIContainer.Resolve <ICacheService>(); RealTimeCacheHelper realTimeCacheHelper = EntityData.ForType(typeof(User)).RealTimeCacheHelper; if (cacheService.EnableDistributedCache) { realTimeCacheHelper.IncreaseEntityCacheVersion(sender.UserId); } else { string cacheKey = realTimeCacheHelper.GetCacheKeyOfEntity(sender.UserId); User user = cacheService.Get <User>(cacheKey); if (user != null && user.FollowedCount > 0) { user.FollowedCount--; } } } }
/// <summary> /// 创建回复贴 /// </summary> /// <param name="post">回复贴</param> public bool Create(BarPost post) { BarSectionService barSectionService = new BarSectionService(); BarSection barSection = barSectionService.Get(post.SectionId); if (barSection == null) { return(false); } EventBus <BarPost> .Instance().OnBefore(post, new CommonEventArgs(EventOperationType.Instance().Create())); //设置审核状态 auditService.ChangeAuditStatusForCreate(post.UserId, post); long id = 0; long.TryParse(barPostRepository.Insert(post).ToString(), out id); if (id > 0) { new AttachmentService(TenantTypeIds.Instance().BarPost()).ToggleTemporaryAttachments(post.UserId, TenantTypeIds.Instance().BarPost(), id); //计数 CountService countService = new CountService(TenantTypeIds.Instance().BarSection()); countService.ChangeCount(CountTypes.Instance().ThreadAndPostCount(), barSection.SectionId, barSection.UserId, 1, true); if (post.TenantTypeId == TenantTypeIds.Instance().Group()) { //群组内容计数+1 OwnerDataService groupOwnerDataService = new OwnerDataService(TenantTypeIds.Instance().Group()); groupOwnerDataService.Change(post.SectionId, OwnerDataKeys.Instance().PostCount(), 1); } else if (post.TenantTypeId == TenantTypeIds.Instance().Bar()) { //用户内容计数+1 OwnerDataService ownerDataService = new OwnerDataService(TenantTypeIds.Instance().User()); ownerDataService.Change(post.UserId, OwnerDataKeys.Instance().PostCount(), 1); } //更新帖子主题计数缓存 RealTimeCacheHelper realTimeCacheHelper = EntityData.ForType(typeof(BarThread)).RealTimeCacheHelper; string cacheKey = realTimeCacheHelper.GetCacheKeyOfEntity(post.ThreadId); ICacheService cacheService = DIContainer.Resolve <ICacheService>(); BarThread barThread = cacheService.Get <BarThread>(cacheKey); if (barThread != null && barThread.ThreadId > 0) { barThread.PostCount++; cacheService.Set(cacheKey, barThread, CachingExpirationType.SingleObject); } new AtUserService(TenantTypeIds.Instance().BarPost()).ResolveBodyForEdit(post.GetBody(), post.UserId, post.PostId); EventBus <BarPost> .Instance().OnAfter(post, new CommonEventArgs(EventOperationType.Instance().Create())); EventBus <BarPost, AuditEventArgs> .Instance().OnAfter(post, new AuditEventArgs(null, post.AuditStatus)); } return(id > 0); }
/// <summary> /// 依据EntityId集合组装成实体集合(自动缓存) /// </summary> /// <param name="entityIds">主键集合</param> public virtual IEnumerable <TEntity> PopulateEntitiesByEntityIds <T>(IEnumerable <T> entityIds) { TEntity[] entityArray = new TEntity[entityIds.Count()]; Dictionary <object, int> entityId2ArrayIndex = new Dictionary <object, int>(); for (int i = 0; i < entityIds.Count(); i++) { TEntity entity = cacheService.Get <TEntity>(RealTimeCacheHelper.GetCacheKeyOfEntity(entityIds.ElementAt(i))); if (entity != null) { entityArray[i] = entity; } else { entityArray[i] = null; entityId2ArrayIndex[entityIds.ElementAt(i)] = i; } } //缓存中取不到的实体集中从数据库获取 if (entityId2ArrayIndex.Count > 0) { IEnumerable <TEntity> entitiesFromDatabase = CreateDAO().FetchByPrimaryKeys <TEntity>(entityId2ArrayIndex.Keys); foreach (var entityFromDatabase in entitiesFromDatabase) { entityArray[entityId2ArrayIndex[entityFromDatabase.EntityId]] = entityFromDatabase; #region 处理缓存 if (RealTimeCacheHelper.EnableCache && entityFromDatabase != null) { if (RealTimeCacheHelper.PropertyNameOfBody != null) { if (RealTimeCacheHelper.PropertyNameOfBody != null) { //启用实体正文缓存时,不在实体缓存中存储实体正文 RealTimeCacheHelper.PropertyNameOfBody.SetValue(entityFromDatabase, null, null); } } cacheService.Set(RealTimeCacheHelper.GetCacheKeyOfEntity(entityFromDatabase.EntityId), entityFromDatabase, RealTimeCacheHelper.CachingExpirationType); } #endregion } } List <TEntity> entities = new List <TEntity>(); foreach (var entity in entityArray) { if (entity != null && !entity.IsDeletedInDatabase) { entities.Add(entity); } } return(entities); }
/// <summary> /// 数据库删除实体后自动调用该方法 /// </summary> /// <param name="entity"></param> protected virtual void OnDeleted(TEntity entity) { #region 处理缓存 if (RealTimeCacheHelper.EnableCache) { //递增实体缓存版本 RealTimeCacheHelper.IncreaseEntityCacheVersion(entity.EntityId); //更新列表缓存版本 RealTimeCacheHelper.IncreaseListCacheVersion(entity); cacheService.MarkDeletion(RealTimeCacheHelper.GetCacheKeyOfEntity(entity.EntityId), entity, CachingExpirationType.SingleObject); } #endregion }
/// <summary> /// 更新敏感词 /// </summary> /// <param name="sensitiveWord"></param> /// <returns></returns> public int Update(SensitiveWord sensitiveWord) { int id = CreateDAO().ExecuteScalar <int>(Sql.Builder.Append("select Id from tn_SensitiveWords where Word = @0", sensitiveWord.Word)); RealTimeCacheHelper.IncreaseEntityCacheVersion(sensitiveWord.Id); cacheService.Remove(RealTimeCacheHelper.GetCacheKeyOfEntity(sensitiveWord.Id)); if (id > 0 && id != sensitiveWord.Id) { return(-1); } base.Update(sensitiveWord); return(sensitiveWord.Id); }
/// <summary> /// 获取ContentItem附表数据 /// </summary> /// <param name="contentTypeId"></param> /// <param name="contentItemId"></param> /// <returns></returns> public IDictionary <string, object> GetContentItemAdditionalProperties(int contentTypeId, long contentItemId) { string cacheKey = "ContentItemAP:" + RealTimeCacheHelper.GetCacheKeyOfEntity(contentItemId); IDictionary <string, object> additionalProperties = cacheService.Get <IDictionary <string, object> >(cacheKey); if (additionalProperties == null) { ContentTypeDefinition contentType = new MetadataService().GetContentType(contentTypeId); if (contentType != null) { additionalProperties = new Dictionary <string, object>(); Database database = CreateDAO(); database.OpenSharedConnection(); try { using (var cmd = database.CreateCommand(database.Connection, string.Format("SELECT * FROM {0} WHERE {1} = @0", contentType.TableName, contentType.ForeignKey), contentItemId)) { using (IDataReader dr = cmd.ExecuteReader()) { if (dr.Read()) { foreach (var column in contentType.Columns) { if (dr[column.ColumnName] == null) { additionalProperties.Add(column.ColumnName, column.DefaultValue); } else { additionalProperties.Add(column.ColumnName, dr[column.ColumnName]); } } } dr.Close(); } } } finally { database.CloseSharedConnection(); } cacheService.Add(cacheKey, additionalProperties, CachingExpirationType.SingleObject); } } return(additionalProperties); }
/// <summary> /// 获取下一篇 /// </summary> /// <param name="blogThread">当前日志</param> /// <returns>下一篇日志id</returns> public long GetNextThreadId(BlogThread blogThread) { string cacheKey = RealTimeCacheHelper.GetCacheKeyOfEntity(blogThread.ThreadId) + "-NextThreadId"; long? nextThreadId = cacheService.Get(cacheKey) as long?; if (!nextThreadId.HasValue) { nextThreadId = 0; var sql = Sql.Builder.Select("ThreadId").From("spb_BlogThreads"); var whereSql = Sql.Builder.Where("ThreadId > @0", blogThread.ThreadId) .Where("TenantTypeId = @0", blogThread.TenantTypeId) .Where("OwnerId = @0", blogThread.OwnerId) .Where("PrivacyStatus<>@0", PrivacyStatus.Private) .Where("spb_BlogThreads.IsDraft=0"); switch (this.PubliclyAuditStatus) { case PubliclyAuditStatus.Again: case PubliclyAuditStatus.Fail: case PubliclyAuditStatus.Pending: case PubliclyAuditStatus.Success: whereSql.Where("AuditStatus=@0", this.PubliclyAuditStatus); break; case PubliclyAuditStatus.Again_GreaterThanOrEqual: case PubliclyAuditStatus.Pending_GreaterThanOrEqual: whereSql.Where("AuditStatus>@0", this.PubliclyAuditStatus); break; default: break; } var orderSql = Sql.Builder.OrderBy("ThreadId ASC"); sql.Append(whereSql).Append(orderSql); var ids_object = CreateDAO().FetchTopPrimaryKeys <BlogThread>(1, sql); if (ids_object.Count() > 0) { nextThreadId = ids_object.Cast <long>().First(); } cacheService.Add(cacheKey, nextThreadId, CachingExpirationType.SingleObject); } return(nextThreadId.Value); }
/// <summary> /// 删除ContentItem /// </summary> /// <param name="contentItem"></param> /// <returns></returns> public override int Delete(ContentItem contentItem) { ContentTypeDefinition contentType = contentItem.ContentType; if (contentType != null) { List <Sql> sqls = new List <Sql>(); sqls.Add(Sql.Builder.Append(string.Format("DELETE FROM {0} WHERE {1}=@0", contentType.TableName, contentType.ForeignKey), contentItem.ContentItemId)); sqls.Add(Sql.Builder.Append("UPDATE spb_cms_ContentFolders SET ContentItemCount=ContentItemCount-1 WHERE ContentFolderId=@0", contentItem.ContentFolderId)); CreateDAO().Execute(sqls); } string cacheKey = "ContentItemAP:" + RealTimeCacheHelper.GetCacheKeyOfEntity(contentItem.ContentItemId); cacheService.Remove(cacheKey); return(base.Delete(contentItem)); }
/// <summary> /// 更新ContentItem /// </summary> /// <param name="contentItem"></param> public override void Update(ContentItem contentItem) { ContentTypeDefinition contentType = contentItem.ContentType; if (contentType != null) { StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.AppendFormat("UPDATE {0} SET ", contentType.TableName); List <object> values = new List <object>(); int columnIndex = 0; foreach (var column in contentType.Columns) { if (column.EnableEdit) { sqlBuilder.AppendFormat(" {0}=@{1},", column.ColumnName, columnIndex); values.Add(contentItem.AdditionalProperties[column.ColumnName]); columnIndex++; } } //去除末尾"," sqlBuilder.Remove(sqlBuilder.Length - 1, 1); sqlBuilder.AppendFormat(" WHERE {0}=@{1}", contentType.ForeignKey, columnIndex); values.Add(contentItem.ContentItemId); Sql sql = Sql.Builder.Append(sqlBuilder.ToString(), values.ToArray()); CreateDAO().Execute(sql); } string cacheKey = "ContentItemAP:" + RealTimeCacheHelper.GetCacheKeyOfEntity(contentItem.ContentItemId); cacheService.Remove(cacheKey); base.Update(contentItem); //更新解析正文缓存 cacheKey = GetCacheKeyOfResolvedBody(contentItem.ContentItemId); string resolveBody = cacheService.Get <string>(cacheKey); if (resolveBody != null) { resolveBody = contentItem.AdditionalProperties.Get <string>("Body", string.Empty); resolveBody = DIContainer.ResolveNamed <IBodyProcessor>(TenantTypeIds.Instance().ContentItem()).Process(resolveBody, TenantTypeIds.Instance().ContentItem(), contentItem.ContentItemId, contentItem.UserId); cacheService.Set(cacheKey, resolveBody, CachingExpirationType.SingleObject); } }
/// <summary> /// 数据库新增实体后自动调用该方法 /// </summary> protected virtual void OnInserted(TEntity entity) { #region 处理缓存 if (RealTimeCacheHelper.EnableCache) { //更新列表缓存版本 RealTimeCacheHelper.IncreaseListCacheVersion(entity); if (RealTimeCacheHelper.PropertyNameOfBody != null) { string body = RealTimeCacheHelper.PropertyNameOfBody.GetValue(entity, null) as string; cacheService.Add(RealTimeCacheHelper.GetCacheKeyOfEntityBody(entity.EntityId), body, RealTimeCacheHelper.CachingExpirationType); //启用实体正文缓存时,不在实体缓存中存储实体正文 RealTimeCacheHelper.PropertyNameOfBody.SetValue(entity, null, null); } cacheService.Add(RealTimeCacheHelper.GetCacheKeyOfEntity(entity.EntityId), entity, RealTimeCacheHelper.CachingExpirationType); } #endregion }
/// <summary> /// 相册隐私状态更改,同步更改相册下隐私状态 /// </summary> /// <param name="albumId"></param> public void UpdatePrivacyStatus(long albumId) { var dao = CreateDAO(); dao.OpenSharedConnection(); Album album = new PhotoService().GetAlbum(albumId); if (album != null) { Sql sql = Sql.Builder .Append("update spb_Photos set PrivacyStatus = @0 where spb_Photos.AlbumId = @1", album.PrivacyStatus, albumId); dao.Execute(sql); } Sql sql_Select = Sql.Builder .Select("PhotoId") .From("spb_Photos"); IEnumerable <object> photoIds = dao.FetchTopPrimaryKeys <Photo>(int.MaxValue, sql_Select); dao.CloseSharedConnection(); foreach (var item in photoIds) { long id = 0; if (long.TryParse(item.ToString(), out id)) { RealTimeCacheHelper.IncreaseEntityCacheVersion(id); //处理掉本机缓存 string cacheKeyOfEntity = RealTimeCacheHelper.GetCacheKeyOfEntity(id); Photo photo = cacheService.Get <Photo>(cacheKeyOfEntity); if (photo != null) { photo.IsEssential = true; } } } }
/// <summary> /// 关注后更新缓存 /// </summary> /// <param name="sender">关注实体</param> /// <param name="eventArgs">事件参数</param> void FollowUpdateCountModule_After(FollowEntity sender, CommonEventArgs eventArgs) { if (eventArgs.EventOperationType == EventOperationType.Instance().Create()) { //更新用户缓存 ICacheService cacheService = DIContainer.Resolve <ICacheService>(); RealTimeCacheHelper realTimeCacheHelper = EntityData.ForType(typeof(User)).RealTimeCacheHelper; if (cacheService.EnableDistributedCache) { realTimeCacheHelper.IncreaseEntityCacheVersion(sender.UserId); } else { string cacheKey = realTimeCacheHelper.GetCacheKeyOfEntity(sender.UserId); User user = cacheService.Get <User>(cacheKey); if (user != null) { user.FollowedCount++; } } } }