C#缓存二

介绍
经过 《C# 缓存》 和《C#使用redis》作为缓存,我们可以了解C#中简单使用缓存的原理和代码。
使用缓存,可以降低操作数据库频率进而提升性能。在使用缓存过程中,我们会遇到一个问题,就是做数据库操作的时候,当我们对数据库进行了改动,即进行增加删除更新操作的时候,我们如何处理缓存数据?1.改变改变数据库时改变缓存,2.改变数据库时情况缓存。我推荐后者,因为,第一种方案,是对两个数据源进行操作,这会牵扯到事务等等,提高了复杂性,而第二种,只有当我操作数据库成功时,才会去清空缓存数据。

原理
在上述两篇文章中,我们发现,不管是内存缓存,还是redis缓存,均可对缓存起一个别称,即Name字段。
既然,我们可以对缓存起别名,也就是说,我们可以针对一个实体,或者说一个存储模型,根据类名或者其他的唯一命名方式,对这个实体的查询操作,建立缓存,在进行 增加 更新 删除操作的时候,情况这个别名的缓存信息。

代码实现
1.实体基类和具体的实体

public class Entity
{
public Guid Id { get; set; }

    public void GenerateId()
    {
        this.Id=Guid.NewGuid();
    }
}

public class DemoCacheEntity:Entity
{
public int RandomValue { get; set; }
}

新建提示仓储接口和实现

public interface IRepository<TEntity>
    where TEntity:Entity
{
    void Add(TEntity entity);

    void Update(TEntity entity);

    void Remove(TEntity entity);

    TEntity Get(Guid id);   
}

public class Repository<TEntity>
    :IRepository<TEntity>
    where TEntity : Entity
{
    /// <summary>
    ///     保存 entities 的地方
    /// </summary>
    private static IList<TEntity> entities=
        new List<TEntity>();

    private readonly ICache _cache;

    public Repository(ICache cache)
    {
        this._cache = cache;
    }

    public void Add(TEntity entity)
    {
        if (entity.Id == Guid.Empty)
        {
            entity.GenerateId();
        }
        entities.Add(entity);
        this._cache.Clear();

    }

    public void Update(TEntity entity)
    {
        var toUpdate = entities.FirstOrDefault();
        toUpdate = entity;
        this._cache.Clear();
    }

    public void Remove(TEntity entity)
    {
        var toDelete = entities.FirstOrDefault();
        entities.Remove(toDelete);
        this._cache.Clear();
    }

    public TEntity Get(Guid id)
    {
        var key = id.ToString();
        return (TEntity)this._cache.Get(key,
            (k) => this.GetFromList(id));   
    }

    private TEntity GetFromList(Guid id)
    {
        var entity = entities.FirstOrDefault(c => c.Id == id);
        Console.WriteLine("如果显示了这条信息,表示从list中取数,而非缓存中取数据");
        return entity;
    }
}

通过仓储的实现,我们可以发现,在通过构造函数,传入 缓存,在 add update delete 方法中,对缓存进行清空处理,get方法是默认的缓存处理手段, 接下来,看democacheentity的具体仓储实现方式

public class DemoEntityRepository
Repository, IRepository
{
    private static ICache DemoEntityCacheInstance = new DemoCache("ENTITYCACHE-DEMOCACHEENTITY");

    public DemoEntityRepository()
        :base(DemoEntityCacheInstance)
    {
        // 每个实体对应的 cache name 应该是唯一的
    }
}

具体的仓储实现方式就比较简单了,就是建立仓储实例的时候,传入一个唯一的缓存实现。
到此,我们就可以通过 管理名称为"ENTITYCACHE-DEMOCACHEENTITY"来管理实体为DemoCacheEnttiy的缓存。

使用
1.插入时的使用方式

Console.WriteLine("----------------------测试 Add Start----------------------");
IRepository repository=
new DemoEntityRepository();

        var testId = Guid.NewGuid();

        var entity=new DemoCacheEntity()
                       {
            Id = testId,
                           RandomValue = GetRandomValue()
        };
        repository.Add(entity);

        DemoCacheEntity getEntity = repository.Get(testId);
        Console.Write("第一次取值   ");
        ShowEntityCacheItem(getEntity);

        Stopwatch watch = new Stopwatch();
        watch.Start();

        while (true)
        {
            if (watch.ElapsedMilliseconds < 10000)
            {
                continue;
            }

            getEntity = repository.Get(testId);
            Console.Write("10s后取值    ");
            ShowEntityCacheItem(getEntity);
            break;
        }

        while (true)
        {
            if (watch.ElapsedMilliseconds < 40000)
            {
                continue;
            }
            getEntity = repository.Get(testId);
            Console.Write("40s后取值    ");
            ShowEntityCacheItem(getEntity);
            break;
        }

        while (true)
        {
            if (watch.ElapsedMilliseconds < 70000)
            {
                continue;
            }
            getEntity = repository.Get(testId);
            Console.Write("70s后取值  此处应该还是entity的值 ");
            ShowEntityCacheItem(getEntity);
            break;
        }

        watch.Stop();
        Console.WriteLine("----------------------测试 Add End----------------------");

