在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#数据库操作 → Redis多线程 批量插入 性能测试 示例

Redis多线程 批量插入 性能测试 示例

C#数据库操作

下载此实例
  • 开发语言:C#
  • 实例大小:23.22M
  • 下载次数:120
  • 浏览次数:1181
  • 发布时间:2016-11-27
  • 实例类别:C#数据库操作
  • 发 布 人:crazycode
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 多线程 线程 测试 Redis

实例介绍

【实例简介】

【实例截图】


下为基础操作:


【核心代码】


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ServiceStack.Redis;
using ServiceStack.Redis.Generic;

namespace SSRedisDemo
{
    public partial class Form1 : Form
    {
        public static IRedisClientsManager clientsManager=null;
        public static IRedisClient redisClient=null;

        public Form1()
        {
            InitializeComponent();
            var count = this.tabControl1.TabCount;
            for (int i = 0; i < count; i  )
            {
                this.tabControl1.GetControl(i).Enabled = false;
            }
            this.tabControl1.GetControl(0).Enabled = true;
        }

        private void btnConn_Click(object sender, EventArgs e)
        {
            try
            {
                #region 集群访问方式

                var host = String.Format("{2}@{0}:{1}", this.txtHost.Text, this.txtPort.Text, this.txtPwd.Text);
                host = String.Format("{0}:{1}", this.txtHost.Text, this.txtPort.Text);//v3.0格式
                clientsManager = new PooledRedisClientManager(new string[] {host});
                redisClient = clientsManager.GetClient();

                #endregion

                #region 单个实例方式

                //redisClient = new RedisClient(this.txtHost.Text, Int32.Parse(this.txtPort.Text),this.txtPwd.Text);

                #endregion
            }
            catch(Exception ex)
            {
                MessageBox.Show("失败:" ex.Message);
                return;
            }
            MessageBox.Show("成功");

            var count = this.tabControl1.TabCount;
            for (int i = 0; i < count; i  )
            {
                this.tabControl1.GetControl(i).Enabled = true;
            }

        }

        private void btnSetString_Click(object sender, EventArgs e)
        {
            redisClient.Set(this.txtStringKey.Text, this.txtStringValue.Text);
        }

        private void btnGetString_Click(object sender, EventArgs e)
        {
            var strValue=redisClient.Get<string>(this.txtStringKey.Text);
            MessageBox.Show(strValue);
        }

        private void btnTransaction_Click(object sender, EventArgs e)
        {
            using (IRedisClient RClient = clientsManager.GetClient())
            {
                RClient.Add("key", 1);
                using (IRedisTransaction IRT = RClient.CreateTransaction())
                {
                    IRT.QueueCommand(r => r.Set("key", 20));
                    IRT.QueueCommand(r => r.Increment("key", 1));

                    IRT.Commit(); // 提交事务
                }
                MessageBox.Show(RClient.Get<string>("key"));
            }
        }

        private void btnAcquireLock_Click(object sender, EventArgs e)
        {
            using (IRedisClient RClient = clientsManager.GetClient())
            {
                RClient.Add("mykey", 1);
                // 支持IRedisTypedClient和IRedisClient
                using (RClient.AcquireLock("testlock"))
                {
                    //Response.Write("申请并发锁<br/>");
                    var counter = RClient.Get<int>("mykey");

                    Thread.Sleep(100);

                    RClient.Set("mykey", counter   1);
                    MessageBox.Show(RClient.Get<int>("mykey").ToString());
                }
            }
        }

        private void btnQueue_Click(object sender, EventArgs e)
        {
            redisClient.EnqueueItemOnList("operLog", "操作时间:"   DateTime.Now.ToString());
            MessageBox.Show("写入成功");
        }

        private void btnQueueRead_Click(object sender, EventArgs e)
        {
            string msg = redisClient.DequeueItemFromList("operLog");
            MessageBox.Show(msg);
        }

        /// <summary>
        /// DecrementValue	根据指定的Key,将值减1(仅整型有效)
        ///DecrementValueBy	根据指定的Key,将值减去指定值(仅整型有效)
        ///IncrementValue	根据指定的Key,将值加1(仅整型有效)
        ///IncrementValueBy	根据指定的Key,将值加上指定值(仅整型有效)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnIncStart_Click(object sender, EventArgs e)
        {
            var key = "incKey";
            var v = redisClient.IncrementValue(key);//将值加1(仅整型有效)
            redisClient.IncrementValueBy(key, 100);//将值加100
            MessageBox.Show("Success");
        }

