/// <summary>
 /// Initializes a new instance of the <see cref="T:EasyCaching.Memcached.DefaultMemcachedCachingProvider"/> class.
 /// </summary>
 /// <param name="memcachedClient">Memcached client.</param>
 public DefaultMemcachedCachingProvider(
     IMemcachedClient memcachedClient,
     MemcachedOptions options)
 {
     this._memcachedClient = memcachedClient;
     this._options         = options;
 }
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            this.client = ProviderHelper.GetClient(name, config, () => (ICouchbaseClientFactory)new CouchbaseClientFactory());

            ProviderHelper.CheckForUnknownAttributes(config);
        }
Ejemplo n.º 3
0
 public GeocodioQueryService(IGeoQueryParser geoQueryParser, IGeoQueryDispatchService geoQueryDispatchService,
                             IMemcachedClient memcachedClient)
 {
     _geoQueryParser          = geoQueryParser;
     _geoQueryDispatchService = geoQueryDispatchService;
     _memcachedClient         = memcachedClient;
 }
Ejemplo n.º 4
0
        public MemCached(IOptions <MemCachedOptions> options, ILogger <MemCached> logger)
        {
            _logger = logger;

            try
            {
                MemcachedCluster cluster;

                if (!string.IsNullOrWhiteSpace(options.Value.host))
                {
                    cluster = new MemcachedCluster($"{options.Value.host}:{options.Value.port}");
                }
                else
                {
                    cluster = new MemcachedCluster("localhost:11212");
                }

                cluster.Start();

                _memcache = cluster.GetClient();
            }
            catch (Exception ex)
            {
                _logger.LogError(new EventId(ex.HResult), ex, ex.Message);
            }
        }
 public MemcachedAccessTokenProvider(IMemcachedClient memcachedClient, string cookieName, bool useSecureCookie)
 {
     _memcachedClient = memcachedClient;
     _cookieName = cookieName;
     _useSecureCookie = useSecureCookie;
     _logger = log4net.LogManager.GetLogger(this.GetType());
 }
Ejemplo n.º 6
0
 static MemCacheMgr()
 {
     lock (thisLock)
     {
         _instance = CreateClient();                //_instance = new MemcachedClient();
     }
 }
Ejemplo n.º 7
0
 internal CouchbaseViewBase(IMemcachedClient client, IHttpClientLocator clientLocator, string designDocument, string indexName)
 {
     this.client         = client;
     this.clientLocator  = clientLocator;
     this.designDocument = designDocument;
     this.indexName      = indexName;
 }
        void initData()
        {
            client = new MemcachedClient();

            System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
            sessionStateSection = (SessionStateSection)cfg.GetSection("system.web/sessionState");
        }
            public bool Save(IMemcachedClient client, string id, bool metaOnly, bool useCas)
            {
                using (var ms = new MemoryStream())
                {
                    this.SaveHeader(ms);
                    bool retval;
                    var  ts = TimeSpan.FromMinutes(this.Timeout);

                    retval = useCas
                                                                ? client.Cas(Memcached.StoreMode.Set, HeaderPrefix + id, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, this.HeadCas).Result
                                                                : client.Store(Memcached.StoreMode.Set, HeaderPrefix + id, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);

                    if (!metaOnly)
                    {
                        ms.Position = 0;

                        using (var bw = new BinaryWriter(ms))
                        {
                            this.Data.Serialize(bw);
                            retval = useCas
                                                                                ? client.Cas(Memcached.StoreMode.Set, DataPrefix + id, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, this.DataCas).Result
                                                                                : client.Store(Memcached.StoreMode.Set, DataPrefix + id, new ArraySegment <byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);
                        }
                    }

                    return(retval);
                }
            }
Ejemplo n.º 10
0
 internal CouchbaseView(IMemcachedClient client, IHttpClientLocator clientLocator,
                        string designDocument, string indexName, bool shouldLookupDocById = false,
                        string pagedViewIdProperty = null, string pagedViewKeyProperty = null)
     : base(client, clientLocator, designDocument, indexName)
 {
     _shouldLookupDocById = shouldLookupDocById;
 }
Ejemplo n.º 11
0
 public Memcache(MemcachedSetting setting, IMemcachedClient client)
 {
     _client = new MemcachedClient(null, new MemcachedClientConfiguration(null, new MemcachedClientOptions()
     {
         Protocol = MemcachedProtocol.Binary, Servers = new List <Server>()
     }));
 }
 public MemcachedAccessTokenProvider(IMemcachedClient memcachedClient, string cookieName, bool useSecureCookie)
 {
     _memcachedClient = memcachedClient;
     _cookieName      = cookieName;
     _useSecureCookie = useSecureCookie;
     _logger          = log4net.LogManager.GetLogger(this.GetType());
 }
        void initData()
        {
            client = new MemcachedClient();

            System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
            sessionStateSection = (SessionStateSection)cfg.GetSection("system.web/sessionState");
        }
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            _client = ProviderHelper.GetClient(name, config, () => (ICouchbaseClientFactory) new CouchbaseClientFactory());

            ProviderHelper.CheckForUnknownAttributes(config);
        }
        public void AssertGetSetIntValue(IMemcachedClient cacheClient)
        {
            cacheClient.Set("test:intkey1", 1);
            var value = cacheClient.Get("test:intkey1");

            Assert.That(value, Is.EqualTo(1));
        }
Ejemplo n.º 16
0
 public ScheduleSubscriber(IMsgApiService msgSvc, IUCenterService uCenter, IScheduleRepository repository, IMemcachedClient cache)
 {
     _msgSvc     = msgSvc;
     _uCenter    = uCenter;
     _repository = repository;
     _cache      = cache;
 }
