教程集 www.jiaochengji.com
教程集 >  脚本编程  >  Asp.net  >  正文 .NET中用memcached缓存及Memcached.ClientLibrary使用教程

.NET中用memcached缓存及Memcached.ClientLibrary使用教程

发布时间:2016-11-27   编辑:jiaochengji.com
教程集为您提供.NET中用memcached缓存及Memcached.ClientLibrary使用教程等资源,欢迎您收藏本站,我们将为您提供最新的.NET中用memcached缓存及Memcached.ClientLibrary使用教程资源
Memcached是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。本文主要讲讲memcached分布式缓存的负载均衡配置比例,数据压缩,socket的详细配置等,以及在.net中的常用方法。

memcached在windows下的下载与安装

官方网站:http://memcached.org/

下载完成后

1、打开SetupFile安装文件夹。


2、打开cmd命令界面。

不要忘啦去windows服务中把服务启动了。

3、 以上的安装和启动都是在默认环境下进行的,在安装时可设置如下参数:

-p 监听的端口
-l 连接的IP地址, 默认是本机
-d start 启动memcached服务
-d restart 重起memcached服务
-d stop|shutdown 关闭正在运行的memcached服务
-d install 安装memcached服务
-d uninstall 卸载memcached服务
-u 以的身份运行 (仅在以root运行的时候有效)
-m 最大内存使用,单位MB。默认64MB
-M 内存耗尽时返回错误,而不是删除项
-c 最大同时连接数,默认是1024
-f 块大小增长因子,默认是1.25
-n 最小分配空间,key value flags默认是48
-h 显示帮助

4、对这样你就安装好啦。下面看我们怎么用c#语言操作memcached啦。


memcached使用

1、下载客户端的3个dll,ICSharpCode.SharpZipLib.dll,log4net.dll,Memcached.ClientLibrary.dll

2、跟着我新建一个简单控制台应用程序


 class AMemcached
    {
        public static MemcachedClient cache;
        static AMemcached()
        {
            string[] servers = { "172.18.5.66:11211" };
            //初始化池
            SockIOPool pool = SockIOPool.GetInstance();
            //设置服务器列表
            pool.SetServers(servers);
            //各服务器之间负载均衡的设置比例
            pool.SetWeights(new int[] { 1 });
            //初始化时创建连接数
            pool.InitConnections = 3;
            //最小连接数
            pool.MinConnections = 3;
            //最大连接数
            pool.MaxConnections = 5;
            //连接的最大空闲时间,下面设置为6个小时(单位ms),超过这个设置时间,连接会被释放掉
            pool.MaxIdle = 1000 * 60 * 60 * 6;
            //socket连接的超时时间,下面设置表示不超时(单位ms),即一直保持链接状态
            pool.SocketConnectTimeout = 0;
            //通讯的超市时间,下面设置为3秒(单位ms),.Net版本没有实现
            pool.SocketTimeout = 1000 * 3;
            //维护线程的间隔激活时间,下面设置为30秒(单位s),设置为0时表示不启用维护线程
            pool.MaintenanceSleep = 30;
            //设置SocktIO池的故障标志
            pool.Failover = true;
            //是否对TCP/IP通讯使用nalgle算法,.net版本没有实现
            pool.Nagle = false;
            //socket单次任务的最大时间(单位ms),超过这个时间socket会被强行中端掉,当前任务失败。
            pool.MaxBusy = 1000 * 10;
            pool.Initialize();
            cache = new MemcachedClient();
            //是否启用压缩数据:如果启用了压缩,数据压缩长于门槛的数据将被储存在压缩的形式
            cache.EnableCompression = false;
            //压缩设置,超过指定大小的都压缩
            //cache.CompressionThreshold = 1024 * 1024;           
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //存入key为a,value为123的一个缓存
            AMemcached.cache.Add("a", "123");
            //读出key为a的缓存值
            var s = AMemcached.cache.Get("a");
            //输出
            Console.WriteLine(s);
            Console.ReadKey();           
        }
    }


Note:首先告诉你一个好的消息,memcached就这么简单,你已经能够使用啦,如果感兴趣,那么在AMemcached.cache的后面加点,看看这个类库里面还有那些关于增删改查重载的好方法。如果你还想再进一步了解,那么继续往下看。


细品 .NET Memcached.ClientLibrary

1、说说memcached分布式缓存的设置与应用


            string[] servers = { "172.18.5.66:11211", "192.168.10.121:11211" };
            //初始化池
            SockIOPool pool = SockIOPool.GetInstance();
            //设置服务器列表
            pool.SetServers(servers);
            //各服务器之间负载均衡的设置比例
            pool.SetWeights(new int[] { 1, 10 });



Note:

1、在172.18.5.66,与192.168.10.121两台机器上装memcached服务端。

2、 pool.SetWeights这里的1跟10意思是,负载均衡比例,假如11000条数据,大致数据分布为:172.18.5.66分布1000条数据左右。另外一台为10000条左右。

3、memcached服务端并不具备负载均衡的能力,而是memcachedClient实现的,具体存取数据实现的核心是采用一致性Hash算法,把key-value分布到某一台服务器中里边。

2、说说memcached的数据压缩机制

            //是否启用压缩数据:如果启用了压缩,数据压缩长于门槛的数据将被储存在压缩的形式
            cache.EnableCompression = false;
            //压缩设置,超过指定大小的都压缩
            //cache.CompressionThreshold = 1024 * 1024;

Note:

1、这个处理是在MemcachedClient对象中,设置这个EnableCompression属性,是否使用压缩的意思,如果启用啦压缩功能 ,则ICSharpCode.SharpZipLib类库会在数据超过预设大小时,进行数据压缩处理。

2、CompressionThreshold这个属性是压缩的阀值,默认是15K,如果超过设定的阀值则使用memcached的通讯协议,存数据时给每个数据项分配一个16为的flag表示,用作记录是否有压缩,如果有压缩则提取数据是进行解压。如果没有超过阀值则不压缩,直接存储。

3、说说怎么使用客户端多个SocketIO池


class AMemcached
    {
        public MemcachedClient cache;
        public  AMemcached(string poolName)
        {
            string[] servers = { "172.18.5.66:11211", "192.168.10.121:11211" };
            //初始化池
            SockIOPool pool = SockIOPool.GetInstance(poolName);
            //设置服务器列表
            pool.SetServers(servers);
            //各服务器之间负载均衡的设置比例
            pool.SetWeights(new int[] { 1, 10 });
            //初始化时创建连接数
            pool.InitConnections = 3;
            //最小连接数
            pool.MinConnections = 3;
            //最大连接数
            pool.MaxConnections = 5;
            //连接的最大空闲时间,下面设置为6个小时(单位ms),超过这个设置时间,连接会被释放掉
            pool.MaxIdle = 1000 * 60 * 60 * 6;
            //socket连接的超时时间,下面设置表示不超时(单位ms),即一直保持链接状态
            pool.SocketConnectTimeout = 0;
            //通讯的超时时间,下面设置为3秒(单位ms),.Net版本没有实现
            pool.SocketTimeout = 1000 * 3;
            //维护线程的间隔激活时间,下面设置为30秒(单位s),设置为0时表示不启用维护线程
            pool.MaintenanceSleep = 30;
            //设置SocktIO池的故障标志
            pool.Failover = true;
            //是否对TCP/IP通讯使用nalgle算法,.net版本没有实现
            pool.Nagle = false;
            //socket单次任务的最大时间(单位ms),超过这个时间socket会被强行中端掉,当前任务失败。
            pool.MaxBusy = 1000 * 10;
            // 初始化一些值并与MemcachedServer段建立连接
            pool.Initialize();
            cache = new MemcachedClient();
            //是否启用压缩数据:如果启用了压缩,数据压缩长于门槛的数据将被储存在压缩的形式
            cache.EnableCompression = false;
            //压缩设置,超过指定大小的都压缩
            //cache.CompressionThreshold = 1024 * 1024;   
            //指定客户端访问的SockIO池
            cache.PoolName = poolName;
        }


    }
    class Program
    {
        static void Main(string[] args)
        {
            //存入key为a,value为123的一个缓存
            new AMemcached("me").cache.Add("b", 123);
            //读出key为a的缓存值
            var s = new AMemcached("me").cache.Get("b");
            //输出
            Console.WriteLine(s);
            Console.ReadKey();           
        }
    }


Note:使用SocketIoPool的场景,假如你的系统中用到A,B两台机器memcached的缓存数据,而A,B是不相关的,没有数据互通共享,那么这个时候你就可以根据设置poolName来处理读写那台机器。而不用多处,重复配置客户端的各种参数。

4、说说memcached的故障转移处理

           //设置SocktIO池的故障标志
            pool.Failover = true;

Note:memcached的鼓掌转移是一套正常节点发生故障变为死节点时的处理机制。

1、开启故障转移:如果发生socket异常,则该节点被添加到存放死节点属性的_hostDead中,新请求被映射到dead server,检测尝试连接死节点的时间间隔属性_hostDeadDuration(默认设置为100ms),如果没有达到设定的间隔时间则key会被映射到可用的server处理,如果达到了时间间隔,则尝试重新链接,连接成功将此节点从_hostDead中去除,连接失败则间隔时间翻倍存放,下次重新连接时间会被拉长。

2、不开启故障转移:新的请求都会被映射到dead server上,尝试重新建立socket链接,如果连接失败,返回null或者操作失败。

5、说说key-value中的key与value

1、key在服务端的长度限制为250个字符,建议使用较短的key但不要重复。

2、value的大小限制为1mb,如果大拉,可以使用压缩,如果还大,那可能拆分到多个key中。



