接口压力测试控制台程序

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace TestApi
{
    class Program
    {
        public static List<Result> results = new List<Result>();

        static void Main(string[] args)
        {
            //运行次数
            var runCount = 10;
            //线程数
            var threadCount = 50;
            //输出文本
            FileStream fileStream = new FileStream("./TestDetail.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter streamWriter = new StreamWriter(fileStream);
            TextWriter writer = Console.Out;
            Console.SetOut(streamWriter);

            Console.WriteLine("================开启线程处理================");
            List<ManualResetEvent> list = new List<ManualResetEvent>();
            for (int i = 0; i < threadCount; i++)
            {
                ////测试登录
                //ManualResetEvent mreCheck = new ManualResetEvent(false);
                //System.Threading.Thread threadCheckUser = new Thread((o) =>
                //{
                //    string sUrl = "http://127.0.0.1:2923/ICBuring/VerifyUserIsCanLogin";
                //    string sJson = (new JavaScriptSerializer()).Serialize(new { userName = "opts", passWord = "123456" });
                //    StartRequest(runCount, System.Threading.Thread.CurrentThread.ManagedThreadId, sUrl, sJson);
                //    ((ManualResetEvent)o).Set();
                //});
                //list.Add(mreCheck);
                //threadCheckUser.Start(mreCheck);

                //测试查表
                ManualResetEvent mreEvent = new ManualResetEvent(false);
                System.Threading.Thread threadTableInfo = new Thread((o) =>
                {
                    string sUrl = "http://127.0.0.1:2923/ICBuring/GetTableInfo";
                    string sJson = (new JavaScriptSerializer()).Serialize(new
                    {
                        userName = "opts",
                        passWord = "123456",
                        querySql = "SELECT FULLNAME FROM EMPLOYEE WHERE EMPLOYEENAME='opts'"
                    });
                    StartRequest(runCount, System.Threading.Thread.CurrentThread.ManagedThreadId, sUrl, sJson);
                    ((ManualResetEvent)o).Set();
                });
                list.Add(mreEvent);
                threadTableInfo.Start(mreEvent);

                ////测试调用服务修改数据
                //ManualResetEvent mreOrder = new ManualResetEvent(false);
                //System.Threading.Thread threadOrder = new Thread((o) =>
                //{
                //    string sUrl = "http://127.0.0.1:2923/ICBuring/UpdateTaskQty";
                //    string sJson = (new JavaScriptSerializer()).Serialize(new
                //    {
                //        userName = "opts",
                //        passWord = "123456",
                //        taskCode = "6248290",
                //        qty = "200"
                //    });
                //    StartRequest(runCount, System.Threading.Thread.CurrentThread.ManagedThreadId, sUrl, sJson);
                //    ((ManualResetEvent)o).Set();
                //});
                //list.Add(mreOrder);
                //threadOrder.Start(mreOrder);
            }
            WaitHandle.WaitAll(list.ToArray());
            OutPutResult();
            Console.WriteLine("===========所有线程完成任务!===============");
            //输出文本
            Console.SetOut(writer);
            streamWriter.Close();
            fileStream.Close();
            //读取文本到控制台
            System.IO.StreamReader sr = new System.IO.StreamReader("D:\\TestDetail.txt");
            string content = sr.ReadToEnd();
            foreach (string s in content.Split('\n'))
            Console.WriteLine(s);
            sr.Close();

            Console.WriteLine("执行完成,执行信息保存路径:D://TestDetail.txt,请按任意键关闭!" );

            Console.ReadLine();


        }

        /// <summary>
        /// 操作请求
        /// </summary>
        /// <param name="connectionCount"></param>
        /// <param name="threadId"></param>
        /// <param name="sUrl"></param>
        /// <param name="sJson"></param>
        public static void StartRequest(int connectionCount, int threadId,string sUrl,string sJson)
        {
            int iSuccess = 0;
            int iFailed = 0;
            DateTime beforDT = System.DateTime.Now;
            for (var i = 0; i < connectionCount; i++)
            {
                try
                {
                    Post(sUrl, sJson);
                    iSuccess++;
                }
                catch (Exception ex)
                {
                    iFailed++;
                }
            }
            DateTime afterDT = System.DateTime.Now;
            TimeSpan ts = afterDT.Subtract(beforDT);
            results.Add(new Result() { ThreadID=threadId,Url=sUrl,SuccessCount=iSuccess,FailedCount=iFailed,TotalTime= ts.TotalMilliseconds / 1000 });
        }

        /// <summary>
        /// 打印信息
        /// </summary>
        public static void OutPutResult()
        {
            foreach (Result result in results.OrderBy(o=>o.Url))
            {
                Console.WriteLine( result.Url + ",线程:" + result.ThreadID + "," + "成功数:" + result.SuccessCount.ToString() 
                                + ",失败数:" + result.FailedCount.ToString() + ",总共花费" + result.TotalTime + "秒");
            }
        }

        /// <summary>
        /// Post方式调用接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string Post(string url, string json)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpContent content = new StringContent(json);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                HttpResponseMessage response = client.PostAsync(url, content).Result;
                HttpStatusCode status = response.EnsureSuccessStatusCode().StatusCode;
                string rt = response.Content.ReadAsStringAsync().Result;
                if (!(status == HttpStatusCode.OK))
                {
                    throw new Exception("HttpError:Stauts:" + Convert.ToInt16(status).ToString() + " Msg:" + rt);
                }
                return rt.ToString();
            }
        }

        /// <summary>
        /// 输出信息
        /// </summary>
        public class Result
        {
            /// <summary>
            /// 线程ID
            /// </summary>
            public int ThreadID { get; set; }
            /// <summary>
            /// 请求地址
            /// </summary>
            public string Url { get; set; }
            /// <summary>
            /// 成功次数
            /// </summary>
            public int SuccessCount { get; set; }
            /// <summary>
            /// 失败次数
            /// </summary>
            public int FailedCount { get; set; }
            /// <summary>
            /// 用时
            /// </summary>
            public double TotalTime { get; set; }
        }
    }
}

  

上一篇:MD5计算,一个扩展类,哪里都能用


下一篇:Java面向对象---多态