Memcached ----关于存取的小例子

   ITOO底层封装的memcached的方法存取的时候有一定的时间耗费。它的工作原理是:存的时候先把对象序列化成字符串,取的时候再把字符串反序列化为对象使用!其实memcached缓存有一个客户端,可以提供对memcached的存取,并且各种类型的都可以,所以我就提供给大家一个小例子,希望对初学memcached的学者有帮助!


首先

要做一些前提工作:引用dll。
    Memcached ----关于存取的小例子_第1张图片      

     引用了这4个DLL,我们就可以非常简单的用memcached的客户端来操作了!

其次:

写一个memcachedHelper类,用来连接多台机器存放数据库,搭建memcached分布式的环境!
     
using Memcached.ClientLibrary;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace test
{
    class MemcacheHelper
    {
        public MemcacheHelper()
        {
           //跟配置文件相连,使之可以连接多个服务器
            string server = ConfigurationManager.AppSettings["serverlist"];
            string[] serverlist;
            serverlist = server.Split(',');

            SockIOPool pool = SockIOPool.GetInstance();
            pool.SetServers(serverlist);
            pool.MinConnections = 3;
            pool.InitConnections = 3;
            pool.MaxConnections = 5;
            pool.SocketConnectTimeout = 5000;
            pool.Initialize();
        }
    }
}


配置配置文件,使之可以灵活填写数据库连接的电脑个数:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="serverlist" value="127.0.0.1:11211,192.168.21.88:11211"></add>
  </appSettings>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>



最后

建立一个窗体,放上8个按钮外加一个txt文本框
接下来是后台的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Memcached.ClientLibrary;
using System.Collections;
 
namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
          //实例化一个helper类,链接数据库池
            MemcacheHelper memchachehelper = new MemcacheHelper();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            //实例化一个客户端,用于操作memcached数据库
            MemcachedClient client = new MemcachedClient();
 
            client.EnableCompression = false;
 
            client.Set("key1", "字符串测试");
 
            MessageBox.Show("key1:字符串测试");
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            MemcachedClient client = new MemcachedClient();
           //取出数据的值,将内容显示到界面的文本框中
            txt01.Text = client.Get("key1").ToString();
        }
 
        private void button3_Click(object sender, EventArgs e)
        {
          //实例化一个对象
            Person person = new Person { UserId = "1", UserName = "李少然" };
            MemcachedClient client = new MemcachedClient();
            client.EnableCompression = false;
           //向数据库中存入对象
            client.Set("key2", person);
            MessageBox.Show("key2:对象PersonUserId = 1, UserName =李少然");
        }
 
        private void button4_Click(object sender, EventArgs e)
        {
            MemcachedClient client = new MemcachedClient();
            //从缓存中取出对象
            Person cc = client.Get("key2") as Person;
           //将对象的内容显示到文本框中
            txt01.Text = cc.UserId.ToString() + ";" + cc.UserName.ToString();
        }
       //存入泛型
        private void button5_Click(object sender, EventArgs e)
        {
            ArrayList arraylist = new ArrayList();
            arraylist.Add("泛型集合测试Erica"); 
            arraylist.Add("泛型集合测试李少然"); 
            arraylist.Add("泛型集合测试李卫中");
            MemcachedClient client = new MemcachedClient();
            client.EnableCompression = false;
            client.Set("key3", arraylist);
            MessageBox.Show("key3:泛型集合测试Erica,泛型集合测试李少然,泛型集合测试李卫中");
        }
 
        private void button6_Click(object sender, EventArgs e)
        {
            MemcachedClient client = new MemcachedClient();
            object demo = client.Get("key3"); 
            ArrayList arraylist = demo as ArrayList;
            txt01.Text = arraylist[0].ToString() + ";" + arraylist[1].ToString() + ";" + arraylist[2].ToString() + ";";
        }
 
           //存入dt
        private void button7_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable(); 
            string str = "";
            dt.Columns.Add("id");
            dt.Columns.Add("name"); 
            DataRow dr = dt.NewRow();
            for (int i = 0; i < 3; i++)
            {
                dr = dt.NewRow();
                dr["id"] = "00" + i.ToString();
                dr["name"] = "姓名" + i.ToString();
                dt.Rows.Add(dr);
                str += dr["id"] + "," + dr["name"] + ";";
            }
            MemcachedClient client = new MemcachedClient(); 
            client.EnableCompression = false; 
            client.Set("key4", dt);
            MessageBox.Show("key4:" + str);
        }
 
        private void button8_Click(object sender, EventArgs e)
        {
            MemcachedClient client = new MemcachedClient();
 
            object demo = client.Get("key4");
 
            DataTable dt = demo as DataTable;
 
            int count = dt.Rows.Count;
 
            txt01.Text = dt.Rows[0][0].ToString() + "," + dt.Rows[0][1].ToString() + ";" + dt.Rows[1][0].ToString() + "," + dt.Rows[1][1].ToString() + ";" + dt.Rows[2][0].ToString() + "," + dt.Rows[2][1].ToString() + ";";
        }
    }
}

      person类的代码:
     using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace test
{
    [Serializable]
    public class Person
    {
        public string UserName { get; set; }
 
        public string UserId { get; set; }
    }
}


    这样就建立了小例子,可以存取各种类型的数据!那么ITOO的底层代码也就不用转来转去了就用两句话就可以解决!
//存
 public static bool Set(string key, object value, DateTime expiry)
        {
            return mc.Set(key,value, expiry);
        }
//取
 public static T GetObject<T>(T obj, string key)
        {
            obj = (T)mc.Get(key);
            return obj;
        }

小总:
     
     这样,就可以改掉ITOO底层的代码!但是又出现了一个问题就是:计算机识别二进制是特别快的,ITOO底层把对象先序列化为二进制肯定也是有道理的,如果我直接存对象,可能应用方便了,代码少了几行,但是却没有做测试实验,不知道到底存对象和序列化对象再存入memcached有什么不同!接下来会继续了解的

   下一篇,小编会讲解一些memcached集群存取的一些算法,敬请期待!


你可能感兴趣的:(Memcached ----关于存取的小例子)