cache缓存如何实现同步更新?
每次数据insert,delete,update数据操作时,都要手动更新缓存太麻烦了
我是这样做的,比如有一个GetList用于获取数据,给它一个CacheKey,
然后在insert插入数据后,我手动调用一个方法来清除CacheKey,
这样GetList再次获取数据时,CacheKey已经不存在了..所以取到的最新数据
原理是很简单的吧. insert,delete,update 重新设置缓存不就好了!?
一般建议在增删改操作后面加个 notify 方法. 通知缓存更新
有没有更懒得策略
@chen_zhao_kun:
_repository.Update(item); //提醒更新事件 _eventPublisher.EntityUpdated<SystemCity>(item); //实现了自己的业务 public void HandleEvent(EntityUpdated<SystemCity> eventMessage) { _cacheManager.RemoveByPattern(ServicesRes.CityListCache); _cacheManager.RemoveByPattern(ServicesRes.CityListContainCache); }
这是我项目的做法.全部都是通过广播实现的.消费端就处理诸如清缓存等业务
没有最懒的做法.只有最好的封装;
@万雅虎: 源码分享下,可以吗
@万雅虎:看错了,我是想给你40分的,不好意思啊
@chen_zhao_kun: 代码很简单的只是一个实现原理
public interface IEventPublisher { /// <summary> /// Publish event /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="eventMessage">Event message</param> /// <param name="throwWhenInnerException"></param> void Publish<T>(T eventMessage, bool throwWhenInnerException = true); }
public class EventPublisher : IEventPublisher { private readonly ISubscriptionService _subscriptionService; /// <summary> /// Ctor /// </summary> /// <param name="subscriptionService"></param> public EventPublisher(ISubscriptionService subscriptionService) { _subscriptionService = subscriptionService; } /// <summary> /// Publish to cunsumer /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="x">Event consumer</param> /// <param name="eventMessage">Event message</param> /// <param name="throwWhenInnerException"></param> protected virtual void PublishToConsumer<T>(IConsumer<T> x, T eventMessage, bool throwWhenInnerException) { try { x.HandleEvent(eventMessage); } catch { if (throwWhenInnerException) { throw; } //todo: } } /// <summary> /// Publish event /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="eventMessage">Event message</param> /// <param name="throwWhenInnerException"></param> public virtual void Publish<T>(T eventMessage, bool throwWhenInnerException = true) { var subscriptions = _subscriptionService.GetSubscriptions<T>(); subscriptions.ToList().ForEach(x => PublishToConsumer(x, eventMessage, throwWhenInnerException)); } }
有时间可以研究下NOP . 这个地方我也是挖掘的NOP精髓~
@万雅虎: 好的,谢谢