天天看点

.netcore 2.1 缓存 MemoryCache 使用,MVC、控制台MVC版控制台版本:

MVC版

1:Startup类

public void ConfigureServices(IServiceCollection services)

{

    。。。忽略

    services.AddMemoryCache();//启用内存缓存

}

2:Controller调用

IMemoryCache _memoryCache;

public MyCacheController(IMemoryCache memoryCache)

{

    _memoryCache = memoryCache;

}

public void MySize()

{

CancellationTokenSource tokenSource = new CancellationTokenSource();

var cacheOptions = new MemoryCacheEntryOptions()

{

    //5s过期,被动过期,需要下一次被调用的时候,触发‘RegisterPostEvictionCallback’

    AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(5)

};

//过期触发的回调方法,大家可以调试查看key/value/reason/obj

cacheOptions.RegisterPostEvictionCallback((key, value, reason, obj) =>

{

    Console.WriteLine(reason);

});

    //添加主动过期回调

    cacheOptions.AddExpirationToken(new CancellationChangeToken(tokenSource.Token));

    _memoryCache.Set("key", "value", cacheOptions);

    //2秒后主动过期,2秒后主动调用RegisterPostEvictionCallback方法

    tokenSource.CancelAfter(1000 * 2);

}

控制台版本:

static void Main(string[] args)

{

    //cache的最大限制是:100

    MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()

{

});

CancellationTokenSource tokenSource = new CancellationTokenSource();

var cacheOptions = new MemoryCacheEntryOptions()

{

    AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10)  //10s过期

};

cacheOptions.RegisterPostEvictionCallback((key, value, reason, obj) =>

{

    Console.WriteLine(reason);

});

cacheOptions.AddExpirationToken(new CancellationChangeToken(tokenSource.Token));

memoryCache.Set("key", "value", cacheOptions);

//System.Threading.Thread.Sleep(2000);

tokenSource.CancelAfter(1000 * 2);

Console.Read();

}

继续阅读