Exemple #1
0
        public RedisRegistryProvider()
        {
            if (SeifApplication.AppEnv.GlobalConfiguration.RegistryConfiguration == null)
                throw new Exception("注册中心配置有误");

            string url = SeifApplication.AppEnv.GlobalConfiguration.RegistryConfiguration.Url;
            string collectionName = "RegistryData";

            var attrs = DictionaryUtils.GetFromConfig(SeifApplication.AppEnv.GlobalConfiguration.RegistryConfiguration.AddtionalFields);
            if (attrs != null && attrs.ContainsKey(AttrKeys.Registry_RedisCollectionName) )
            {
                if (!string.IsNullOrEmpty(attrs[AttrKeys.Registry_RedisCollectionName]))
                {
                    collectionName = attrs[AttrKeys.Registry_RedisCollectionName];
                }
            }

            _redisClient = new RedisClient(url);
            _typedClient = _redisClient.As<RegistryDataInfo>();
            _table = _typedClient.Lists[collectionName];

            _redisSubscription = _redisClient.CreateSubscription();
            _redisSubscription.OnMessage += (channel, msg) =>
            {
                var data = _serializer.Deserialize<ServiceRegistryMetta>(msg);
                if (this.ServiceChanged == null) return;

                this.ServiceChanged(this, new ServiceNotifyEventArgs
                {
                    Data = data
                });
            };
        }
Exemple #2
0
 private void SetKey(IRedisClient client, int count)
 {
     for(int i = 1; i <= count; i++)
     {
         client.Set("key" + i, count);
     }
 }
        private IRedisClient TrackInstance(MethodBase callingMethodType, string method, IRedisClient instance)
        {
            // track
            var frame = new TrackingFrame()
            {
                Id = Guid.NewGuid(),
                Initialised = DateTime.Now,
                ProvidedToInstanceOfType = callingMethodType.DeclaringType,
            };
            lock (this.trackingFrames)
            {
                this.trackingFrames.Add(frame);
            }

            // proxy
            var proxy = new TrackingRedisClientProxy(instance, frame.Id);
            proxy.BeforeInvoke += (sender, args) =>
            {
                if (string.Compare("Dispose", args.MethodInfo.Name, StringComparison.InvariantCultureIgnoreCase) != 0)
                {
                    return;
                }
                lock (this.trackingFrames)
                {
                    this.trackingFrames.Remove(frame);
                }
                var duration = DateTime.Now - frame.Initialised;

                Logger.DebugFormat("{0,18} Disposed {1} released from instance of type {2} checked out for {3}", method, frame.Id, frame.ProvidedToInstanceOfType.FullName, duration);
            };

            Logger.DebugFormat("{0,18} Tracking {1} allocated to instance of type {2}", method, frame.Id, frame.ProvidedToInstanceOfType.FullName);
            return proxy.GetTransparentProxy() as IRedisClient;
        }
Exemple #4
0
 public DAO()
 {
     _client = new RedisClient();
     //Set to 1 to avoid conflicts with any default installs
     //TODO: make configurable
     _client.Db = 1;
 }
 public RedisResultBin2(Uri dbUri, string dbPrefix, string filePrefix)
 {
     this.client = new RedisClient(dbUri);
     artifactListKey = dbPrefix + "/Artifacts";
     fileNameCounterKey = dbPrefix + "/ArtifactCounter";
     this.filePrefix = filePrefix;
 }
 protected static void FlushRedis(IRedisClient redisClient)
 {
     foreach (var key in redisClient.SearchKeys("recommendify-test*"))
     {
         redisClient.Remove(key);
     }
 }