Ejemplo n.º 17
0
        private ICache CreateCacheEngine()
        {
            if (!_isInitialised)
            {
                lock (_lockRef)
                {
                    if (!_isInitialised)
                    {
                        _isInitialised = true;
                        var config     = new Enyim.Caching.Configuration.MemcachedClientConfiguration();
                        var serverFarm = ConstructCacheFarm();
                        serverFarm.NodeList.ForEach(n => config.AddServer(n.IPAddressOrHostName, n.Port));
                        config.SocketPool.ConnectionTimeout = ConnectTimeout;
                        config.SocketPool.DeadTimeout       = DeadNodeTimeout;

                        config.SocketPool.MaxPoolSize = MaximumPoolSize;
                        config.SocketPool.MinPoolSize = MinimumPoolSize;

                        // Note: Tried using the Binary protocol here but I consistently got unreliable results in tests.
                        // TODO: Need to investigate further why Binary protocol is unreliable in this scenario.
                        // Could be related to memcached version and/or transcoder.
                        config.Protocol   = MemcachedProtocol.Text;
                        config.Transcoder = new DataContractTranscoder();
                        _client           = new MemcachedClient(config);
                        Logger.WriteInfoMessage("memcachedAdapter initialised.");
                        LogManager.AssignFactory(new LogFactoryAdapter(Logger));
                    }
                }
            }
            return(new memcachedAdapter(Logger, _client));
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            base.Initialize(name, config);

            _client = ProviderHelper.GetClient(name, config, () => (IMemcachedClientFactory)new DefaultClientFactory());

            ProviderHelper.CheckForUnknownAttributes(config);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// 初始化一个<see cref="DefaultMemcachedCacheProvider"/>类型的实例
 /// </summary>
 /// <param name="memcachedClient">Memcached客户端</param>
 /// <param name="options">Memcached选项</param>
 /// <param name="log">日志</param>
 public DefaultMemcachedCacheProvider(IMemcachedClient memcachedClient,
                                      IOptionsMonitor <MemcachedOptions> options, Bing.Logs.ILog log = null)
 {
     this._memcachedClient = memcachedClient;
     this._options         = options.CurrentValue;
     this._log             = log ?? NullLog.Instance;
     this.CacheStatsInfo   = new CacheStatsInfo();
 }
        public override void Initialize(string name, NameValueCollection config)
        {
            base.Initialize(name, config);

            this.client = ProviderHelper.GetClient(name, config, () => (IMemcachedClientFactory) new DefaultClientFactory());

            ProviderHelper.CheckForUnknownAttributes(config);
        }
        private static SessionStateItem Get(IMemcachedClient client, bool acquireLock, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
        {
            locked  = false;
            lockId  = null;
            lockAge = TimeSpan.Zero;
            actions = SessionStateActions.None;

            var e = SessionStateItem.Load(client, id, false, _compressor, _isLoggingEnabled ? _logger : null);

            if (e == null)
            {
                return(null);
            }

            if (acquireLock)
            {
                // repeat until we can update the retrieved
                // item (i.e. nobody changes it between the
                // time we get it from the store and updates it s attributes)
                // Save() will return false if Cas() fails
                while (true)
                {
                    if (e.LockId > 0)
                    {
                        break;
                    }

                    actions = e.Flag;

                    e.LockId   = _exclusiveAccess ? e.HeadCas : 0;
                    e.LockTime = DateTime.UtcNow;
                    e.Flag     = SessionStateActions.None;

                    // try to update the item in the store
                    if (e.Save(client, id, true, _exclusiveAccess, _compressor, _isLoggingEnabled ? _logger : null))
                    {
                        locked = true;
                        lockId = e.LockId;

                        return(e);
                    }

                    // it has been modified between we loaded and tried to save it
                    e = SessionStateItem.Load(client, id, false, _compressor, _isLoggingEnabled ? _logger : null);
                    if (e == null)
                    {
                        return(null);
                    }
                }
            }

            locked  = true;
            lockAge = DateTime.UtcNow - e.LockTime;
            lockId  = e.LockId;
            actions = SessionStateActions.None;

            return(acquireLock ? null : e);
        }
Ejemplo n.º 22
0
        public MemcachedCache(IMemcachedClient memcachedClient)
        {
            if (memcachedClient == null)
            {
                throw new ArgumentNullException(nameof(memcachedClient));
            }

            this.memcachedClient = memcachedClient;
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:EasyCaching.Memcached.DefaultMemcachedCachingProvider"/> class.
 /// </summary>
 /// <param name="memcachedClient">Memcached client.</param>
 public DefaultMemcachedCachingProvider(
     IMemcachedClient memcachedClient,
     MemcachedOptions options,
     ILoggerFactory loggerFactory = null)
 {
     this._memcachedClient = memcachedClient;
     this._options         = options;
     this._logger          = loggerFactory?.CreateLogger <DefaultMemcachedCachingProvider>();
 }
Ejemplo n.º 24
0
        public MemcachedCache(IMemcachedClient client)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            this.client = client;
        }
Ejemplo n.º 25
0
 public HomeController(
     IMemcachedClient memcachedClient,
     IBlogPostService blogPostService,
     ILoggerFactory loggerFactory)
 {
     _memcachedClient = memcachedClient;
     _blogPostService = blogPostService;
     _logger          = loggerFactory.CreateLogger <HomeController>();
 }
        /// <summary>
        /// Function to initialize the provider
        /// </summary>
        /// <param name="name">Name of the element in the configuration file</param>
        /// <param name="config">Configuration values for the provider from the Web.config file</param>
        public override void Initialize(
            string name,
            NameValueCollection config)
        {
            base.Initialize(name, config);
            client = ProviderHelper.GetClient(name, config, () => (ICouchbaseClientFactory) new CouchbaseClientFactory(), out disposeClient);

            ProviderHelper.CheckForUnknownAttributes(config);
        }
Ejemplo n.º 27
0
        public MemcachedCache(IMemcachedClientConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            client = new MemcachedClient(configuration);
        }
Ejemplo n.º 28
0
        private static void Initialize()
        {
            ICouchbaseClientFactory factory = Container.Resolve <ICouchbaseClientFactory>();

            if (factory != null)
            {
                memcachedClient = factory.Create((ICouchbaseClientConfiguration)ConfigurationManager.GetSection("default-bucket"));
            }
        }
Ejemplo n.º 29
0
        public object Get(string key)
        {
            object value = null;

            IMemcachedClient client = this.GetMemcachedClient();

            value = client.Get(key);

            return(value);
        }
Ejemplo n.º 30
0
        public SlabStatisticsDto GetMetadata()
        {
            SlabStatisticsDto resultMetadata = new SlabStatisticsDto();

            IMemcachedClient client = this.GetMemcachedClient();

            ServerStats stats = client.Stats();

            return(resultMetadata);
        }
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);

            lock (SyncLock) {
                if (_client == null)
                    _client = ProviderHelper.GetClient(name, config, () => (IMemcachedClientFactory)new MembaseClientFactory());
            }
            ProviderHelper.CheckForUnknownAttributes(config);
        }