        private void btnIncStop_Click(object sender, EventArgs e)
        {
            var key = "incKey";
            var v = redisClient.Get<long>(key);
            MessageBox.Show("当前值:" v.ToString());
        }

        private void btnTypedClient_Click(object sender, EventArgs e)
        {
            Person p1 = new Person() { Id = 1, Name = "刘备" };
            Person p2 = new Person() { Id = 2, Name = "关羽" };
            Person p3 = new Person() { Id = 3, Name = "张飞" };
            Person p4 = new Person() { Id = 4, Name = "曹操" };
            Person p5 = new Person() { Id = 5, Name = "典韦" };
            Person p6 = new Person() { Id = 6, Name = "郭嘉" };
            List<Person> ListPerson = new List<Person>() { p2, p3, p4, p5, p6 };

            using (IRedisClient RClient = clientsManager.GetClient())
            {
                IRedisTypedClient<Person> IRPerson = RClient.As<Person>();
                IRPerson.DeleteAll();

                //------------------------------------------添加--------------------------------------------

                //添加单条数据
                IRPerson.Store(p1);
                //添加多条数据
                IRPerson.StoreAll(ListPerson);

                //------------------------------------------查询--------------------------------------------

                //Linq支持
                MessageBox.Show("Id == 1 的Name:"   IRPerson.GetAll().Where(m => m.Id == 1).First().Name);       //刘备
                //注意,用IRedisTypedClient的对象IRPerson的Srore()添加的才能用IRPerson()方法读取
                MessageBox.Show("Id == 2 的Name:"   IRPerson.GetAll().First(m => m.Id == 2).Name);       //关羽

                //------------------------------------------删除--------------------------------------------

                IRPerson.Delete(p1);    //删除 刘备
                MessageBox.Show("删除刘备后总数:"   IRPerson.GetAll().Count());      //5
                IRPerson.DeleteById(2); //删除 关羽
                MessageBox.Show("删除关羽后总数:"   IRPerson.GetAll().Count());      //4
                IRPerson.DeleteByIds(new List<int> { 3, 4 });    //删除张飞 曹操
                MessageBox.Show("删除张飞曹操后总数:"   IRPerson.GetAll().Count());      //2
                IRPerson.DeleteAll();   //全部删除
                MessageBox.Show("全部删除后总数:"   IRPerson.GetAll().Count());      //0
            }
        }

        private void btnTestAddSetReplace_Click(object sender, EventArgs e)
        {
            using (IRedisClient RClient = clientsManager.GetClient())
            {
                RClient.Add("c1", "缓存1");
                RClient.Set("c1", "缓存2");
                RClient.Replace("c1", "缓存3");
                MessageBox.Show(RClient.Get<string>("c1"));
                RClient.Remove("c1");
                MessageBox.Show("移除状态:"   (RClient.Get<string>("c1") == null));
            }
        }

        private void btnList_T_Click(object sender, EventArgs e)
        {
            using (IRedisClient RClient = clientsManager.GetClient())
            {
                //内部维护一个List<T>集合
                RClient.AddItemToList("蜀国", "刘备");
                RClient.AddItemToList("蜀国", "关羽");
                RClient.AddItemToList("蜀国", "张飞");
                List<string> ListString = RClient.GetAllItemsFromList("蜀国");
                foreach (string str in ListString)
                {
                    MessageBox.Show(str); //输出 刘备 关羽 张飞
                }
            }

        }

        private void btnHash_T_Click(object sender, EventArgs e)
        {
            using (IRedisClient RClient = clientsManager.GetClient())
            {
                //Hash<T>
                RClient.AddItemToSet("魏国", "曹操");
                RClient.AddItemToSet("魏国", "曹操");
                RClient.AddItemToSet("魏国", "典韦");
                HashSet<string> HashSetString = RClient.GetAllItemsFromSet("魏国");
                foreach (string str in HashSetString)
                {
                    MessageBox.Show(str); //输出 典韦 曹操
                }
            }
        }

        private void btnList_Range_Click(object sender, EventArgs e)
        {
            using (IRedisClient RClient = clientsManager.GetClient())
            {
                //内部维护一个List<T>集合
                RClient.AddItemToSortedSet("蜀国1", "刘备", 5);
                RClient.AddItemToSortedSet("蜀国1", "关羽", 2);
                RClient.AddItemToSortedSet("蜀国1", "张飞", 3);
                IDictionary<String, double> DicString = RClient.GetRangeWithScoresFromSortedSet("蜀国1", 0, 2);
                foreach (var r in DicString)
                {
                    MessageBox.Show(r.Key   ":"   r.Value); //输出 关羽 张飞 刘备
                }
            }
        }