Exemple #7
0
        static RedisHelper()
        {
            try
            {

                RedisClientManagerConfig RedisConfig = new RedisClientManagerConfig();

                RedisConfig.AutoStart = true;
                RedisConfig.MaxReadPoolSize = 60;
                RedisConfig.MaxWritePoolSize = 60;
                var hostWrite = System.Configuration.ConfigurationManager.AppSettings["RedisServerWrite"];
                var arryWrite = hostWrite.Split(';').ToList();
                var hostRead = System.Configuration.ConfigurationManager.AppSettings["RedisServerRead"];
                var arryRead = hostWrite.Split(';').ToList();
                if (arryWrite.Count > 0 && arryRead.Count > 0)
                {
                    prcm = new PooledRedisClientManager(arryWrite, arryRead, RedisConfig);
                    redisClient = prcm.GetClient();
                }
                else
                {
                    throw new Exception("连接服务器失败,请检查配置文件");
                }
            }
            catch
            {
                throw new Exception("连接服务器失败,请检查配置文件");
            }
        }
 /// <summary>
 /// Lock
 /// </summary>
 /// <param name="client"></param>
 /// <param name="globalLockKey"></param>
 /// <param name="acquisitionTimeout">in seconds</param>
 /// <param name="lockTimeout">in seconds</param>
 public DisposableDistributedLock(IRedisClient client, string globalLockKey, int acquisitionTimeout, int lockTimeout)
 {
     myLock = new DistributedLock();
     myClient = client;
     this.globalLockKey = globalLockKey;
     lockState = myLock.Lock(globalLockKey, acquisitionTimeout, lockTimeout, out lockExpire, myClient);
 }
        private static void AssertClientHasHost(IRedisClient client, string hostWithOptionalPort)
        {
            var parts = hostWithOptionalPort.Split(':');
            var port = parts.Length > 1 ? int.Parse(parts[1]) : RedisNativeClient.DefaultPort;

            Assert.That(client.Host, Is.EqualTo(parts[0]));
            Assert.That(client.Port, Is.EqualTo(port));
        }
        public IRedisClient<string> GetClient()
        {
            if (_client == null || _client.IsDisposed || _invalidated)
            _client = new RedisClient(_host, _port);

              _invalidated = false;
              return _client;
        }
Exemple #11
0
 //Método requerido para establecer una conexión con el servicio de Redis
 private static void RedisConnection()
 {
     if (redisClient == null)
     {
         var clientsManager = new PooledRedisClientManager(RedisUri);
         redisClient = clientsManager.GetClient();
     }
 }
Exemple #12
0
 public RedisJobFetcher(
     IRedisClient redis, 
     IEnumerable<string> queueNames, 
     TimeSpan fetchTimeout)
 {
     _redis = redis;
     _queueNames = queueNames.ToList();
     _fetchTimeout = fetchTimeout;
 }
        public RedisTempDataProvider(RedisTempDataProviderOptions options, IRedisClient redis)
        {
            if (options == null) throw new ArgumentNullException("options");
            if (redis == null) throw new ArgumentNullException("redis");

            // Copy so that references can't be modified outside of thsi class.
            this.options = new RedisTempDataProviderOptions(options);
            this.redis = redis;
        }
Exemple #14
0
 public Base(int maxNeighbours, string redisPrefix, IRedisClient redisClient)
 {
     RedisClient = redisClient;
     MaxNeighbours = maxNeighbours;
     RedisPrefix = redisPrefix;
     InputMatrices = new Dictionary<string, InputMatrix>();
     SimilarityMatrix = new SimilarityMatrix(
             new Options {Key = "similarities", MaxNeighbours = MaxNeighbours, RedisPrefix = RedisPrefix},
             redisClient);
 }
Exemple #15
0
        public RedisFetchedJob(IRedisClient redis, string jobId, string queue)
        {
            if (redis == null) throw new ArgumentNullException("redis");
            if (jobId == null) throw new ArgumentNullException("jobId");
            if (queue == null) throw new ArgumentNullException("queue");

            _redis = redis;

            JobId = jobId;
            Queue = queue;
        }
        protected void LoadBasicStrings(IRedisClient redis)
        {
            int A = 'A';
            int Z = 'Z';
            var letters = (Z - A + 1).Times(i => ((char)(i + A)).ToString());
            var numbers = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

            var pos = 0;
            letters.Each(x => redis.Set("string:letters/" + x, x));
            numbers.Each(x => redis.Set("string:numbers/" + pos++, x));
        }
