痛快-Cache

前言

在开发中,我们经常使用缓存。

分布式缓存使用CARP(Caching Array Routing Protocol)技术,可以产生一种高效率无接缝式的缓存,使用上让多台缓存服务器形同一台,并且不会造成数据重复存放的情况。

示例代码

首选引用如下DLL和依赖DLL,ServiceStack已宣称有100多位开发者在开发,我们可以借助其强大的团队来实现Cache功能

  using ServiceStack.CacheAccess;
  using ServiceStack.CacheAccess.Azure;
  using ServiceStack.CacheAccess.Memcached;
  using ServiceStack.CacheAccess.Providers;
  using ServiceStack.Redis;

using System.Collections.Generic;
using System.Net;
using ServiceStack.CacheAccess;
using ServiceStack.CacheAccess.Azure;
using ServiceStack.CacheAccess.Memcached;
using ServiceStack.CacheAccess.Providers;
using ServiceStack.Redis;

namespace TongKuao.Cache
{
    public class CacheHelper
    {
        public static ICacheClient cache = GetCache(CacheType.Memcache);
        public static ICacheClient GetCache(CacheType cacheType)
        {
            ICacheClient cache = null;
            switch (cacheType)
            {
                case CacheType.MemoryCache:
                    cache = GetMemotyCache();
                    break;
                case CacheType.Memcache:
                    cache = GetMemCache();
                    break;
                case CacheType.Redis:
                    cache = GetRedis();
                    break;
                case CacheType.Azure:
                    cache = GetAzure();
                    break;
                default:
                    cache = null;
                    break
            }
            return cache;
        }

        private static ICacheClient GetMemotyCache()
        {
            return new MemoryCacheClient();
        }

        private static ICacheClient GetMemCache()
        {
            List iPEndPoints = new List();
            iPEndPoints.Add(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11211));
            return new MemcachedClientCache(iPEndPoints);
        }

        private static ICacheClient GetRedis()
        {
            IRedisClientsManager iRedisClientsManager = new PooledRedisClientManager("127.0.0.1:6379");
            ICacheClient cache = (ICacheClient)iRedisClientsManager.GetCacheClient();
            return cache;
        }

        private static ICacheClient GetAzure()
        {
            return new AzureCacheClient("MyAppCache");
        }

        public enum CacheType
        {
            MemoryCache = 1,
            Memcache = 2,
            Redis = 3,
            Azure = 4
        }
    }
}

  我们的调用方式:

            var dater = CacheHelper.cache.Get<string>("Dater");
            if (dater == null)
            {
                CacheHelper.cache.Add<string>("Dater", DateTime.Now.ToString(), new TimeSpan(0, 0, 0, 10));
            }
            ViewBag.Dater = dater;

提示:在正式的开发中,我们一般会用IoC进入注入的方式,这里只是简单的示例。

转载于:https://www.cnblogs.com/tongkuai/p/3234455.html

你可能感兴趣的:(痛快-Cache)