MemCache内存数据库使用示例
1、创建一个Web项目:
需要引入三个程序集文件
2、分为三步:
(1)打开内存数据库连接
(2)往内存数据库中存入数据(读取内存数据库中的数据)
(3)关闭内存数据库
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Memcached.ClientLibrary; using System.Text; namespace WebMemcachedDemo { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { MemHelper.SetServer(); //AddDatas(); GetDatas(); MemHelper.CloseMemcacheConnection(); } } public void AddDatas() { string utilonline = "test"; MemcachedClient mc = new MemcachedClient(); mc.EnableCompression = true; try { StringBuilder sb = new StringBuilder(); sb.Append("<table width='100%'>"); for (int i = 0; i < 10; i++) { if(i%2==0) sb.Append("<tr style='background:lightgray;'>"); else sb.Append("<tr style='background:greenyellow;'>"); for (int j = 0; j < 5; j++) { sb.Append("<td>"); sb.Append((i+j).ToString()); sb.Append("</td>"); } sb.Append("</tr>"); } sb.Append("</table>"); string result = sb.ToString(); mc.Set(utilonline, result);//保存到实时数据库 } catch (Exception ex) { Console.WriteLine(ex.Message + "---" + ex.InnerException); } } public void GetDatas() { string utilonline = "test"; MemcachedClient mc = new MemcachedClient(); mc.EnableCompression = true; string result = ""; if (mc.KeyExists(utilonline)) { result = mc.Get(utilonline).ToString(); } this.Literal1.Text = result; } } public class MemHelper { /// <summary> /// 打开链接 /// </summary> public static void SetServer() { try { string[] server = { "127.0.0.1:11211" }; SockIOPool pool = SockIOPool.GetInstance(); pool.SetServers(server); pool.InitConnections = 3; pool.MinConnections = 3; pool.MaxConnections = 50; pool.SocketConnectTimeout = 1000; pool.SocketTimeout = 3000; pool.MaintenanceSleep = 30; pool.Failover = true; pool.Nagle = false; pool.Initialize(); } catch (Exception ex) { Console.WriteLine(ex.Message + "---" + ex.InnerException); } } /// <summary> /// 关闭连接 /// </summary> public static void CloseMemcacheConnection() { SockIOPool.GetInstance().Shutdown(); } } }View Code
3、对于一些大量的数据不必每次都从数据库中读取,只需要存放到内存中就可以了,下次读取,只从内存中读取就可以了,减少时间
4、效果图
优质内容筛选与推荐>>