Exemple #17
0
        public static void BeforeRedisScenario()
        {
            GlobalLock.Acquire();
            LogManager.LogFactory = new ConsoleLogFactory();

            Storage = new RedisStorage(RedisHost, RedisDb);
            JobStorage.Current = Storage;

            Client = Storage.PooledManager.GetClient();
            Client.FlushDb();
        }
        public void RedisBackedFurnaceItemsTestsSetUp()
        {
            Client = Substitute.For<IRedisClient>();
            ContentTypes = Substitute.For<IFurnaceContentTypes>();
            ContentType = new ContentType { Name = ContentTypeName, Namespace = ContentTypeNamespace };

            SiteConfiguration = Substitute.For<IFurnaceSiteConfiguration>();
            SiteConfiguration.DefaultSiteCulture.Returns(new CultureInfo("en-AU"));

            Sut = new RedisBackedFurnaceItems(Client, SiteConfiguration, ContentTypes);
        }
        public RedisResultCollection(IRedisClient client, string filePrefix)
        {
            this.client = client;
            this.filePrefix = filePrefix;
            this.testRunInfos = new RedisInfoCollection<TestRun>(client, () => new TestRun());

            if(!Directory.Exists(filePrefix))
                Directory.CreateDirectory(filePrefix);

            ForceUnlock();
        }
