memcached 基本實作

  • 436
  • 0
  • C#
  • 2016-10-26

這篇主要先講語法本身的存取。

環境的準備,簡單描述
docker
容器為 ubuntu 16.04 
ubuntu 16.04 用到的 package 為:memcached、openssh-server、supervisor

其實有 windows 版的 memcached,但是為了練一下 docker 跟 linux 所以選擇了比較難一些些的做法


以下為 C# 端

安裝套件:Install-Package EnyimMemcached

App.config

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <configSections>

    <sectionGroup name="enyim.com">

      <section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" />

    </sectionGroup>

  </configSections>

  <startup>

    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />

  </startup>

  <enyim.com>

    <memcached>

      <servers>

        <add address="127.0.0.1" port="11211" />      

      </servers>

      <socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00" />

    </memcached>

  </enyim.com>

</configuration>

StoreMode 有三種

Add

新增,不可修改既有的

Set

新增/修改

Replace

取代 既有的,不可新增

程式

using Enyim.Caching;

using Enyim.Caching.Memcached;

using System;



namespace ConsoleApplication9

{

    class Program

    {

        static void Main(string[] args)

        {

            string key = "key";

            string data = "data";

            DateTime expireDateTime = DateTime.Now.AddMinutes(10);



            using (MemcachedClient client = new MemcachedClient())

            {

                Console.Write("寫入資料是否成功:");

                Console.WriteLine(client.Store(StoreMode.Add,key,data,expireDateTime));

                Console.WriteLine($"寫入的資料為:{data}");

           

                Console.Write("讀取資料:");

                Console.WriteLine(client.Get(key));



                data += "test";

                Console.WriteLine($"更新後的資料為:{data}");

                Console.Write("更新資料是否成功:");

                Console.WriteLine(client.Store(StoreMode.Set, key, data, expireDateTime));

                // Console.WriteLine(client.Store(StoreMode.Replace, key, data, expireDateTime));



                Console.Write("讀取更新後的資料:");

                Console.WriteLine(client.Get(key));



                Console.Write("刪除資料是否成功:");

                Console.WriteLine(client.Remove(key));

            }

            Console.WriteLine("End");

            Console.ReadLine();

        }

    }

}