Redis实战 - 1.String和计数器

在.NET Core 项目中操练String

使用 StackExchange.Redis 访问 Redis

		static void Main(string[] args)
        {
            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379"))
            {

                IDatabase db = redis.GetDatabase();
                db.StringSet("name", "Michal Jackson");
                string name = db.StringGet("name");
                Console.WriteLine(name); //结果:Michal Jackson

                db.StringSet("age", "11");
                //incr 自增
                db.StringIncrement("age");
                RedisValue age = db.StringGet("age");
                Console.WriteLine(age);//结果:12
                //incrby 指定增量
                age = db.StringIncrement("age", 5);
                Console.WriteLine(age);//结果:17
                //decr 自减
                age = db.StringDecrement("age");
                Console.WriteLine(age);//结果:16
                //decrby 指定减量
                age = db.StringDecrement("age", 5);
                Console.WriteLine(age);//结果:11

                //mset 设置多个值
                db.StringSet(new KeyValuePair<RedisKey, RedisValue>[]
                {
                    new KeyValuePair<RedisKey, RedisValue>("aa", "aa"),
                    new KeyValuePair<RedisKey, RedisValue>("bb", "bb"),
                    new KeyValuePair<RedisKey, RedisValue>("cc", "5"),
                });

                //mget 取多个值
                var values = db.StringGet(new RedisKey[] { "aa", "bb", "cc" });
                foreach (RedisValue redisValue in values)
                {
                    Console.Write(redisValue + ",");
                }
                //结果:aa,bb,5

                //exists 是否存在
                db.StringSet("name1", "Dave1");
                bool existsResult = db.KeyExists("name1");
                Console.WriteLine(existsResult); //结果:true

                //del 删除
                bool delResult = db.KeyDelete("name1");
                Console.WriteLine(delResult); //结果:true
                existsResult = db.KeyExists("name1");
                Console.WriteLine(existsResult); //结果:false

                //type 判断类型
                db.StringSet("name2", "Dave2");
                var typeOfValue = db.KeyType("name2");
                Console.WriteLine(typeOfValue); //String 
                
                //expire 过期时间
                db.StringSet("name3", "Dave3");
                db.KeyExpire("name3", TimeSpan.FromSeconds(5));
                RedisValue value = db.StringGet("name3"); 
                Console.WriteLine(value);       //Dave3
                Console.WriteLine("此处等待6秒...");
                Thread.Sleep(6 * 1000);
                value = db.StringGet("name3"); //啥也没有..
                Console.WriteLine(value);

                //ex 设置key直接设置有效期
                db.StringSet("name4","Dave4", TimeSpan.FromSeconds(5));
                RedisValue value4 = db.StringGet("name4"); 
                Console.WriteLine(value4);       //Dave4
                Console.WriteLine("此处等待6秒...");
                Thread.Sleep(6 * 1000);
                value4 = db.StringGet("name4"); //啥也没有..
                Console.WriteLine(value4);

                //ttl 查看过期时间
                db.StringSet("name6","Dave6", TimeSpan.FromSeconds(5));
                for (int i = 1; i < 7; i++)
                {
                     Thread.Sleep( 1000);
                    RedisValue valueTTL = db.StringGet("name6");
                   var ttl =  db.KeyTimeToLive("name6");
                    if (ttl==null)
                    {
                        Console.WriteLine($"{i}秒过后:Dave6已过期");
                    }
                    else
                    {
                        Console.WriteLine($"{i}秒过后:{valueTTL}还能存活{ttl}秒");
                    }
                    
                 }
                // 1秒过后:Dave6还能存活00:00:03.9970000秒
                // 2秒过后:Dave6还能存活00:00:02.9040000秒
                // 3秒过后:Daue6还能存活00:00:01.9040000秒
                // 4秒过后:Dave6还能存活00:00:00.9030000秒
                // 5秒过后:Dave6已过期
                // 6秒过后:Daue6已过期
            }

            Console.ReadKey();
        }

1.string值写到前台,取RedisValue

Startup.cs 注入 IConnectionMultiplexer

	services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect("localhost:6379"));

HomeController.cs

    public class HomeController : Controller
    {
        private readonly IConnectionMultiplexer _redis;
        private readonly IDatabase _db;

        public HomeController(IConnectionMultiplexer redis)
        {
            _redis = redis;
            _db = _redis.GetDatabase();
        }

        public IActionResult Index()
        {
            _db.StringSet("fullname", "Michael Jackson");
            var name = _db.StringGet("fullname");
            return View("Index", name);
        }
	}

视图 Index


@model StackExchange.Redis.RedisValue

<div class="text-center">
    <h1 class="display-4"> Welcome:@Model </h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

2.计数器

2.1 视图组件 ViewComponent

创建 CounterViewComponent 类

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using StackExchange.Redis;

namespace RedisToEsay.ViewComponents
{
    public class CounterViewComponent : ViewComponent
    {
        private readonly IDatabase _db;

        public CounterViewComponent(IConnectionMultiplexer redis)
        {
            _db = redis.GetDatabase();
        }

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

            throw new Exception("can't get pageId");
        }
    }
}

创建 Default 视图

@model string

<h4>@Model</h4>

然后在Shared_Layout.cshtml 调用

  <div>
        @await Component.InvokeAsync("Counter")
    </div>

报错:Defualt 创建的位置不对

An unhandled exception occurred while processing the request.
InvalidOperationException: The view 'Components/Counter/Default' was not found. The following locations were searched:
/Views/Home/Components/Counter/Default.cshtml
/Views/Shared/Components/Counter/Default.cshtml
/Pages/Shared/Components/Counter/Default.cshtml

所以创建的位置在 /Views/Shared/Components/Counter/Default.cshtml


参考:

草根专栏,Redis in .NET Core 入门:(2) String
杨旭(Video),Redis in ASP.NET Core 1. 计数器

posted @ 2019-02-28 21:42  【唐】三三  阅读(1557)  评论(0编辑  收藏  举报