Exemple #20
0
 protected virtual void Dispose(bool disposing)
 {
     if (!this._disposed)
     {
         if (disposing)
         {
             Redis.Dispose();
             Redis = null;
         }
     }
     this._disposed = true;
 }
        public override void Execute(IRedisClient client)
        {
            try
            {
                if (VoidReturnCommand != null)
                {
                    VoidReturnCommand(client);

                }
                else if (IntReturnCommand != null)
                {
                    IntReturnCommand(client);

                }
                else if (LongReturnCommand != null)
                {
                    LongReturnCommand(client);

                }
                else if (DoubleReturnCommand != null)
                {
                    DoubleReturnCommand(client);

                }
                else if (BytesReturnCommand != null)
                {
                    BytesReturnCommand(client);

                }
                else if (StringReturnCommand != null)
                {
                    StringReturnCommand(client);

                }
                else if (MultiBytesReturnCommand != null)
                {
                    MultiBytesReturnCommand(client);

                }
                else if (MultiStringReturnCommand != null)
                {
                    MultiStringReturnCommand(client);
                }
                else if (DictionaryStringReturnCommand != null)
                {
                    DictionaryStringReturnCommand(client);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
Exemple #22
0
 public CCMatrix(Options options, IRedisClient redisClient)
 {
     this.options = options;
     this.redisClient = redisClient;
     Matrix = new SparseMatrix(
             new Options
             {
                 Key = string.Format("{0}:{1}", options.Key, "ccmatrix"),
                 MaxNeighbours = options.MaxNeighbours,
                 RedisPrefix = options.RedisPrefix,
                 Weight = options.Weight
             }, redisClient);
 }
Exemple #23
0
        public RobotsCache(CollectorManager cm, string domainSchemeAndServer)
        {
            this.Redis = cm.PRCM.GetClient();
            this.DomainSchemeAndServer = new Uri(domainSchemeAndServer).AbsoluteUri;
            this.RobotID = "urn:domain:robots:data";
            this.RobotLastDateCrawlID = "urn:domain:robots:last-date-crawl";

            if (!TryRetrieveFromCache())
            {
                RetrieveRobots();
                this.Redis.SetEntryInHash(this.RobotID, this.DomainSchemeAndServer,
                    this.RobotsExclusion.JsonSerialize());
                this.Redis.SetEntryInHash(this.RobotLastDateCrawlID,this.DomainSchemeAndServer,
                    DateTime.Now.ToString());
            }
        }
Exemple #24
0
        public ExecOnceOnly(IRedisClientsManager redisManager, string hashKey, string correlationId)
        {
            redisManager.ThrowIfNull("redisManager");
            hashKey.ThrowIfNull("hashKey");

            this.hashKey = hashKey;
            this.correlationId = correlationId;

            if (correlationId != null)
            {
                redis = redisManager.GetClient();
                var exists = !redis.SetEntryInHashIfNotExists(hashKey, correlationId, Flag);
                if (exists)
                    throw HttpError.Conflict("Request {0} has already been processed".Fmt(correlationId));
            }
        }
        public AppStoresWapUIServiceTest()
        {
            _redisServiceMock = new Mock<IRedisService>();
            redisService = _redisServiceMock.Object;

            _redisServiceMock2 = new Mock<IRedisService2>();
            redisService2 = _redisServiceMock2.Object;

            _redisClientMock = new Mock<IRedisClient>();
            redisClient = _redisClientMock.Object;

            _appStoreUIServiceMock = new Mock<IAppStoreUIService>();
            appStoreUIService = _appStoreUIServiceMock.Object;

            _logServiceMock = new Mock<ILogger>();
            logService = _logServiceMock.Object;

            _fileServiceMock = new Mock<IFileService>();
            fileService = _fileServiceMock.Object;

            _fullTextSearchServiceMock = new Mock<IFullTextSearchService>();
            fullTextSearchService = _fullTextSearchServiceMock.Object;

            _requestRepoMock = new Mock<IRequestRepository>();
            requestRepo = _requestRepoMock.Object;

            appStoreUIRealService = new AppStoreUIService(fs, redisReal);

            sesionRepository = new Mock<ISessionRepository>();
            sesionRepositoryReal = new SessionRepository();

            cookieServiceReal =new CookieService();
            cookieService = new Mock<ICookieService>();

            appStoreServiceReal = new AppStoreService(fs, redisReal, appStoreUIRealService, new FullTextSearchService(redisReal),new IMEICacheService(redisReal));
            appStoreServiceReal.RedisService2 = new RedisService2();
            appStoreService = new AppStoreService(fs, redisService, appStoreUIRealService, new FullTextSearchService(redisService), new IMEICacheService(redisReal));
            appStoreService.RedisService2 = redisService2;

            appStoresWapUIServiceReal = new AppStoresWapUISerivces(appStoreUIRealService, redisReal, appStoreServiceReal, sesionRepositoryReal, cookieServiceReal, new FullTextSearchService(redisReal));
            appStoresWapUIServiceReal.RedisService2 = new RedisService2();
            appStoresWapUIService = new AppStoresWapUISerivces(appStoreUIService, redisService, appStoreService, sesionRepository.Object, cookieService.Object, fullTextSearchService);

            appStoresWapUIService.RedisService2 = redisService2;
            Bootstrapper.Start();
            redisReal.FlushAll();
        }
        protected void LoadDifferentKeyTypes(IRedisClient client)
        {
            var items = new List<string> { "one", "two", "three", "four" };
            var map = new Dictionary<string, string> {
                        {"A","one"},
                        {"B","two"},
                        {"C","three"},
                        {"D","four"},
                    };

            items.ForEach(x => Redis.Set("urn:testkeytypes:string:" + x, x));
            items.ForEach(x => Redis.AddItemToList("urn:testkeytypes:list", x));
            items.ForEach(x => Redis.AddItemToSet("urn:testkeytypes:set", x));
            var i = 0;
            items.ForEach(x => Redis.AddItemToSortedSet("urn:testkeytypes:zset", x, i++));
            Redis.SetRangeInHash("urn:testkeytypes:hash", map);
        }
Exemple #27
0
        Collector(
            CollectorManager cm,
            string link, string backlink, string text, string rel, string kind,
            bool crawlChildLinks, bool poolChildLinksFound)
        {
            this.CM = cm;
            this.Redis = cm.PRCM.GetClient();
            this.Link = link;
            this.CurrentBacklink = LinkParser.Validate(backlink, string.Empty);
            this.LinkInfo = new LinkInfo(cm, this.Link, this.CurrentBacklink, text, rel, kind);
            if (!this.LinkInfo.LinkExcludedInRobots)
            {
                SaveLink();

                if (crawlChildLinks)
                    CrawlChildLinks();
            }
        }
		private static void UseClient(IRedisClient client, int clientNo)
		{
			var host = "";

			try
			{
				host = client.Host;

				Debug.WriteLine(String.Format("Client '{0}' is using '{1}'", clientNo, client.Host));
				var differentDbs = new[] { 1, 0, 2 };

				foreach (var db in differentDbs)
				{
					client.Db = db;

					var testClientKey = "test:" + host + ":" + clientNo;
					client.SetEntry(testClientKey, testData);
					var result = client.GetValue(testClientKey) ?? "";
					LogResult(db, testClientKey, result);

					var testClientSetKey = "test+set:" + host + ":" + clientNo;
					client.AddItemToSet(testClientSetKey, testData);
					var resultSet = client.GetAllItemsFromSet(testClientSetKey);
					LogResult(db, testClientKey, resultSet.ToList().FirstOrDefault());

					var testClientListKey = "test+list:" + host + ":" + clientNo;
					client.AddItemToList(testClientListKey, testData);
					var resultList = client.GetAllItemsFromList(testClientListKey);
					LogResult(db, testClientKey, resultList.FirstOrDefault());

				}
			}
			catch (NullReferenceException ex)
			{
				Debug.WriteLine("NullReferenceException StackTrace: \n" + ex.StackTrace);
                Assert.Fail("NullReferenceException");
            }
			catch (Exception ex)
			{
				Debug.WriteLine(String.Format("\t[ERROR@{0}]: {1} => {2}",
					host, ex.GetType().Name, ex));
                Assert.Fail("Exception");
			}
		}
Exemple #29
0
        private void Connect()
        {
            while (_c == null)
            {
                if (_uris.Count == 0)
                {
                    throw new DisqueConnectionException("Could not connect to any of the provided nodes");
                }
                int index = _random.Next(_uris.Count);

                try
                {
                    Uri uri = _uris[index];
                    _c = new RedisClient(uri.Host, uri.Port);
                }
                catch (Exception e)
                {
                    _uris.RemoveAt(index);
                }
            }
        }
        public AppStoresServiceTest()
        {
            _redisServiceMock = new Mock<IRedisService>();
            redisService = _redisServiceMock.Object;

            _redisServiceMock2 = new Mock<IRedisService2>();
            redisService2 = _redisServiceMock2.Object;

            _redisClientMock = new Mock<IRedisClient>();
            redisClient = _redisClientMock.Object;

            _appStoreUIServiceMock = new Mock<IAppStoreUIService>();
            appStoreUIService = _appStoreUIServiceMock.Object;

            _fileServiceMock = new Mock<IFileService>();
            fileService = _fileServiceMock.Object;

            _logServiceMock = new Mock<ILogger>();
            logService = _logServiceMock.Object;

            _requestRepoMock = new Mock<IRequestRepository>();
            requestRepo = _requestRepoMock.Object;

            _fullTextSearchServiceMock = new Mock<IFullTextSearchService>();
            fullTextSearchService = _fullTextSearchServiceMock.Object;
            _imeiCacheServiceMock = new Mock<IIMEICacheService>();
            imeiCacheService = _imeiCacheServiceMock.Object;

            appStoreUIRealService = new AppStoreUIService(fs, redis);
            appStoreUIRealService.RedisService2 = redis2;
            appStoreRealService = new AppStoreService(fs, redis, appStoreUIRealService, fullTextSearchService, imeiCacheService);
            appStoreRealService.RedisService2 = redis2;

            appStoreMockService = new AppStoreService(_fileServiceMock.Object, _redisServiceMock.Object,
                _appStoreUIServiceMock.Object, _fullTextSearchServiceMock.Object,_imeiCacheServiceMock.Object);
            appStoreMockService.RedisService2 = redisService2;
            redis.FlushAll();

            EntityMapping.Config();
        }
 public RedisClientFacade(IRedisClient redisClient)
 {
     this.redisClient = redisClient;
 }
        public static List <string> GetSlowLog(this IRedisClient client)
        {
            var sha1 = client.GetSha1(slow_log_command_text);

            return(client.ExecLuaShaAsList(sha1));
        }
Exemple #33
0
 /// <summary>
 /// 计算给定的一个或多个有序集的权限值并集,并将该并集(结果集)储存到 <paramref name="destination"/> 。
 /// </summary>
 /// <param name="client">Redis 客户端。</param>
 /// <param name="destination">目标有序集的键名。如果有序集已存在,则会覆盖。</param>
 /// <param name="keyWeights">有序集键名和乘法因子的字典。</param>
 /// <param name="aggregate">聚合的方式。</param>
 /// <returns>保存到 <paramref name="destination"/> 的结果集的基数。</returns>
 public static long ZUnionStore(this IRedisClient client, string destination, RedisWeightDictionary keyWeights, RedisAggregate?aggregate = null)
 {
     return(ZStore("ZUNIONSTORE", client, destination, keyWeights, aggregate));
 }
Exemple #34
0
 public EbProductsController(IServiceClient _client, IRedisClient _redis) : base(_client, _redis)
 {
 }
Exemple #35
0
 /// <summary>
 /// 有序集 <paramref name="key"/> 增量地迭代(incrementally iterate)一集元素(a collection of elements)。
 /// </summary>
 /// <param name="client">Redis 客户端。</param>
 /// <param name="key">有序集的键名</param>
 /// <param name="cursor">起始游标,0 表示开始一次新的迭代。</param>
 /// <param name="pattern">给定模式相匹配的元素。匹配语法可以参考 <seealso cref="System.RedisKeyExtensions.Keys(IRedisClient, String)"/> 方法。</param>
 /// <param name="count">每次迭代所返回的元素数量。</param>
 /// <returns>支持迭代的枚举。</returns>
 public static IEnumerable <RedisScoreItem> ZScan(this IRedisClient client, string key, long cursor = 0, string pattern = null, long count = 10)
 {
     return(new RedisScan <RedisScoreItem>(client, "ZSCAN", key, cursor, pattern, count
                                           , (command, args) => new RedisItem <RedisScoreItem>(false, command, args), 2));
 }
Exemple #36
0
 public RedisTests()
 {
     _redisClient = GetRequiredService<IRedisClient>();
 }
 public static int RemoveKeysByPattern(this IRedisClient client, string pattern)
 {
     return((int)client.ExecLuaAsInt(Script.RemoveKeysByPatternScript, pattern));
 }
Exemple #38
0
 public RedisConnection(IRedisClient redis)
 {
     Redis = redis;
 }
 public ObjectDashboardViewComponent(IServiceClient _client, IRedisClient _redis)
 {
     this.ServiceClient = _client as JsonServiceClient;
     this.Redis         = _redis as RedisClient;
 }
        /// <summary>
        /// 获取多个hash中的相同项的值
        /// </summary>
        /// <param name="redis"></param>
        /// <param name="keyInHash">比如房间id</param>
        /// <param name="hashKeys">比如r:gift:exp,r:live:exp</param>
        /// <returns></returns>
        public static List <string> GetMiltiHashValueWithSameKey(this IRedisClient redis, string keyInHash, params string[] hashKeys)
        {
            var sha1 = redis.GetSha1(get_multi_hash_value_with_same_key);

            return(redis.ExecLuaShaAsList(sha1, hashKeys, new[] { keyInHash }));
        }
    /// <summary>
    /// 閫氳繃PipeLine鎵归噺鑾峰彇鏁版嵁,Hash,Set,ZSet鏆備笉鍙敤锛屽緟瑙e喅
    /// </summary>
    /// <param name="keys"></param>
    /// <param name="dataType"></param>
    /// <param name="poolType"></param>
    /// <returns></returns>
    public static Dictionary <string, object> GetWithPipeLine(List <string> keys, RedisDataType dataType, RedisPoolType poolType)
    {
        Dictionary <string, object> result = new Dictionary <string, object>();
        Dictionary <string, Dictionary <string, string> > r1 = new Dictionary <string, Dictionary <string, string> >();

        PooledRedisClientManager pool  = GetRedisPool(poolType);
        IRedisClient             redis = pool.GetReadOnlyClient();
        var pipe = redis.CreatePipeline();

        try
        {
            for (int i = 0; i < keys.Count; i++)
            {
                string key = keys[i];
                switch (dataType)
                {
                case RedisDataType.Simple:
                    pipe.QueueCommand(r => r.GetValue(key), b => result.Add(key, b));
                    break;

                case RedisDataType.List:
                    pipe.QueueCommand(r => r.GetAllItemsFromList(key), b => result.Add(key, b));
                    break;

                case RedisDataType.Hash:
                    pipe.QueueCommand(r => { r.GetAllEntriesFromHash(key); return(new byte[] { }); }, b => result.Add(key, (Object)b));
                    break;

                case RedisDataType.Set:
                    //pipe.QueueCommand(r => r.GetAllItemsFromSet(key), b => result.Add(key, b));
                    break;

                case RedisDataType.ZSet:
                    //pipe.QueueCommand(r => r.GetAllWithScoresFromSortedSet(key), b => result.Add(key, b));
                    break;

                case RedisDataType.Exists:
                    pipe.QueueCommand(r => r.ContainsKey(key), b => result.Add(key, b));
                    break;

                default:
                    break;
                }
            }
            pipe.Flush();
        }
        catch { throw; }
        finally
        {
            if (pipe != null)
            {
                pipe.Dispose();
            }
            if (redis != null)
            {
                redis.Dispose();
            }
        }

        return(result);
    }
        /// <summary>
        /// 获取多个hash中的数字项的值的相加数
        /// </summary>
        /// <param name="redis"></param>
        /// <param name="keyInHash">比如房间id</param>
        /// <param name="hashKeys">比如r:gift:exp,r:live:exp</param>
        /// <returns></returns>
        public static long SumMiltiHashNumberValueWithSameKey(this IRedisClient redis, string keyInHash, params string[] hashKeys)
        {
            var sha1 = redis.GetSha1(sum_multi_hash_number_value_with_same_key);

            return(redis.ExecLuaShaAsInt(sha1, hashKeys, new[] { keyInHash }));
        }
Exemple #43
0
 static RedisBase()
 {
     redisClient = RedisProxyAgent.GetClient();
 }
 public static string GetString(this IRedisClient client)
 {
     return(string.Format("{0}:{1}", client.Host, client.Port));
 }
Exemple #45
0
 public DVController(IServiceClient _ssclient, IRedisClient _redis) : base(_ssclient, _redis)
 {
 }
 public RecordEventsService(IConfiguration configuration, IRedisClient redisClient)
 {
     _redis      = redisClient;
     ChannelName = configuration["redis:channel"];
 }
        /// <summary>
        /// acquire distributed, non-reentrant lock on key
        /// </summary>
        /// <param name="key">global key for this lock</param>
        /// <param name="acquisitionTimeout">timeout for acquiring lock</param>
        /// <param name="lockTimeout">timeout for lock, in seconds (stored as value against lock key) </param>
        /// <param name="client"></param>
        /// <param name="lockExpire"></param>
        public virtual long Lock(string key, int acquisitionTimeout, int lockTimeout, out long lockExpire, IRedisClient client)
        {
            lockExpire = 0;

            // cannot lock on a null key
            if (key == null)
            {
                return(LOCK_NOT_ACQUIRED);
            }

            const int sleepIfLockSet = 200;

            acquisitionTimeout *= 1000;             //convert to ms
            int tryCount = (acquisitionTimeout / sleepIfLockSet) + 1;

            var ts            = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
            var newLockExpire = CalculateLockExpire(ts, lockTimeout);

            var localClient = (RedisClient)client;
            int wasSet      = localClient.SetNX(key, BitConverter.GetBytes(newLockExpire));
            int totalTime   = 0;

            while (wasSet == LOCK_NOT_ACQUIRED && totalTime < acquisitionTimeout)
            {
                int count = 0;
                while (wasSet == 0 && count < tryCount && totalTime < acquisitionTimeout)
                {
                    System.Threading.Thread.Sleep(sleepIfLockSet);
                    totalTime    += sleepIfLockSet;
                    ts            = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
                    newLockExpire = CalculateLockExpire(ts, lockTimeout);
                    wasSet        = localClient.SetNX(key, BitConverter.GetBytes(newLockExpire));
                    count++;
                }
                // acquired lock!
                if (wasSet != LOCK_NOT_ACQUIRED)
                {
                    break;
                }

                // handle possibliity of crashed client still holding the lock
                using (var pipe = localClient.CreatePipeline())
                {
                    long lockValue = 0;
                    pipe.QueueCommand(r => ((RedisNativeClient)r).Watch(key));
                    pipe.QueueCommand(r => ((RedisNativeClient)r).Get(key), x => lockValue = (x != null) ? BitConverter.ToInt64(x, 0) : 0);
                    pipe.Flush();

                    // if lock value is 0 (key is empty), or expired, then we can try to acquire it
                    ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
                    if (lockValue < ts.TotalSeconds)
                    {
                        ts            = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
                        newLockExpire = CalculateLockExpire(ts, lockTimeout);
                        using (var trans = localClient.CreateTransaction())
                        {
                            var expire = newLockExpire;
                            trans.QueueCommand(r => ((RedisNativeClient)r).Set(key, BitConverter.GetBytes(expire)));
                            if (trans.Commit())
                            {
                                wasSet = LOCK_RECOVERED;                                 //recovered lock!
                            }
                        }
                    }
                    else
                    {
                        localClient.UnWatch();
                    }
                }
                if (wasSet != LOCK_NOT_ACQUIRED)
                {
                    break;
                }
                System.Threading.Thread.Sleep(sleepIfLockSet);
                totalTime += sleepIfLockSet;
            }
            if (wasSet != LOCK_NOT_ACQUIRED)
            {
                lockExpire = newLockExpire;
            }
            return(wasSet);
        }
Exemple #48
0
 public DevController(IServiceClient _client, IRedisClient _redis) : base(_client, _redis)
 {
 }