一、建立一個數據表IPStat用於存放用戶信息
我在IPStat表中存放的用戶信息只包括登錄用戶的IP(IP_Address),IP來源(IP_Src)和登錄時間 (IP_DateTime),些表的信息本人只保存一天的信息,如果要統計每個月的信息則要保存一個月。因為我不太懂對數據日志的操作,所以創建此表。
二、在Global.asax中獲取用戶信息
在Global.asax的Session_Start即新會話啟用時獲取有關的信息,同時在這里實現在線人數、訪問總人數的增量統計,代碼如下:
void Session_Start(object sender, EventArgs e) { //獲取訪問者的IP string ipAddress = Request.ServerVariables["REMOTE_ADDR"]; //獲取訪問者的來源 string ipSrc; //判斷是否從搜索引擎導航過來的 if (Request.UrlReferrer == null) { ipSrc = ""; } else { //獲取來源地址 ipSrc = Request.UrlReferrer.ToString(); } //獲取訪問時間 DateTime ipDatetime = DateTime.Now; //保存IP信息到數據庫中 IPControl cont = new IPControl(); cont.AddIP(ipAddress, ipSrc, ipDatetime); //獲取用戶訪問的頁面 string pageurl = Request.Url.ToString(); //判斷訪問的是否是默認頁 if (pageurl.EndsWith("IPStat.aspx")) { //鎖定變量 Application.Lock(); //為頁面訪問量+1 Application["StatCount"] = int.Parse(Application["StatCount"].ToString()) + 1; //解鎖 Application.UnLock(); } //鎖定變量 Session.Timeout = 10; //設定超時為10分鍾 Application.Lock(); Application["countSession"] = Convert.ToInt32(Application["countSession"]) + 1; //訪問總人數+1 Application["onlineWhx"] = (int)Application["onlineWhx"] + 1; //在線人數加+1 Session["login_name"] = null; //解鎖 Application.UnLock(); }
提醒一句,別忘了下面的代碼,以實現在用戶離線時,將在線人數減去1.
void Session_End(object sender, EventArgs e) { // 在會話結束時運行的代碼。 // 注意: 只有在 Web.config 文件中的 sessionstate 模式設置為 InProc 時,才會引發 Session_End 事件。如果會話模式設置為 StateServer // 或 SQLServer,則不會引發該事件。 //鎖定變量 Application.Lock(); Application["onlineWhx"] = (int)Application["onlineWhx"] - 1; //在線人數減-1 Session["login_name"] = null; //解鎖 Application.UnLock(); }
三、將以上有關信息保存到數據庫IPStat
創建了一個獲取IP數據信息的類IPControl(),用來實現對數據庫IPStat數據的操作,關於IPControl()類的內容,因為它是C#中對數據庫的操作,以解Sql server 數據庫,就能看懂它,這里就不作介紹了,請點擊該鏈接查看。
為了實現將用戶IP信息存入數據庫,在上面代碼中對IPControl()進行調用
//保存IP信息到數據庫中 IPControl cont = new IPControl(); cont.AddIP(ipAddress, ipSrc, ipDatetime);
參數ipAddress為用戶IP,ipSrc為用戶來源, ipDatetime為用戶進入時間。
四、創建定時器,定時操作有關數據
對以上IPSta數據庫的數據,需要創建一個或者幾個定時器,並在每天晚上24時前的10秒鍾內統計一天的流量,然后將其刪除,把統計結果保存到另一個數據表中,供頁面顯示昨日訪問量是調用。定時器的創建和使用請點擊創建一個或者幾個定時器,供你參考。
以上不妥之處請批評指正。謝謝!
在ASP.net中網站訪問量統計方法—獲取IP數據信息的類
using System; using System.Data; using System.Data.SqlClient; using System.Text; /// /// 獲取IP數據信息的類 /// public class IPControl { //常量用來表示T-SQL語句中用到的變量名稱 private const string PARM_IP_ADDRESS = "@IPAddress"; private const string PARM_IP_SRC = "@IPSrc"; private const string PARM_IP_DATETIME = "@IPDateTime"; //T-SQL語句 private const string SQL_INSERT_IPSTAT = "INSERT INTO IPStat VALUES(@IPAddress,@IPSrc,@IPDateTime)"; private const string SQL_DELETE_IPSTAT = "delete from IPStat WHERE DATEDIFF(d,ip_datetime,getdate())>30"; //只保留一個月的數據 private const string SQL_SELECT_TOTAL = "SELECT COUNT(*) FROM IPStat "; private const string SQL_SELECT_TODAY = "SELECT COUNT(*) FROM IPStat WHERE DATEDIFF(d,ip_datetime,getdate())=0"; private const string SQL_SELECT_YESTERDAY = "SELECT COUNT(*) FROM IPStat WHERE DATEDIFF(d,ip_datetime,getdate())=1"; private const string SQL_SELECT_MONTH = "SELECT COUNT(*) FROM IPStat WHERE DATEDIFF(d,ip_datetime,getdate())<30 and DATEDIFF(mm,ip_datetime,getdate())=0"; public IPControl() { } /// /// 保存IP數據信息到數據庫 /// /// /// public void AddIP(string ipAddress,string ipSrc,DateTime ipDatetime) { //構建連接語句字符串 StringBuilder strSQL = new StringBuilder(); //創建表示QQ號的參數 SqlParameter[] parms = new SqlParameter[] { new SqlParameter(PARM_IP_ADDRESS, SqlDbType.NVarChar, 20), new SqlParameter(PARM_IP_SRC, SqlDbType.NVarChar,80), new SqlParameter(PARM_IP_DATETIME, SqlDbType.DateTime)}; SqlCommand cmd = new SqlCommand(); // 依次給參數賦值,並添加到執行語句中 parms[0].Value = ipAddress; parms[1].Value = ipSrc; parms[2].Value = ipDatetime; foreach(SqlParameter parm in parms) cmd.Parameters.Add(parm); //定義對象資源保存的范圍,一旦using范圍結束,將釋放對方所占的資源 using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringLocalTransaction)) { //在執行字符串中加載插入語句 strSQL.Append(SQL_INSERT_IPSTAT); conn.Open(); //設定SqlCommand的屬性 cmd.Connection = conn; cmd.CommandType = CommandType.Text; cmd.CommandText = strSQL.ToString(); //執行SqlCommand命令 cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); //如果執行成功,返回true,否則false。 } } public string GetTotal() { //調用SqlHelper訪問組件的方法返回第一行第一列的值 object count = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_TOTAL, null); //返回統計結果 return count.ToString(); } public string GetToday() { //調用SqlHelper訪問組件的方法返回第一行第一列的值 object count = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_TODAY, null); //返回統計結果 return count.ToString(); } public string GetYesterday() { //調用SqlHelper訪問組件的方法返回第一行第一列的值 object count = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_YESTERDAY, null); //返回統計結果 return count.ToString(); } public string GetMonth() { //調用SqlHelper訪問組件的方法返回第一行第一列的值 object count = SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, SQL_SELECT_MONTH, null); //返回統計結果 return count.ToString(); } }
在Global.asax中使用定時器來統計在線人數和每天每月的訪問量
一、在 Application_Start 中創建定時器
//以下為使用多個定時器System.Timers.Timer的處理方法 //用thread重新包一下,定義兩個定時器 System.Threading.Thread myTimer_1 = new System.Threading.Thread(new System.Threading.ThreadStart(write_1)); myTimer_1.Start(); System.Threading.Thread myTimer_2 = new System.Threading.Thread(new System.Threading.ThreadStart(write_2)); myTimer_2.Start();
二、使用定時器每10分鍾更新一次在線人數檢查一次是否要存入一天流量的信息
//使用第一個定時器,每10分鍾更新一次在線人數 private void write_1() { //以下使用System.Timers.Timer類 每間隔10分鍾存一次數據 System.Timers.Timer myTimer1 = new System.Timers.Timer(600000); //實例化Timer類,設置間隔時間為600000毫秒(10分鍾存一次總人數); myTimer1.Enabled = true; //是否執行System.Timers.Timer.Elapsed事件; myTimer1.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed); //到達時間的時候執行事件myTimer_Elapsed; myTimer1.AutoReset = true; //設置是執行一次(false)還是一直執行(true); } //使用第二個定時器, private void write_2() { //以下使用System.Timers.Timer類 每間隔10分鍾檢查一次是否要存入一天流量的信息 System.Timers.Timer myTimer2 = new System.Timers.Timer(600000); //實例化Timer類,設置間隔時間為600000毫秒(10分鍾存一次總人數); myTimer2.Enabled = true; //是否執行System.Timers.Timer.Elapsed事件; myTimer2.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_peopleDay); //到達時間的時候執行事件myTimer_peopleDay; myTimer2.AutoReset = true; //設置是執行一次(false)還是一直執行(true); }
三、創建 myTimer過程來處理在線人數和統計每日、月、年的流量
//創建 myTimer_Elapsed 過程並定義第一個定時器事件,要用來處理在線人數的代碼 private void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { //如果現在的在現人數大於原有的在現人數,則替換數據表中的在現人數 int MaxOnline = Convert.ToInt32(Application["OnlineMax"]); int MinOnline = Convert.ToInt32(Application["OnlineWhx"]); if (MaxOnline < MinOnline) { SqlConnection con = Db.DB.createconnection(); con.Open(); SqlCommand cmd = new SqlCommand("update countpeople set totol='" + Application["countSession"].ToString() + "',OnLine=+'" + Application["onlineWhx"] + "',DataTimes='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'", con); cmd.ExecuteNonQuery(); con.Close(); Application["OnlineMax"] = Application["OnlineWhx"]; //將現在線人數賦於OnlineMax Application["dataTimes"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } else { //將總訪問人數寫入數據庫 SqlConnection con = Db.DB.createconnection(); con.Open(); SqlCommand cmd = new SqlCommand("update countpeople set totol=" + Application["countSession"].ToString(), con); cmd.ExecuteNonQuery(); con.Close(); } } //創建 myTimer_peopleDay 過程並定義第二個定時器事件,要用來統計每日、月、年的流量 private void myTimer_peopleDay(object sender, System.Timers.ElapsedEventArgs e) { try { //當天晚上24時 if (DateTime.Now.Hour == 23) { if (DateTime.Now.Minute >= 50) { //當天晚上24時,寫入一天的流量 //初始化一個iP數據訪問對象 IPControl cont = new IPControl(); //獲取今天訪問量 Int32 countToday = Convert.ToInt32(cont.GetToday()); //獲取本月訪問量 Int32 countMonth = Convert.ToInt32(cont.GetMonth()); //存儲過程名sp_InsertCountPeopleDay SqlConnection con1 = Db.DB.createconnection(); con1.Open(); SqlCommand cmd1 = new SqlCommand("sp_InsertCountPeopleDay", con1); cmd1.CommandType = CommandType.StoredProcedure; //存儲過程名 //調用並設置存儲過程參數 cmd1.Parameters.Add(new SqlParameter("@peopleDay", SqlDbType.Int)); cmd1.Parameters.Add(new SqlParameter("@dateTimes", SqlDbType.DateTime)); //給參數賦值 cmd1.Parameters["@peopleDay"].Value = countToday; cmd1.Parameters["@dateTimes"].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); cmd1.ExecuteNonQuery(); con1.Close(); //在一個月的最后一天寫入本月的訪問量 //取本月最后一天(30或者31日) DateTime lastDay = Convert.ToDateTime(DateTime.Now.AddMonths(1).ToString("yyyy-MM-01")).AddDays(-1); int lastDay1 = DateTime.Now.Day; //取當前時間的日期 if (lastDay1.ToString() == lastDay.ToString()) //如果前日期等於本月最后一天的日期,則前本月的流量寫入數據庫 { SqlConnection conM = Db.DB.createconnection(); conM.Open(); SqlCommand cmdM = new SqlCommand("sp_InsertCountPeopleMonth", conM); cmdM.CommandType = CommandType.StoredProcedure; //存儲過程名 //調用並設置存儲過程參數 cmdM.Parameters.Add(new SqlParameter("@peopleMonth", SqlDbType.Int)); cmdM.Parameters.Add(new SqlParameter("@dateTimeMonth", SqlDbType.DateTime)); //給參數賦值 cmdM.Parameters["@peopleMonth"].Value = countMonth; cmdM.Parameters["@dateTimeMonth"].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); cmdM.ExecuteNonQuery(); conM.Close(); } } } } catch { } }