插入运行结果

图片.png

通过运行结果,我们不难发现,70s之后,即缓存到期,数据是再次从列表中过去

2.更新实体属性

Console.WriteLine("----------------------测试 Update Start----------------------");

        IRepository<DemoCacheEntity> repository =
            new DemoEntityRepository();


        DemoCacheEntity getEntity = repository.Get(testId);
        Console.Write("第一次需要update的信息,此处应该是缓存信息,没有打印从list取值信息  ");
        ShowEntityCacheItem(getEntity);

        getEntity.RandomValue = GetRandomValue();
        repository.Update(getEntity);

        getEntity = repository.Get(testId);
        Console.Write("第一次需要update的信息,此处应该是list信息,打印从list取值信息  ");
        ShowEntityCacheItem(getEntity);

        Stopwatch watch = new Stopwatch();
        watch.Start();

        while (true)
        {
            if (watch.ElapsedMilliseconds < 10000)
            {
                continue;
            }

            getEntity = repository.Get(testId);
            Console.Write("10s后取值    ");
            ShowEntityCacheItem(getEntity);
            break;
        }

        while (true)
        {
            if (watch.ElapsedMilliseconds < 40000)
            {
                continue;
            }
            getEntity = repository.Get(testId);
            Console.Write("40s后取值    ");
            ShowEntityCacheItem(getEntity);
            break;
        }

        while (true)
        {
            if (watch.ElapsedMilliseconds < 70000)
            {
                continue;
            }
            getEntity = repository.Get(testId);
            Console.Write("70s后取值  此处应该还是entity的值 ");
            ShowEntityCacheItem(getEntity);
            break;
        }

        watch.Stop();
        Console.WriteLine("----------------------测试 Update End----------------------");

更新实体,运行结果

图片.png

从运行结果可以看出,当我们更新实体后,是在次重list中获取数据,而非从缓存中获取数据

删除实体
Console.WriteLine("----------------------测试 Delete Start----------------------");
IRepository repository =
new DemoEntityRepository();
DemoCacheEntity getEntity = repository.Get(testId);
Console.Write("第一次需要Delete的信息,此处应该是缓存信息,没有打印从list取值信息 ");
ShowEntityCacheItem(getEntity);
repository.Remove(getEntity);
Stopwatch watch = new Stopwatch();
watch.Start();

        while (true)
        {
            if (watch.ElapsedMilliseconds < 10000)
            {
                continue;
            }

            try
            {
                getEntity = repository.Get(testId);
                if (getEntity == null)
                {
                    Console.WriteLine("从数据库中删除了");
                    break;
                }
                
            }
            catch (Exception ex)
            {
                Console.WriteLine("从数据库中删除了");
                break;
            }
        }
        watch.Stop();
        Console.WriteLine("----------------------测试 Delete End----------------------");

删除操作运行结果

图片.png

根据运行结果,我们可以看出,当我们删除实体后,再次尝试读取数据时,会提示已经删除,也不会从list中读取数据。

总结
根据以上结果,我们可以得出一个结论,就是我们可以通过管理唯一命名的缓存来管理实体缓存,不需要去更新缓存数据。
作为缓存,就两个操作,要么生效,要么失效,我们可以在取数据的时候,让缓存生效,在改动数据库的时候,让缓存失效,即可达到当数据库数据发生改变的时候,我们的缓存数据,得到的永远是数据库值(直接修改数据库不会清空缓存)。
扩展1:这里是在仓储中操作了缓存,仓储依赖了缓存,是个不好的做法,可以借助领域事件来完成情况缓存的操作,而且,缓存不应该是在仓储中使用,合理的使用,应该是在应用层和仓储之间,建立缓存体系。
扩展2:这里建立缓存,是通过唯一指定的名称建立缓存组件,其实,我们可以不指定唯一名称,而是根据提示的type,获取到名称,来建立对应的缓存组件。

作者:诸葛_小亮
链接:https://www.jianshu.com/p/f807446c394c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值