C# 中 Redis 的简单使用

准备 一个 redis 文件 

在redis 所在目录运行  

redis-server.exe redis.windows.conf

出现这个就说明 redis 服务启动了 ,这个界面不能关闭


新建一个控制台 :目标框架选新一点 ,不然安装不上插件

NUGET 安装  :ServiceStack.Redis.Core

接着写代码就可以了:复制可以直接用

using System;
using System.Collections.Generic;
using ServiceStack.Redis;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            //登录成功记录用户到redis
            var people = new People { age = 18, name = "qal", acount="qazwsxedc" ,token = Guid.NewGuid().ToString()  };
            using (RedisClient client = new RedisClient("127.0.0.1", 6379))
            {   
                client.SetEntryInHash(people.token, "age", people.age.ToString());
                client.SetEntryInHash(people.token, "name", people.name.ToString());
                client.SetEntryInHash(people.token, "acount", people.acount.ToString());
                //给对象设置超时时间 设置12个小时后过期
                client.Expire(people.token, 3600 * 12); 
            }

            // 每次获取资源先验证token是否存在 
            using (RedisClient client = new RedisClient("127.0.0.1", 6379))
            {
                if (client.Exists(people.token)>0)
                {
                    Dictionary<string, string> prople = client.GetAllEntriesFromHash(people.token);
                    foreach (var item in prople)
                    {
                        Console.WriteLine($"键:{item.Key},值:{item.Value}");
                    }
                }
            }
            Console.ReadKey();
        }
    }
}


 

猜你喜欢

转载自blog.csdn.net/qq_36445227/article/details/108197415