.netCore 使用分布式缓存(docker+redis)
电脑版发表于:2019/12/22 16:45
1. 通过docker创建 Redis
执行命令:
docker run --name asp-redis -p 6379:6379 -d redis
查看redis状态:
docker ps
可以发现 already working
2. 创建项目 DistributedRedisDemo
我们可以看到这里有建好的迁移,我们只需要修改一下 appsetting.json 的连接字符串
添加好我们需要的模型,且在ApplicationDbContext.cs添加好DBset
执行命令:
Update-Database
3. 添加 redis 分布式依赖库
Microsoft.Extensions.Caching.Redis
//依赖注入分布式redis服务 //依赖注入分布式redis服务 services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect("localhost")); services.AddDistributedRedisCache(option => { option.Configuration = "localhost"; //实例名称 option.InstanceName = "RedisDemoInstance"; });
HomeController.cs
private readonly IConnectionMultiplexer _redis; private readonly IDistributedCache _distributedCache; private readonly IDatabase _db; public HomeController(IConnectionMultiplexer redis,IDistributedCache distributedCache) { //分布式缓存使用方式 _distributedCache = distributedCache; //非分布式缓存使用方式 _redis = redis; _db = _redis.GetDatabase(); } public IActionResult Index() { var value = _distributedCache.Get("name-key"); //当name没有值 if (value == null) { //值 var obj = new Dictionary<string, string> { ["FirstName"] = "Nick", ["LastName"] = "Carter" }; //json序列化 var str = JsonConvert.SerializeObject(obj); //编码 byte[] encoded = Encoding.UTF8.GetBytes(str); //缓存实例化 var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(30)); _distributedCache.Set("name-key", encoded, options); return View("Index", obj); } else { var str = Encoding.UTF8.GetString(value); var obj = JsonConvert.DeserializeObject<Dictionary<string, string>>(str); return View("Index",obj); } }
Index.cshtml
@model Dictionary<string, string> @{ ViewData["Title"] = "Home Page"; } <div class="text-center"> <h1 class="display-4">Welcome:</h1> @foreach (var kv in Model) { <h3> @kv.Key : @kv.Value </h3> } </div>
Result:
Than:
Than 30秒后: