Home > Backend Development > C#.Net Tutorial > Example introduction of high-performance caching system (Memcached)

Example introduction of high-performance caching system (Memcached)

零下一度
Release: 2017-06-23 15:05:22
Original
2096 people have browsed it

Entity types in Memcached cannot be cached in Memcached without being serialized, so the entity classes need to be processed before they can be cached.

Memcached is a high-performance distributed In-memory object caching system for dynamic web applications to reduce database load. It improves the speed of dynamic, database-driven websites by caching data and objects in memory to reduce the number of database reads. Memcached is based on a hashmap that stores key/value pairs. Its daemon is written in C, but the client can be written in any language and communicates with the daemon through the memcached protocol.

We can use Memcached to cache string types and other types that have been serialized internally, but for our custom types, we cannot cache them in Memcached because Memcached can only cache serialized data. , therefore, here we serialize the custom entity type and store it in Memcached.

First download memcached under the windows platform, and then install it. After installation, start the memcached service. You can enter the dos command under cmd, or you can start the service in Computer Management->Service->memcached->Start.

Then you can start the service in Introduce relevant dlls into the project:
Commons.dll, ICSharpCode.SharpZipLib.dll, log4net.dll, Memcached.ClientLibrary.dll
Introduce Memcached.ClientLibrary.dll into the project reference

Then follow After writing the program, create an MVC program here:
Create a class in the Models folder:

[Serializable]
public class VIP
{
public string UserName { get; set; }

public int? Vip { get; set; }

public DateTime? VipEndDate { get; set; }

public string Mail { get; set; }

public string QQ { get; set; }
}
Copy after login

If it is not marked as serializable, subsequent running of the program will Report an error.

Then create a MemcachedHelper class to assist programming.

public class MemcachedHelper
{
public static MemcachedClient mclient;

static MemcachedHelper()
{
string[] serverlist = new string[] { "127.0.0.1:11211" };

SockIOPool pool = SockIOPool.GetInstance("First");
pool.SetServers(serverlist);
pool.Initialize();
mclient = new MemcachedClient();
mclient.PoolName = "First";
mclient.EnableCompression = false;
}

public static bool set(string key, object value, DateTime expiry)
{
return mclient.Set(key, value, expiry);
}

public static object Get(string key)
{
return mclient.Get(key);
}

}
Copy after login

Finally, the specific implementation in the Controller:

public class EntityMemcachedController : Controller
    {
        //
        // GET: /EntityMemcached/
        /// <summary>
        /// 序列化实体类为字节数组,将其存储到Memcached中,以缓存数据,从而减轻访问压力....
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var vipInfo = new List<VIP>{
                new VIP{ UserName="张三", Vip=1, QQ="3123456", Mail="3123456", VipEndDate=(DateTime?)DateTime.Now.AddDays(1) },
                new VIP{ UserName="李四", Vip=1, QQ="4123456", Mail="4123456", VipEndDate=(DateTime?)DateTime.Now.AddDays(2) },
                new VIP{ UserName="王五", Vip=1, QQ="5123456", Mail="5123456", VipEndDate=(DateTime?)DateTime.Now.AddDays(3) },
                new VIP{ UserName="赵六", Vip=1, QQ="6123456", Mail="6123456", VipEndDate=(DateTime?)DateTime.Now.AddDays(4) },
                new VIP{ UserName="刘七", Vip=1, QQ="7123456", Mail="7123456", VipEndDate=(DateTime?)DateTime.Now.AddDays(5) }
            };

            
            if (Request.Cookies["_EntityMemcached"] == null)
            {
                string sessionId = Guid.NewGuid().ToString();
                Response.Cookies["_EntityMemcached"].Value = sessionId;
                Response.Cookies["_EntityMemcached"].Expires = DateTime.Now.AddMinutes(1);//设置cookie过期时间

                MemcachedHelper.set(sessionId, vipInfo, DateTime.Now.AddMinutes(1));//设置缓存过期时间

                return Content("Memcached分布式缓存设置成功!!!");
            }
            else
            {
                string key = Request.Cookies["_EntityMemcached"].Value.ToString();

                object obj = MemcachedHelper.Get(key);
                List<VIP> info = obj as List<VIP>;

                if (info != null)
                {
                    return View(info);
                }

            }

            return Content("若显示则有&#39;bug&#39;");
        }
Copy after login

See See the implementation:

Then exit and click "Implement memcached cache" again

I set the cache within one minute, so it will always be this interface within this minute. I have to say that memcached is still good! Next, we will study the caching strategy of OutputCached + Monogodb

The above is the detailed content of Example introduction of high-performance caching system (Memcached). For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template