Ejemplo n.º 32
0
        public StatisticsDto GetStatistics()
        {
            StatisticsDto resultStats = new StatisticsDto();

            IMemcachedClient client = this.GetMemcachedClient();

            ServerStats stats = client.Stats();

            return(resultStats);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MemcachedServiceCache"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="tagMapper">The tag mapper.</param>
 public MemcachedServiceCache(IMemcachedClient client, ITagMapper tagMapper)
 {
     if (client == null)
     {
         throw new ArgumentNullException("client");
     }
     Cache      = client;
     _tagMapper = tagMapper;
     Settings   = new ServiceCacheSettings();
 }
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            // Initialize the base class
            base.Initialize(name, config);

            // Create our Couchbase client instance
            _client = ProviderHelper.GetClient(name, config, () => (ICouchbaseClientFactory) new CouchbaseClientFactory(), out _disposeClient);

            if (_isFirstTimeInitialization)
            {
                lock (FirstTimeInitializationSync)
                {
                    if (_isFirstTimeInitialization)
                    {
                        var loggingEnabled = ProviderHelper.GetAndRemove(config, "logging", false) ?? "false";
                        _isLoggingEnabled = (String.Compare(loggingEnabled, "true", StringComparison.OrdinalIgnoreCase) == 0);

                        if (_isLoggingEnabled)
                        {
                            // Path where to store NLog logs (effective if useExistedLoggingConfig != "true")
                            var loggingFileName = ProviderHelper.GetAndRemove(config, "loggingFilename", false) ?? "Logs/CouchbaseSessionStateProvider.log";

                            // useExistedLoggingConfig = "true" to use existed application NLog config file
                            // or useExistedLoggingConfig = "false" (or just skip this config) to configure NLog in Couchbase provider and override application settings (if exists)
                            var useExistedLoggingConfigString = ProviderHelper.GetAndRemove(config, "useExistedLoggingConfig", false) ?? "false";
                            var useExistedLoggingConfig       = (String.Compare(useExistedLoggingConfigString, "true", StringComparison.OrdinalIgnoreCase) == 0);

                            _logger = SetupLogger(useExistedLoggingConfig, loggingFileName);
                        }

                        // By default use exclusive session access. But allow it to be overridden in the config file
                        var exclusive = ProviderHelper.GetAndRemove(config, "exclusiveAccess", false) ?? "true";
                        _exclusiveAccess = (String.Compare(exclusive, "true", StringComparison.OrdinalIgnoreCase) == 0);

                        // By default do not use compression on session data
                        var compress = ProviderHelper.GetAndRemove(config, "compress", false) ?? "false";
                        _compressData = (String.Compare(compress, "true", StringComparison.OrdinalIgnoreCase) == 0);

                        if (_compressData)
                        {
                            // By default we use lz4 instead of gzip, because it is considered much faster!
                            var compressionTypeString = ProviderHelper.GetAndRemove(config, "compressionType", false) ?? "quicklz";
                            _compressor = CompressorFactory.Create(compressionTypeString);
                        }

                        LogProviderConfiguration();

                        // Make sure no extra attributes are included
                        ProviderHelper.CheckForUnknownAttributes(config);

                        _isFirstTimeInitialization = false;
                    }
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="T:EasyCaching.Memcached.DefaultMemcachedCachingProvider"/> class.
        /// </summary>
        /// <param name="memcachedClient">Memcached client.</param>
        public DefaultMemcachedCachingProvider(
            IMemcachedClient memcachedClient,
            IOptionsMonitor <MemcachedOptions> options,
            ILoggerFactory loggerFactory = null)
        {
            this._memcachedClient = memcachedClient;
            this._options         = options.CurrentValue;
            this._logger          = loggerFactory?.CreateLogger <DefaultMemcachedCachingProvider>();

            this._cacheStats = new CacheStats();
        }
Ejemplo n.º 36
0
 public GameServicesController(
     IOptions <AppSettingsConfig> appSettingsConfig,
     IOptions <AuthenticationConfig> authenticationConfig,
     GameServiceClient gameServiceClient,
     IMemcachedClient memcachedClient)
 {
     this.appSettingsConfig    = appSettingsConfig.Value;
     this.authenticationConfig = authenticationConfig.Value;
     this.gameServiceClient    = gameServiceClient;
     this.memcachedClient      = memcachedClient;
 }
Ejemplo n.º 37
0
        private void Validation(IMemcachedClient cacheDatabase, string key, object value)
        {
            if (cacheDatabase == null)
            {
                throw new InvalidOperationException("The cache database was not initialized or the provider operation has failed");
            }

            if (key == null || value == null)
            {
                throw new ArgumentNullException("Key parameter or object value parameter can not be null");
            }
        }
		public MemcachedClientFailoverTests()
			: base(TestName)
		{
			// note: we're intentionally adding a dead server
			new ClusterBuilder(TestName)
					.Endpoints("localhost:11300")
					.SocketOpts(connectionTimeout: TimeSpan.FromMilliseconds(100))
					.Use
						.ReconnectPolicy(() => new PeriodicReconnectPolicy { Interval = TimeSpan.FromHours(1) })
					.Register();

			config = new ClientConfigurationBuilder().Cluster(TestName).Create();
			client = new MemcachedClient(config);
		}
Ejemplo n.º 39
0
        /// <summary>
        /// 使用单例模式 创建MemcachedClient客户端实例
        /// </summary>
        /// <returns></returns>
        public static IMemcachedClient Create()
        {
            if(_client==null)
            {
                lock (_syncRoot)
                {
                    if(_client==null)
                    {
                        _client=new MemcachedClient();
                    }
                }
            }

            return _client;
        }
        public static SessionStateItem Get(IMemcachedClient client, HttpContext context, bool acquireLock, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions)
        {
            locked = false;
            lockId = null;
            lockAge = TimeSpan.Zero;
            actions = SessionStateActions.None;

            var e = SessionStateItem.Load(client, id, false);
            if (e == null)
                return null;

            if (acquireLock) {
                // repeat until we can update the retrieved
                // item (i.e. nobody changes it between the
                // time we get it from the store and updates it s attributes)
                // Save() will return false if Cas() fails
                while (true) {
                    if (e.LockId > 0)
                        break;

                    actions = e.Flag;

                    e.LockId = exclusiveAccess ? e.HeadCas : 0;
                    e.LockTime = DateTime.UtcNow;
                    e.Flag = SessionStateActions.None;

                    // try to update the item in the store
                    if (e.Save(client, id, true, exclusiveAccess)) {
                        locked = true;
                        lockId = e.LockId;

                        return e;
                    }

                    // it has been modified between we loaded and tried to save it
                    e = SessionStateItem.Load(client, id, false);
                    if (e == null)
                        return null;
                }
            }

            locked = true;
            lockAge = DateTime.UtcNow - e.LockTime;
            lockId = e.LockId;
            actions = SessionStateActions.None;

            return acquireLock ? null : e;
        }
Ejemplo n.º 41
0
        public static double SetAndGetEnyim(int numberOfOperations, IMemcachedClient cli)
        {
            var start = DateTime.Now;

            //enyim is synchronous so no need to handle callbacks
            for (var i = 0; i < numberOfOperations; i++)
            {
                var key = "ey" + i;
                var value = key + " value";
                cli.Store(StoreMode.Set, key, value);
            }

            for (var i = 0; i < numberOfOperations; i++)
            {
                var key = "ey" + i;
                var value = cli.Get(key);
            }

            return (DateTime.Now - start).TotalSeconds;
        }
        /// <summary>
        /// Function to initialize the provider
        /// </summary>
        /// <param name="name">Name of the element in the configuration file</param>
        /// <param name="config">Configuration values for the provider from the Web.config file</param>
        public override void Initialize(
            string name,
            NameValueCollection config)
        {
            base.Initialize(name, config);
            _client = ProviderHelper.GetClient(name, config, () => (ICouchbaseClientFactory)new CouchbaseClientFactory(), out _disposeClient);

            ProviderHelper.CheckForUnknownAttributes(config);
        }
Ejemplo n.º 43
0
 public Memcached(IMemcachedSettings memcachedSettings, IMemcachedClientFactory memcachedClientFactory)
 {
     _memcacheSettings = memcachedSettings;
     _memcachedClient = memcachedClientFactory.Create(memcachedSettings);
 }
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            // Initialize the base class
            base.Initialize(name, config);

            // Create our Couchbase client instance
            _client = ProviderHelper.GetClient(name, config, () => (ICouchbaseClientFactory)new CouchbaseClientFactory(), out _disposeClient);

            if (_isFirstTimeInitialization)
            {
                lock (FirstTimeInitializationSync)
                {
                    if (_isFirstTimeInitialization)
                    {
                        var loggingEnabled = ProviderHelper.GetAndRemove(config, "logging", false) ?? "false";
                        _isLoggingEnabled = (String.Compare(loggingEnabled, "true", StringComparison.OrdinalIgnoreCase) == 0);

                        if (_isLoggingEnabled)
                        {
                            // Path where to store NLog logs (effective if useExistedLoggingConfig != "true")
                            var loggingFileName = ProviderHelper.GetAndRemove(config, "loggingFilename", false) ?? "Logs/CouchbaseSessionStateProvider.log";

                            // useExistedLoggingConfig = "true" to use existed application NLog config file
                            // or useExistedLoggingConfig = "false" (or just skip this config) to configure NLog in Couchbase provider and override application settings (if exists)
                            var useExistedLoggingConfigString = ProviderHelper.GetAndRemove(config, "useExistedLoggingConfig", false) ?? "false";
                            var useExistedLoggingConfig = (String.Compare(useExistedLoggingConfigString, "true", StringComparison.OrdinalIgnoreCase) == 0);

                            _logger = SetupLogger(useExistedLoggingConfig, loggingFileName);
                        }

                        // By default use exclusive session access. But allow it to be overridden in the config file
                        var exclusive = ProviderHelper.GetAndRemove(config, "exclusiveAccess", false) ?? "true";
                        _exclusiveAccess = (String.Compare(exclusive, "true", StringComparison.OrdinalIgnoreCase) == 0);

                        // By default do not use compression on session data
                        var compress = ProviderHelper.GetAndRemove(config, "compress", false) ?? "false";
                        _compressData = (String.Compare(compress, "true", StringComparison.OrdinalIgnoreCase) == 0);

                        if (_compressData)
                        {
                            // By default we use lz4 instead of gzip, because it is considered much faster!
                            var compressionTypeString = ProviderHelper.GetAndRemove(config, "compressionType", false) ?? "quicklz";
                            _compressor = CompressorFactory.Create(compressionTypeString);
                        }

                        LogProviderConfiguration();

                        // Make sure no extra attributes are included
                        ProviderHelper.CheckForUnknownAttributes(config);

                        _isFirstTimeInitialization = false;
                    }
                }
            }
        }
 /// <summary>
 /// 初始化一个新的基于Memcached的分布式锁。
 /// </summary>
 /// <param name="client">Memcached客户端。</param>
 public MemcachedDistributedLock(IMemcachedClient client)
 {
     _client = client;
 }
 public static void Remove(IMemcachedClient client, string id)
 {
     client.Remove(DataPrefix + id);
     client.Remove(HeaderPrefix + id);
 }
            public static SessionStateItem Load(string headerPrefix, string dataPrefix, IMemcachedClient client, string id, bool metaOnly)
            {
                // Load the header for the item
                var header = client.GetWithCas<byte[]>(headerPrefix + id);
                if (header.Result == null) {
                    return null;
                }

                // Deserialize the header values
                SessionStateItem entry;
                using (var ms = new MemoryStream(header.Result)) {
                    entry = SessionStateItem.LoadItem(ms);
                }
                entry.HeadCas = header.Cas;

                // Bail early if we are only loading the meta data
                if (metaOnly) {
                    return entry;
                }

                // Load the data for the item
                var data = client.GetWithCas<byte[]>(dataPrefix + id);
                if (data.Result == null) {
                    return null;
                }
                entry.DataCas = data.Cas;

                // Deserialize the data
                using (var ms = new MemoryStream(data.Result)) {
                    using (var br = new BinaryReader(ms)) {
                        entry.Data = SessionStateItemCollection.Deserialize(br);
                    }
                }

                // Return the session entry
                return entry;
            }
Ejemplo n.º 48
0
 static MemcachedClientFactory()
 {
     _client = Create();
 }
 public static SessionStateItem Load(IMemcachedClient client, string id, bool metaOnly)
 {
     return Load(HeaderPrefix, DataPrefix, client, id, metaOnly);
 }
Ejemplo n.º 50
0
        public bool Save(IMemcachedClient client, string id, bool metaOnly, bool useCas, ICompressor compressor, Logger logger)
        {
            var ts = TimeSpan.FromMinutes(Timeout);

            bool retval;

            using (var ms = new MemoryStream())
            {
                // Save the header first
                SaveHeader(ms);

                // Attempt to save the header and fail if the CAS fails
                retval = useCas
                             ? client.Cas(StoreMode.Set, HeaderPrefix + id,
                                          new ArraySegment<byte>(ms.GetBuffer(), 0, (int) ms.Length), ts, HeadCas).Result
                             : client.Store(StoreMode.Set, HeaderPrefix + id,
                                            new ArraySegment<byte>(ms.GetBuffer(), 0, (int) ms.Length), ts);
                if (retval == false)
                {
                    return false;
                }
            }

            // Save the data
            if (!metaOnly)
            {

                byte[] data;

                ArraySegment<byte> arraySegment;

                using (var ms = new MemoryStream())
                {
                    using (var bw = new BinaryWriter(ms))
                    {
                        // Serialize the data
                        Data.Serialize(bw);
                        data = ms.ToArray();
                    }
                }

                if (compressor == null)
                {
                    if (logger != null)
                        logger.Info(string.Format("Save Item with id '{0}' with size {1}", id, data.LongLength));

                    arraySegment = new ArraySegment<byte>(data);
                }
                else
                {
                    var tempdata = compressor.Compress(data);

                    if (logger != null)
                        logger.Info(string.Format("Save Item with id '{0}' that was compressed from {1} bytes to {2} bytes", id, data.LongLength, tempdata.LongLength));

                    arraySegment = new ArraySegment<byte>(tempdata);
                }

                // Attempt to save the data and fail if the CAS fails
                retval = useCas
                             ? client.Cas(StoreMode.Set, DataPrefix + id, arraySegment, ts, DataCas).Result
                             : client.Store(StoreMode.Set, DataPrefix + id, arraySegment, ts);
            }

            // Return the success of the operation
            return retval;
        }
            public static SessionStateItem Load(IMemcachedClient client, string id, bool metaOnly)
            {
                var header = client.GetWithCas<byte[]>(HeaderPrefix + id);
                if (header.Result == null) return null;

                SessionStateItem entry;

                using (var ms = new MemoryStream(header.Result))
                    entry = SessionStateItem.LoadItem(ms);

                if (entry != null) entry.HeadCas = header.Cas;
                if (metaOnly) return entry;

                var data = client.GetWithCas<byte[]>(DataPrefix + id);
                if (data.Result == null) return null;

                using (var ms = new MemoryStream(data.Result))
                using (var br = new BinaryReader(ms))
                    entry.Data = SessionStateItemCollection.Deserialize(br);

                entry.DataCas = data.Cas;

                return entry;
            }
Ejemplo n.º 52
0
 public MemcachedCache()
 {
     client = new MemcachedClient();
 }
            public bool Save(IMemcachedClient client, string id, bool metaOnly, bool useCas)
            {
                using (var ms = new MemoryStream())
                {
                    this.SaveHeader(ms);
                    bool retval;
                    var ts = TimeSpan.FromMinutes(this.Timeout);

                    retval = useCas
                                ? client.Cas(Memcached.StoreMode.Set, HeaderPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, this.HeadCas).Result
                                : client.Store(Memcached.StoreMode.Set, HeaderPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);

                    if (!metaOnly)
                    {
                        ms.Position = 0;

                        using (var bw = new BinaryWriter(ms))
                        {
                            this.Data.Serialize(bw);
                            retval = useCas
                                        ? client.Cas(Memcached.StoreMode.Set, DataPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, this.DataCas).Result
                                        : client.Store(Memcached.StoreMode.Set, DataPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);
                        }
                    }

                    return retval;
                }
            }
Ejemplo n.º 54
0
 public static SessionStateItem Load(IMemcachedClient client, string id, bool metaOnly, ICompressor compressor, Logger logger)
 {
     return Load(HeaderPrefix, DataPrefix, client, id, metaOnly, compressor, logger);
 }
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            // Initialize the base class
            base.Initialize(name, config);

            // Create our Couchbase client instance
            client = ProviderHelper.GetClient(name, config, () => (ICouchbaseClientFactory)new CouchbaseClientFactory(), out disposeClient);

            // By default use exclusive session access. But allow it to be overridden in the config file
            var exclusive = ProviderHelper.GetAndRemove(config, "exclusiveAccess", false) ?? "true";
            exclusiveAccess = (String.Compare(exclusive, "true", true) == 0);

            // Make sure no extra attributes are included
            ProviderHelper.CheckForUnknownAttributes(config);
        }
Ejemplo n.º 56
0
        private static SessionStateItem Load(string headerPrefix, string dataPrefix, IMemcachedClient client, string id, bool metaOnly, ICompressor compressor, Logger logger)
        {
            // Load the header for the item
            var header = client.GetWithCas<byte[]>(headerPrefix + id);
            if (header.Result == null)
            {
                return null;
            }

            // Deserialize the header values
            SessionStateItem entry;
            using (var ms = new MemoryStream(header.Result))
            {
                entry = LoadItem(ms);
            }
            entry.HeadCas = header.Cas;

            // Bail early if we are only loading the meta data
            if (metaOnly)
            {
                return entry;
            }

            // Load the data for the item
            var data = client.GetWithCas<byte[]>(dataPrefix + id);
            if (data.Result == null)
            {
                return null;
            }
            entry.DataCas = data.Cas;

            // Deserialize the data
            if (compressor == null)
            {
                if (logger != null)
                    logger.Info(string.Format("Load data from Session item with id '{0}' with size {1}", id, data.Result.LongLength));

                using (var ms = new MemoryStream(data.Result))
                {
                    using (var br = new BinaryReader(ms))
                    {
                        entry.Data = SessionStateItemCollection.Deserialize(br);
                    }
                }
            }
            else
            {
                using (var input = new MemoryStream(data.Result))
                {
                    var decompressed = compressor.Decompress(input);

                    if (logger != null)
                        logger.Info(string.Format("Load data from Session item with id '{0}' with compessed size {1}. Size after decompression is {2}", id, data.Result.LongLength, decompressed.LongLength));

                    using (var output = new MemoryStream(decompressed))
                    {
                        using (var reader = new BinaryReader(output))
                        {
                            entry.Data = SessionStateItemCollection.Deserialize(reader);
                        }
                    }
                }
            }

            // Return the session entry
            return entry;
        }
 public MemcachedSessionStateStore(IMemcachedClient client)
 {
     _client = client;
 }
            public bool Save(IMemcachedClient client, string id, bool metaOnly, bool useCas)
            {
                using (var ms = new MemoryStream()) {
                    // Save the header first
                    SaveHeader(ms);
                    var ts = TimeSpan.FromMinutes(Timeout);

                    // Attempt to save the header and fail if the CAS fails
                    bool retval = useCas
                        ? client.Cas(StoreMode.Set, HeaderPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, HeadCas).Result
                        : client.Store(StoreMode.Set, HeaderPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);
                    if (retval == false) {
                        return false;
                    }

                    // Save the data
                    if (!metaOnly) {
                        ms.Position = 0;

                        // Serialize the data
                        using (var bw = new BinaryWriter(ms)) {
                            Data.Serialize(bw);

                            // Attempt to save the data and fail if the CAS fails
                            retval = useCas
                                ? client.Cas(StoreMode.Set, DataPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts, DataCas).Result
                                : client.Store(StoreMode.Set, DataPrefix + id, new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length), ts);
                        }
                    }

                    // Return the success of the operation
                    return retval;
                }
            }
 public static void Remove(IMemcachedClient client, string id)
 {
     //lock (padLock)
     //{
         client.Remove(DataPrefix + id);
         client.Remove(HeaderPrefix + id);
     //}
 }
 public void AssertGetSetIntValue(IMemcachedClient cacheClient)
 {
     cacheClient.Set("test:intkey1", 1);
     var value = cacheClient.Get("test:intkey1");
     Assert.That(value, Is.EqualTo(1));
 }