c#上Redis示例<一.写>

来源:互联网 发布:数据库管理系统有哪些 编辑:程序博客网 时间:2024/06/06 02:48

在c#中应用Redis示例,引用StackExchange.Redis.dll,在redis中实现存取。
建立客户类customer.cs

 public  class customer    {        private int id;        private string name;        private int age;        public int Id        {            set            {            this.id=value;            }            get            {                return id;            }        }        public string Name        {            set            {                this.name = value;            }            get            {                return name;            }        }        public int Age        {            set            {                this.age = value;            }            get            {                return age;            }        }    }

初始化redis连接:

 private ConnectionMultiplexer redis; private IDatabase db;            redis = ConnectionMultiplexer.Connect("127.0.0.1:6378");            db = redis.GetDatabase(1);

写redis数据库的方法:

public void AddTcalculationOneObj(customer obj)        {            string str = obj.GetType().Name + ":" + obj.Id.ToString();            Console.WriteLine("key:{0}", str);            FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);            Console.WriteLine("fis count:{0},{1}", fields.Length, fields.GetLength(0));            StackExchange.Redis.HashEntry[] hashFields = new StackExchange.Redis.HashEntry[fields.Length];            int index = 0;            foreach (FieldInfo info in fields)            {                Console.WriteLine("fi name:{0},value:{1}", info.Name, info.GetValue(obj).ToString());                hashFields[index] = new StackExchange.Redis.HashEntry(info.Name, info.GetValue(obj).ToString());                index++;            }            Console.WriteLine("init {0} start!", obj.GetType().Name);            this.db.HashSet(str, hashFields, CommandFlags.None);            Console.WriteLine("init {0} end!", obj.GetType().Name);            string key = obj.GetType().Name + ":keys";            RedisValue value2 = new RedisValue();            value2 = obj.Id.ToString();            this.db.ListRightPush(key, value2, When.Always, CommandFlags.None);        }

调用该方法:

List<customer> cs = new List<customer>();            customer cs1 = new customer();            cs1.Id = 1;            cs1.Name = "cf";            cs1.Age = 18;            cs.Add(cs1);            string key = "customer:keys";            while (this.db.ListLength(key, CommandFlags.None) > 0L)            {                this.db.ListLeftPop(key, CommandFlags.None);            }            for (int i = 0; i < cs.Count; i++)            {                this.AddTcalculationOneObj(cs[i]);            }

运行结果:
这里写图片描述
这里写图片描述

0 0