        private void btnHashTable_Click(object sender, EventArgs e)
        {
            using (IRedisClient RClient = clientsManager.GetClient())
            {
                RClient.SetEntryInHash("xxx", "key", "123");
                List<KeyValuePair<string, string>> keyValuePairs = new List<KeyValuePair<string, string>>();
                KeyValuePair<string, string> kvp = new KeyValuePair<string, string>("key", "1");
                keyValuePairs.Add(kvp);
                RClient.SetRangeInHash("xxx", keyValuePairs);
                MessageBox.Show(string.Join("\r\n", RClient.GetHashValues("xxx").ToArray()));
            }
        }

        private void btnSaveT_Click(object sender, EventArgs e)
        {
            var keyT = "tkey";
            redisClient.Set(keyT, new Person() { Id = 6, Name = "好例子" });
            var p = redisClient.Get<Person>(keyT);
            MessageBox.Show(p.Name);
        }

 

        private void btnBatchAdd_Click_1(object sender, EventArgs e)
        {
            var seed = DateTime.Now.ToString("yyyyMMddHHmmss");
            var count = 10000;
            Stopwatch watch = new Stopwatch();
            using (IRedisClient RClient = clientsManager.GetClient())
            {
                watch.Start();
                for (var i = 0; i < count; i  )
                {
                    RClient.Add(seed   ""   i.ToString(), "缓存"   i);
                }
                watch.Stop();


                MessageBox.Show("单线程插入"   count   "条数据,用时:"   watch.ElapsedMilliseconds "毫秒");

            }
        }

        private void btnBatchQueue_Click(object sender, EventArgs e)
        {

            var seed = DateTime.Now.ToString("yyyyMMddHHmmss");
            var count = 10000;
            Stopwatch watch = new Stopwatch();
            using (IRedisClient RClient = clientsManager.GetClient())
            {
                watch.Start();
                for (var i = 0; i < count; i  )
                {
                    redisClient.EnqueueItemOnList("testQueueLog","操作时间:"   i);
                }
                watch.Stop();


                MessageBox.Show("单线程插入"   count   "条数据,用时:"    watch.ElapsedMilliseconds   "毫秒");

            }

        }


        private void btnBatchAddMulitThread_Click(object sender, EventArgs e)
        {
            string message="";
            var count = int.Parse(this.txtDataCount.Text);// 10000;
            var threadCount = int.Parse(this.txtThreadCount.Text);// 20;
            int rand = new Random().Next(1, 10000);
            Stopwatch watchTotal = new Stopwatch();
            watchTotal.Start();
            var tasks = new Task[threadCount];
            for (int i = 0; i < tasks.Length; i  )
            {
                int taskIndex = i;
                tasks[i] = Task.Factory.StartNew(() =>
                {
                    rand = int.Parse(taskIndex.ToString());
                    var seed = DateTime.Now.ToString("yyyyMMddHHmmss")   "_"   rand;
                    Stopwatch watch = new Stopwatch();
                    using (IRedisClient RClient = clientsManager.GetClient())
                    {
                        watch.Start();
                        for (var j = 0; j < count; j  )
                        {
                            RClient.Add(seed   ""   j.ToString(), "缓存"   j);
                        }
                        watch.Stop();

                        message  = ("\r\n"   rand   "该线程插入"   count   "条数据,用时:"   watch.ElapsedMilliseconds   "毫秒");

                    }
                    
                }
               );
                
            }
            Task.WaitAll(tasks);

            watchTotal.Stop();
            //var startNew = Task<string>.Factory.StartNew((o) => ("holy "   o), "cow");
            //Console.WriteLine(startNew.Result);

            MessageBox.Show(threadCount   "个线程插入"   threadCount * count   "条数据,共用时:"   watchTotal.ElapsedMilliseconds   "毫秒"   ",平均用时:"   watchTotal.ElapsedMilliseconds/threadCount  "毫秒/万条"   message);


        }
    }

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}


实例下载地址

Redis多线程 批量插入 性能测试 示例

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

第 1 楼 Dman1990 发表于: 2017-05-04 14:53 54
看着不错

支持(0) 盖楼(回复)

发表评论

(您的评论需要经过审核才能显示)

查看所有1条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警