经过前几篇文章的理论阐述后,现在开始演练下

一、缓存服务准备

我没有太多的资源,所有东西都安装在我的PC机上(这台笔记本所有权不是我的,历史悠久,还掉了一个键,穷啊,只能接上外接键盘).使用默认设置安装过完成。

用安装后自带的PowerShell工具添加一个名为“FirstCache”缓存。命令好下:

New-Cache FirstCache

Get-CacheHost命令查看现有主机:

微软分布式缓存 AppFabric(Velocity)-开发篇(二)缓存的基础方法使用

主机名为:FENGXU-MSFT,端口号是默认的22233,服务名为默认的:DistributedCacheService

Get-Cache命令查看现有的缓存

微软分布式缓存 AppFabric(Velocity)-开发篇(二)缓存的基础方法使用

可以看到群集中有两个缓存,default是安装后默认的一个缓存,FirstCache是刚刚自己创建的缓存

二、缓存基本API使用

 新建一个工程,添加上一篇中的四个程序集的引用,配置app.config文件如下

?>
<configuration>

  <!--configSections must be the FIRST element -->
  <configSections>

    <!-- required to read the <dataCacheClient> element -->
    <section name="dataCacheClient" type="Microsoft.Data.Caching.DataCacheClientSection,
       CacheBaseLibrary" allowLocation="true" allowDefinition="Everywhere"/>

    <!-- required to read the <fabric> element, when present -->
    <section name="fabric" type="System.Data.Fabric.Common.ConfigFile,
       FabricCommon" allowLocation="true" allowDefinition="Everywhere"/>

  </configSections>

  <!-- routing client-->
  <dataCacheClient deployment="simple" timeout="30000">

    <!-- (optional) specify local cache 
    <localCache
      isEnabled="true"
      sync="TTLBased"
      objectCount="100000"
      ttlValue="300" />
    -->

    <!--(optional) specify cache notifications poll interval 
    <clientNotification pollInterval="300" />
    -->

    <!-- cache host(s) -->
    <hosts>
      <host name="FENGXU-MSFT" cachePort="22233" cacheHostName="DistributedCacheService"/>
    </hosts>
  </dataCacheClient>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>


这里使用的是本地缓存,在host节点中host name 是cache hosts的主机名,cacheHostName是服务名。

在代码中的基本读写

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//添?加ó命ü名?空?间?
using Microsoft.Data.Caching;

namespace VolocityDemo
{
    class BaseMethod
    {
        DataCacheFactory factory;

        public BaseMethod()
        {
            //方?法ぁ?一?:阰使?用?默?认?配?置?创洹?建¨
            factory = new DataCacheFactory();

            //代洙?码?中D动ˉ态?指?定¨
            //方?法ぁ?二t:阰declare array for cache host(s)
            //DataCacheServerEndpoint[] servers = new DataCacheServerEndpoint[1];

            ////specify cache host(s)
            //servers[0] = new DataCacheServerEndpoint("FENGXU-MSFT",
            //                        22233, "DistributedCacheService");
            //factory = new DataCacheFactory(servers, false, false);
        }

        ~BaseMethod()
        {
            factory.Dispose();
        }

        public void Test()
        {
            DataCache dataCache = factory.GetCache("FirstCache");

            //添?加ó缓o存?对?象ó
            if (dataCache.Get("Time1") == null)
            {
                dataCache.Add("Time1", DateTime.Now);
            }
            Console.WriteLine(string.Format("读á取?缓o存?对?象óTime1:阰{0:yyyy-MM-dd HH:mm:ss}", dataCache.Get("Time1")));

            dataCache.Put("Time1", DateTime.Now);
            Console.WriteLine(string.Format("读á取?更ü新?的?缓o存?对?象óTime1:阰{0:yyyy-MM-dd HH:mm:ss}", dataCache.Get("Time1")));

            //移?除y对?象ó
            //remove object in cache using array notation
            dataCache["Time1"] = null;
            //remove object in cache using key "Key0"
            //dataCache.Remove("Key0");
        }
    }
}


当缓存群集重启时,缓存服务将从配置文件中加载现有的缓存配置,FirstCache将仍然存在。还可以用powershell工具Export-CacheClusterConfig命令命令导出来

示例中导出的配置如下:

?>
<configuration>
    <configSections>
        <section name="dataCache" type="Microsoft.Data.Caching.DataCacheSection, CacheBaseLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
    </configSections>
    <dataCache cluster="demoCache" size="Small">
        <caches>
            <cache type="partitioned" consistency="strong" name="default">
                <policy>
                    <eviction type="lru" />
                    <expiration defaultTTL="10" isExpirable="true" />
                </policy>
            </cache>
            <cache type="partitioned" consistency="strong" name="FirstCache">
                <policy>
                    <eviction type="lru" />
                    <expiration defaultTTL="10" isExpirable="true" />
                </policy>
            </cache>
        </caches>
        <hosts>
            <host clusterPort="22234" hostId="1743595319" size="1228" quorumHost="true"
                name="FENGXU-MSFT" cacheHostName="DistributedCacheService"
                cachePort="22233" />
        </hosts>
        <advancedProperties>
            <partitionStoreConnectionSettings providerName="System.Data.SqlServerCe.3.5"
                connectionString="\\127.0.0.1\MicrosoftDistributeCache\ConfigStore.sdf" />
        </advancedProperties>
    </dataCache>
</configuration>

相关文章: