Redis 专题
您的位置:database > Redis专题 > C#连接Redis
C#连接Redis
作者:--    发布时间:2019-11-20

前面我们已经准备成功开启redis服务,其端口号为6379,接下来我们就看看如何使用c#语言来操作redis。就如mongodb一样,要操作redis服务,自然就需要下载c#的客户端,这里通过nuget下载了“servicestack.redis”客户端,引入成功之后,就可以使用c#来对redis服务进行操作了。

由于redis一般是用来作为缓存的,也就是一般我们把一些不经常改变的数据通过redis缓存起来,之后用户的请求就不需要再访问数据库,而可以直接从redis缓存中直接获取,这样就可以减轻数据库服务器的压力以及加快响应速度。既然是用来做缓存的,也就是通过指定key值来把对应value保存起来,之后再根据key值来获得之前缓存的值。具体的操作代码如下所示,这里就不过多介绍了。

请参考以下代码 -

class program
    {
        static void main(string[] args)
        {
            //在redis中存储常用的5种数据类型:string,hash,list,setsorted set
            var client = new redisclient("127.0.0.1", 6379);
            //addstring(client);
            //addhash(client);
            //addlist(client);
            //addset(client);
            addsetsorted(client);

            console.readline();
        }

        private static void addstring(redisclient client)
        {
            var timeout = new timespan(0,0,0,30);
            client.add("test", "learninghard", timeout);
            while (true)
            {
                if (client.containskey("test"))
                {
                    console.writeline("string key: test -value: {0}, 当前时间: {1}", client.get<string>("test"), datetime.now);
                    thread.sleep(10000);
                }
                else
                {
                    console.writeline("value 已经过期了,当前时间:{0}", datetime.now);
                    break;
                }
            }

            var person = new person() {name = "learninghard", age = 26};
            client.add("lh", person);
            var cacheperson = client.get<person>("lh");
            console.writeline("person's name is : {0}, age: {1}", cacheperson.name, cacheperson.age);
        }

        private static void addhash(redisclient client)
        {
            if (client == null) throw new argumentnullexception("client");

            client.setentryinhash("hashid", "name", "learninghard");
            client.setentryinhash("hashid", "age", "26");
            client.setentryinhash("hashid", "sex", "男");

            var hashkeys = client.gethashkeys("hashid");
            foreach (var key in hashkeys)
            {
                console.writeline("hashid--key:{0}", key);
            }

            var haskvalues = client.gethashvalues("hashid");
            foreach (var value in haskvalues)
            {
                console.writeline("hashid--value:{0}", value);
            }

            var allkeys = client.getallkeys(); //获取所有的key。
            foreach (var key in allkeys)
            {
                console.writeline("allkey--key:{0}", key);
            }
        }

        private static void addlist(redisclient client)
        {
            if (client == null) throw new argumentnullexception("client");

            client.enqueueitemonlist("queuelistid", "1.learnghard");  //入队
            client.enqueueitemonlist("queuelistid", "2.张三");
            client.enqueueitemonlist("queuelistid", "3.李四");
            client.enqueueitemonlist("queuelistid", "4.王五");
            var queuecount = client.getlistcount("queuelistid");

            for (var i = 0; i < queuecount; i++)
            {
                console.writeline("queuelistid出队值:{0}", client.dequeueitemfromlist("queuelistid"));   //出队(队列先进先出)
            }

            client.pushitemtolist("stacklistid", "1.learninghard");  //入栈
            client.pushitemtolist("stacklistid", "2.张三");
            client.pushitemtolist("stacklistid", "3.李四");
            client.pushitemtolist("stacklistid", "4.王五");

            var stackcount = client.getlistcount("stacklistid");
            for (var i = 0; i < stackcount; i++)
            {
                console.writeline("stacklistid出栈值:{0}", client.popitemfromlist("stacklistid"));   //出栈(栈先进后出)
            }
        }

        //它是string类型的无序集合。set是通过hash table实现的,添加,删除和查找,对集合我们可以取并集,交集,差集
        private static void addset(redisclient client)
        {
            if (client == null) throw new argumentnullexception("client");

            client.additemtoset("set1001", "a");
            client.additemtoset("set1001", "b");
            client.additemtoset("set1001", "c");
            client.additemtoset("set1001", "d");
            var hastset1 = client.getallitemsfromset("set1001");
            foreach (var item in hastset1)
            {
                console.writeline("set无序集合value:{0}", item); //出来的结果是无须的
            }

            client.additemtoset("set1002", "k");
            client.additemtoset("set1002", "c");
            client.additemtoset("set1002", "a");
            client.additemtoset("set1002", "j");
            var hastset2 = client.getallitemsfromset("set1002");
            foreach (var item in hastset2)
            {
                console.writeline("set无序集合valueb:{0}", item); //出来的结果是无须的
            }

            var hashunion = client.getunionfromsets(new string[] { "set1001", "set1002" });
            foreach (var item in hashunion)
            {
                console.writeline("求set1001和set1002的并集:{0}", item); //并集
            }

            var hashg = client.getintersectfromsets(new string[] { "set1001", "set1002" });
            foreach (var item in hashg)
            {
                console.writeline("求set1001和set1002的交集:{0}", item);  //交集
            }

            var hashd = client.getdifferencesfromset("set1001", new string[] { "set1002" });  //[返回存在于第一个集合,但是不存在于其他集合的数据。差集]
            foreach (var item in hashd)
            {
                console.writeline("求set1001和set1002的差集:{0}", item);  //差集
            }

        }

        /*
        sorted set 是set的一个升级版本,它在set的基础上增加了一个顺序的属性,这一属性在添加修改.元素的时候可以指定,
        * 每次指定后,zset(表示有序集合)会自动重新按新的值调整顺序。可以理解为有列的表,一列存 value,一列存顺序。操作中key理解为zset的名字.
        */
        private static void addsetsorted(redisclient client)
        {
            if (client == null) throw new argumentnullexception("client");

            client.additemtosortedset("setsorted1001", "a");
            client.additemtosortedset("setsorted1001", "b");
            client.additemtosortedset("setsorted1001", "c");
            var listsetsorted = client.getallitemsfromsortedset("setsorted1001");
            foreach (var item in listsetsorted)
            {
                console.writeline("setsorted有序集合{0}", item);
            }

            client.additemtosortedset("setsorted1002", "a", 400);
            client.additemtosortedset("setsorted1002", "d", 200);
            client.additemtosortedset("setsorted1002", "b", 300);

            // 升序获取第一个值:"d"
            var list = client.getrangefromsortedset("setsorted1002", 0, 0);

            foreach (var item in list)
            {
                console.writeline(item);
            }

            //降序获取第一个值:"a"
            list = client.getrangefromsortedsetdesc("setsorted1002", 0, 0);

            foreach (var item in list)
            {
                console.writeline(item);
            }
        }
    }

    class person
    {
        public string name { get; set; }
        public int age { get; set; }
    }

如何要想查看自己操作是否成功,也可以像mongodb那样下载一个客户端工具,这里推荐一款redis desktop manager。这个工具就相当于sql server的客户端工具一样。通过这款工具可以查看redis服务器中保存的数据和对应格式。其使用也非常简单,只需要添加一个redis服务连接即可。该工具的下载地址为:http://pan.baidu.com/s/1sjp55ul


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册