Memcached .NET(C#)实例分析

一:Memcached的安装

step1. 下载memcache的windows稳定版(这里我下载了memcached 1.2.1 for Win32 binaries (Dec 23, 2006) 这个版本),解压放某个盘下面,比如在c:\memcached
step2. 在终端(也即cmd命令界面)下输入 ‘c:\memcached\memcached.exe -d install’ 安装
step3. 再输入: ‘c:\memcached\memcached.exe -d start’ 启动。

PS: 以后memcached将作为windows的一个服务每次开机时自动启动。这样服务器端已经安装完毕了。


二: .NET memcached client library


       下载文件:https://sourceforge.net/projects/memcacheddotnet/
       将Commons.dll,ICSharpCode.SharpZipLib.dll,log4net.dll,Memcached.ClientLibrary.dll 等放到bin目录
       引用Memcached.ClientLibrary.dll
 
程序实例

代码

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->using System;
using System.Collections;
using Memcached.ClientLibrary;
using System.Text;

namespace Memcache
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request["action"] == "clear")
                    this.clear();
                else
                    this.test();
            }
        }

        public void clear()
        {
            string[] servers = { "192.168.1.113:11211", "192.168.202.128:11211" };

            //初始化池
            SockIOPool pool = SockIOPool.GetInstance();
            pool.SetServers(servers);
            pool.InitConnections = 3;
            pool.MinConnections = 3;
            pool.MaxConnections = 5;
            pool.SocketConnectTimeout = 1000;
            pool.SocketTimeout = 3000;
            pool.MaintenanceSleep = 30;
            pool.Failover = true;
            pool.Nagle = false;
            pool.Initialize();
            MemcachedClient mc = new Memcached.ClientLibrary.MemcachedClient();
            mc.EnableCompression = false;
            mc.Delete("cache");
            mc.Delete("endCache");
            Response.Write("清空缓存成功");
        }


        public void test()
        {
            //分布Memcachedf服务IP 端口
            string[] servers = { "192.168.1.113:11211", "192.168.202.128:11211" };

            //初始化池
            SockIOPool pool = SockIOPool.GetInstance();
            pool.SetServers(servers);
            pool.InitConnections = 3;
            pool.MinConnections = 3;
            pool.MaxConnections = 5;
            pool.SocketConnectTimeout = 1000;
            pool.SocketTimeout = 3000;
            pool.MaintenanceSleep = 30;
            pool.Failover = true;
            pool.Nagle = false;
            pool.Initialize();
            //客户端实例
            MemcachedClient mc = new Memcached.ClientLibrary.MemcachedClient();
            mc.EnableCompression = false;
            StringBuilder sb = new StringBuilder();
            //写入缓存
            sb.AppendLine("写入缓存测试:");
            sb.AppendLine("<br>_______________________________________<br>");
            if (mc.KeyExists("cache"))
            {
                sb.AppendLine("缓存cache已存在");
            }
            else
            {
                mc.Set("cache", "写入缓存时间:" DateTime.Now.ToString());
                sb.AppendLine("缓存已成功写入到cache");
            }
            sb.AppendLine("<br>_______________________________________<br>");
            sb.AppendLine("读取缓存内容如下:<br>");
            sb.AppendLine(mc.Get("cache").ToString());

            //测试缓存过期
            sb.AppendLine("<br>_______________________________________<br>");
            if (mc.KeyExists("endCache"))
            {
                sb.AppendLine("缓存endCache已存在,过期时间为:"   mc.Get("endCache").ToString());
            }
            else
            {
                mc.Set("endCache", DateTime.Now.AddMinutes(1).ToString(), DateTime.Now.AddMinutes(1));
                sb.AppendLine("缓存已更新写入到endCache,写入时间:" DateTime.Now.ToString()  " 过期时间:"   DateTime.Now.AddMinutes(1).ToString());
            }

            //分析缓存状态
            Hashtable ht = mc.Stats();
            sb.AppendLine("<br>_______________________________________<br>");
            sb.AppendLine("Memcached Stats:");
            sb.AppendLine("<br>_______________________________________<br>");
            foreach (DictionaryEntry de in ht)
            {
                Hashtable info = (Hashtable)de.Value;
                foreach (DictionaryEntry de2 in info)
                {
                    sb.AppendLine(de2.Key.ToString() ":&nbsp;&nbsp;&nbsp;&nbsp;" de2.Value.ToString() "<br>");
                }
            }
            Response.Write(sb.ToString());
        }
    }
}

您可能感兴趣的文章:
.NET中用memcached缓存及Memcached.ClientLibrary使用教程
memcache是什么?
Memcached安装测试一例
memcached启动和关闭的方法
Django中的缓存Cache是什么
php_memcache扩展有什么用
memcached常用配置参数总结
如何在Linux服务器端的安装Memcache
配置memcached集群负载均衡
PHP清除Memcache过期缓存程序代码

[关闭]
~ ~