ASP.NET Core使用Redis

安装Redis

 https://www.runoob.com/redis/redis-install.html

Nuget包中下载StackExchange.Redis

 

StackExchange.Redis文档地址

 https://stackexchange.github.io/StackExchange.Redis

 注:如果如法访问修改下自己电脑的DNS为114.114.114.114,或百度github.io无法访问如何解决

 添加连接redis字符串

 注入服务

 调用

 视图中使用StackExchange.Redis.RedisValue类型接收数据

计数器应用 

 创建ViewComponent

 创建CountViewComponent.cs

    public class CounterViewComponent : ViewComponent
    {
        private readonly IDatabase _db;
        public CounterViewComponent(ConnectionMultiplexer reids)
        {
            //访问redis数据库
            _db = reids.GetDatabase();
        }

        public async Task<IViewComponentResult> InvokeAsync()
        {
            var controller = RouteData.Values["controller"] as string;
            var action= RouteData.Values["action"] as string;
            if (!string.IsNullOrWhiteSpace(controller) && !string.IsNullOrWhiteSpace(action)) {
                var pageId = $"{controller}-{action}";
                //自增
                await _db.StringIncrementAsync(pageId);
                var count = await _db.StringGetAsync(pageId);
                return View("Default", pageId + ":" + count);
            }
            return View("Default", "0");
        }
    }

创建Default.cshtml

 _Layout.cshtml中调用

 展示效果

原文地址:https://www.cnblogs.com/-zzc/p/14459639.html