Exemple #1
0
        public void ClientKillTest()
        {
            var reply1 = "+OK\r\n";
            var reply2 = ":1\r\n";
            using (var mock = new FakeRedisSocket(reply1, reply2, reply2, reply2, reply2, reply2))
            using (var redis = new RedisClient(mock, new DnsEndPoint("fakehost", 9999)))
            {
                Assert.AreEqual("OK", redis.ClientKill("1.1.1.1", 9999));
                Assert.AreEqual("*4\r\n$6\r\nCLIENT\r\n$4\r\nKILL\r\n$7\r\n1.1.1.1\r\n$4\r\n9999\r\n", mock.GetMessage());

                Assert.AreEqual(1, redis.ClientKill(addr: "1.1.1.1:9999"));
                Assert.AreEqual("*4\r\n$6\r\nCLIENT\r\n$4\r\nKILL\r\n$4\r\nADDR\r\n$12\r\n1.1.1.1:9999\r\n", mock.GetMessage());

                Assert.AreEqual(1, redis.ClientKill(id: "123"));
                Assert.AreEqual("*4\r\n$6\r\nCLIENT\r\n$4\r\nKILL\r\n$2\r\nID\r\n$3\r\n123\r\n", mock.GetMessage());

                Assert.AreEqual(1, redis.ClientKill(type: "normal"));
                Assert.AreEqual("*4\r\n$6\r\nCLIENT\r\n$4\r\nKILL\r\n$4\r\nTYPE\r\n$6\r\nnormal\r\n", mock.GetMessage());

                Assert.AreEqual(1, redis.ClientKill(skipMe: true));
                Assert.AreEqual("*4\r\n$6\r\nCLIENT\r\n$4\r\nKILL\r\n$6\r\nSKIPME\r\n$3\r\nyes\r\n", mock.GetMessage());

                Assert.AreEqual(1, redis.ClientKill(skipMe: false));
                Assert.AreEqual("*4\r\n$6\r\nCLIENT\r\n$4\r\nKILL\r\n$6\r\nSKIPME\r\n$2\r\nno\r\n", mock.GetMessage());
            }
        }
        public void Does_retry_failed_commands()
        {
            //LogManager.LogFactory = new ConsoleLogFactory(debugEnabled: true);

            RedisStats.Reset();

            var redisCtrl = new RedisClient(RedisConfig.DefaultHost);
            redisCtrl.FlushAll();
            redisCtrl.SetClient("redisCtrl");

            var redis = new RedisClient(RedisConfig.DefaultHost);
            redis.SetClient("redisRetry");

            var clientInfo = redisCtrl.GetClientsInfo();
            var redisId = clientInfo.First(m => m["name"] == "redisRetry")["id"];
            Assert.That(redisId.Length, Is.GreaterThan(0));

            Assert.That(redis.IncrementValue("retryCounter"), Is.EqualTo(1));

            redis.OnBeforeFlush = () =>
            {
                redisCtrl.KillClients(withId: redisId);
            };

            Assert.That(redis.IncrementValue("retryCounter"), Is.EqualTo(2));
            Assert.That(redis.Get<int>("retryCounter"), Is.EqualTo(2));

            Assert.That(RedisStats.TotalRetryCount, Is.EqualTo(1));
            Assert.That(RedisStats.TotalRetrySuccess, Is.EqualTo(1));
            Assert.That(RedisStats.TotalRetryTimedout, Is.EqualTo(0));
        }
 private void UseClientAsync(RedisClient client, int clientNo)
 {
     lock (this)
     {
         UseClient(client, clientNo);
     }
 }
        public async void TestSendAndReceive()
        {
            var resolver = new DependencyResolver();

            using (var server = new RedisServer(new RedisConnection(RedisHost, RedisPort, RedisPassword), ServerQueue, new ServiceFactory(resolver)))
            {
                server.Listen();

                using (var client = new RedisClient(new RedisConnection(RedisHost, RedisPort, RedisPassword), ClientQueue, ServerQueue))
                {
                    var clientFactory = new ServiceProxy.ServiceClientFactory(client);

                    var serviceClient = clientFactory.CreateServiceClient<ITestService2>();

                    Assert.That(serviceClient.GetPerson(1), Is.Not.Null);

                    var persons = await serviceClient.ListPersonsAsync(5);
                    Assert.That(persons, Is.Not.Null);
                    Assert.AreEqual(5, persons.Count());

                    var nullCollection = await serviceClient.ListPersonsAsync(-1);
                    Assert.IsNull(nullCollection);

                    var nullObject = serviceClient.GetPerson(-1);
                    Assert.IsNull(nullObject);
                }
            }
        }
		private static void UseClient(RedisClient client, int clientNo)
		{
			var host = "";

			try
			{
				host = client.Host;

				Log("Client '{0}' is using '{1}'", clientNo, client.Host);

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

				Log("\t{0} => {1} len {2} {3} len", testClientKey,
					testData.Length, testData.Length == result.Length ? "==" : "!=", result.Length);

			}
			catch (NullReferenceException ex)
			{
				Console.WriteLine("NullReferenceException StackTrace: \n" + ex.StackTrace);
			}
			catch (Exception ex)
			{
				Console.WriteLine("\t[ERROR@{0}]: {1} => {2}",
					host, ex.GetType().Name, ex.Message);
			}
		}
        public void Can_support_64_threads_using_the_client_simultaneously()
        {
            var before = Stopwatch.GetTimestamp();

            const int noOfConcurrentClients = 64; //WaitHandle.WaitAll limit is <= 64

#if NETCORE
            List<Task> tasks = new List<Task>();
#else
            var clientAsyncResults = new List<IAsyncResult>();
#endif             
            using (var redisClient = new RedisClient(TestConfig.SingleHost))
            {
                for (var i = 0; i < noOfConcurrentClients; i++)
                {
                    var clientNo = i;
                    var action = (Action)(() => UseClientAsync(redisClient, clientNo));
#if NETCORE
                    tasks.Add(Task.Run(action));
#else                                       
                    clientAsyncResults.Add(action.BeginInvoke(null, null));
#endif
                }
            }
#if NETCORE
            Task.WaitAll(tasks.ToArray());
#else            
            WaitHandle.WaitAll(clientAsyncResults.ConvertAll(x => x.AsyncWaitHandle).ToArray());
#endif
            Debug.WriteLine(String.Format("Time Taken: {0}", (Stopwatch.GetTimestamp() - before) / 1000));
        }
Exemple #7
0
 private IRedisClient CreateClient(bool flushAll = true)
 {
     var client = new RedisClient(6379);
     if(flushAll)
         client.FlushAll();
     return client;
 }
 public void Connect()
 {
     // note: defaults to 127.0.0.1:6379
     using(dynamic client = new RedisClient())
     {
     }
 }
 public void Allows_access_of_6000_operations()
 {
     using (var client = new RedisClient(TestConfig.SingleHost))
     {
         6000.Times(() => client.Get("any key"));
     }
 }
 public void Save(EngineInfo info)
 {
     var client = new RedisClient();
     var key = new EngineKeys ().GetInfoKey (info.Id);
     var json = info.ToJson ();
     client.Set(key, json);
 }
        static RedisCacheService()
        {
            Redis = new RedisClient("localhost");
            string ping = Redis.Ping();

            JsConfig.DateHandler = DateHandler.ISO8601;
        }
        public void Does_Timeout_with_repeated_SocketException()
        {
            RedisConfig.Reset();
            RedisConfig.DefaultRetryTimeout = 100;

            var redis = new RedisClient(RedisConfig.DefaultHost);
            redis.FlushAll();

            Assert.That(redis.IncrementValue("retryCounter"), Is.EqualTo(1));

            redis.OnBeforeFlush = () =>
            {
                throw new SocketException();
            };

            try
            {
                redis.IncrementValue("retryCounter");
                Assert.Fail("Should throw");
            }
            catch (RedisException ex)
            {
                Assert.That(ex.Message, Is.StringStarting("Exceeded timeout"));

                redis.OnBeforeFlush = null;
                Assert.That(redis.Get<int>("retryCounter"), Is.EqualTo(1));

                Assert.That(RedisStats.TotalRetryCount, Is.GreaterThan(1));
                Assert.That(RedisStats.TotalRetrySuccess, Is.EqualTo(0));
                Assert.That(RedisStats.TotalRetryTimedout, Is.EqualTo(1));
            }

            RedisConfig.Reset();
        }
		public void Acquiring_lock_with_timeout()
		{
			var redisClient = new RedisClient(TestConfig.SingleHost);

			//Initialize and set counter to '1'
			redisClient.IncrementValue("atomic-counter"); 
			
			//Acquire lock and never release it
			redisClient.AcquireLock("testlock");

			var waitFor = TimeSpan.FromSeconds(2);
			var now = DateTime.Now;

			try
			{
				using (var newClient = new RedisClient(TestConfig.SingleHost))
				{
					//Attempt to acquire a lock with a 2 second timeout
					using (newClient.AcquireLock("testlock", waitFor))
					{
						//If lock was acquired this would be incremented to '2'
						redisClient.IncrementValue("atomic-counter"); 
					}
				}
			}
			catch (TimeoutException tex)
			{
				var timeTaken = DateTime.Now - now;
				Debug.WriteLine(String.Format("After '{0}', Received TimeoutException: '{1}'", timeTaken, tex.Message));

				var counter = redisClient.Get<int>("atomic-counter");
				Debug.WriteLine(String.Format("atomic-counter remains at '{0}'", counter));
			}
		}
 public int ReadPopulationCount(Guid tileId)
 {
     var client = new RedisClient();
     var key = new PeopleKeys ().GetPopulationKey (tileId);
     var value = client.Get (key);
     return Convert.ToInt32(value);
 }
        /// <summary>
        /// create <see cref="RedisClient"/>
        /// </summary>
        /// <param name="configFile"></param>
        /// <param name="endpointName"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">endpointName is null or empty.</exception>
        static public RedisClient Create(string configFile, string endpointName)
        {
            if (string.IsNullOrEmpty(endpointName)) throw new ArgumentNullException("endpointName");

            Config.RedisConfigSection config = null;
            if (string.IsNullOrEmpty(configFile)) config = ConfigurationManager.GetSection("redis") as Config.RedisConfigSection;
            else
            {
                config = ConfigurationManager.OpenMappedExeConfiguration(
                    new ExeConfigurationFileMap { ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFile) },
                    ConfigurationUserLevel.None).GetSection("redis") as Config.RedisConfigSection;
            }

            var clientConfig = config.Clients.Get(endpointName);

            var redisClient = new RedisClient(clientConfig.SocketBufferSize,
                clientConfig.MessageBufferSize,
                clientConfig.MillisecondsSendTimeout,
                clientConfig.MillisecondsReceiveTimeout);

            foreach (Config.ServerConfig server in clientConfig.Servers)
                redisClient.TryRegisterEndPoint(string.Concat(server.Host, server.Port), new[] { new IPEndPoint(IPAddress.Parse(server.Host), server.Port) });

            return redisClient;
        }
Exemple #16
0
        public void ClientKillTest()
        {
            var reply1 = "+OK\r\n";
            var reply2 = ":1\r\n";
            using(var mock = new MockConnector("localhost", 9999, reply1, reply2, reply2, reply2, reply2, reply2))
            using(var redis = new RedisClient(mock))
            {
                Assert.True(redis.ClientKill("1.1.1.1", 9999));
                Assert.Equal("*3\r\n$6\r\nCLIENT\r\n$4\r\nKILL\r\n$12\r\n1.1.1.1:9999\r\n", mock.GetMessage());

                Assert.Equal(1, redis.ClientKill(addr: "1.1.1.1:9999"));
                Assert.Equal("*4\r\n$6\r\nCLIENT\r\n$4\r\nKILL\r\n$4\r\nADDR\r\n$12\r\n1.1.1.1:9999\r\n", mock.GetMessage());

                Assert.Equal(1, redis.ClientKill(id: "123"));
                Assert.Equal("*4\r\n$6\r\nCLIENT\r\n$4\r\nKILL\r\n$2\r\nID\r\n$3\r\n123\r\n", mock.GetMessage());

                Assert.Equal(1, redis.ClientKill(type: "normal"));
                Assert.Equal("*4\r\n$6\r\nCLIENT\r\n$4\r\nKILL\r\n$4\r\nTYPE\r\n$6\r\nnormal\r\n", mock.GetMessage());

                Assert.Equal(1, redis.ClientKill(skipMe: true));
                Assert.Equal("*4\r\n$6\r\nCLIENT\r\n$4\r\nKILL\r\n$6\r\nSKIPME\r\n$3\r\nyes\r\n", mock.GetMessage());

                Assert.Equal(1, redis.ClientKill(skipMe: false));
                Assert.Equal("*4\r\n$6\r\nCLIENT\r\n$4\r\nKILL\r\n$6\r\nSKIPME\r\n$2\r\nno\r\n", mock.GetMessage());
            }
        }
Exemple #17
0
        public string ValidateTransfer(string sourceAppId, string userId, string transferId, string transferToken)
        {
            var red = new RedisClient<string>();
            var result = red.Get("transfertoken:" + transferId);
            if (!string.IsNullOrEmpty(result))
            {
                var redResult = red.Del("transfertoken:" + transferId);

                var redapp = new RedisClient<AppRegistry>();
                redapp.Select(1);
                var app = redapp.Get(HttpContext.Current.Items["AppId"] as string);

                var str = "UserId=" + userId + "&TransferId=" + transferId + "&Salt=" + app.AppSecret ;
                str = Hash.GetHash(str, Hash.HashType.SHA256);

                if (transferToken != str)
                {
                    throw new FaultException<UnauthorizedAccessException>(new UnauthorizedAccessException("token yanlış"));
                }

                string sessionguid = Guid.NewGuid().ToString();
                var redis = new RedisClient<Common.SessionRegistry>();
                var appId = HttpContext.Current.Items["AppId"] as string;
                redis.Set(sessionguid, new SessionRegistry() { SessionCookie = sessionguid, AppId = appId, UserId = userId });
                return sessionguid;
            }
            return null;
        }
Exemple #18
0
        public void TestHGetAll()
        {
            using(var mock = new MockConnector("localhost", 9999, "*2\r\n$6\r\nfield1\r\n$5\r\ntest1\r\n"))
            using(var redis = new RedisClient(mock))
            {
                var response = redis.HGetAll("test");
                Assert.Equal(1, response.Length);
                Assert.Equal("field1", response[0].Field);
                Assert.Equal("test1", (string)response[0].Value);
                Assert.Equal("*2\r\n$7\r\nHGETALL\r\n$4\r\ntest\r\n", mock.GetMessage());
            }

            this.RealCall(redis =>
            {
                redis.HSet("test", "field1", "value1");
                redis.HSet("test", "field2", "value2");

                var response = redis.HGetAll("test");
                Assert.Equal(2, response.Length);
                for(int i = 0; i < 2; i++)
                {
                    Assert.Equal("field" + (i + 1), response[i].Field);
                    Assert.Equal("value" + (i + 1), (string)response[i].Value);
                }
            });
        }
		public void Working_with_int_values()
		{
			const string intKey = "intkey";
			const int intValue = 1;

			//STORING AN INT USING THE BASIC CLIENT
			using (var redisClient = new RedisClient(TestConfig.SingleHost))
			{
				redisClient.SetEntry(intKey, intValue.ToString());
				string strGetIntValue = redisClient.GetValue(intKey);
				int toIntValue = int.Parse(strGetIntValue);

				Assert.That(toIntValue, Is.EqualTo(intValue));
			}

			//STORING AN INT USING THE GENERIC CLIENT
			using (var redisClient = new RedisClient(TestConfig.SingleHost))
			{
				//Create a generic client that treats all values as ints:
				IRedisTypedClient<int> intRedis = redisClient.GetTypedClient<int>();

				intRedis.SetEntry(intKey, intValue);
				var toIntValue = intRedis.GetValue(intKey);

				Assert.That(toIntValue, Is.EqualTo(intValue));
			}
		}
 public bool HasMessage()
 {
     using (var redisClient = new RedisClient())
     {
         return redisClient.ContainsKey(string.Format("{0}:{1}", _address.Machine, _address.Queue));
     }
 }
        public void Does_retry_failed_commands_auth()
        {
            // -> Redis must have "requirepass testpassword" in config
            var connstr = "testpassword@localhost";
            RedisStats.Reset();

            var redisCtrl = new RedisClient(connstr); //RedisConfig.DefaultHost
            redisCtrl.FlushAll();
            redisCtrl.SetClient("redisCtrl");

            var redis = new RedisClient(connstr);
            redis.SetClient("redisRetry");

            var clientInfo = redisCtrl.GetClientsInfo();
            var redisId = clientInfo.First(m => m["name"] == "redisRetry")["id"];
            Assert.That(redisId.Length, Is.GreaterThan(0));

            Assert.That(redis.IncrementValue("retryCounter"), Is.EqualTo(1));

            redis.OnBeforeFlush = () =>
            {
                redisCtrl.KillClients(withId: redisId);
            };

            Assert.That(redis.IncrementValue("retryCounter"), Is.EqualTo(2));
            Assert.That(redis.Get<int>("retryCounter"), Is.EqualTo(2));

            Assert.That(RedisStats.TotalRetryCount, Is.EqualTo(1));
            Assert.That(RedisStats.TotalRetrySuccess, Is.EqualTo(1));
            Assert.That(RedisStats.TotalRetryTimedout, Is.EqualTo(0));
        }
		public virtual void OnBeforeEachTest()
		{
			if (Redis != null) Redis.Dispose();
			Redis = new RedisClient(TestConfig.SingleHost);
		    Redis.NamespacePrefix = "RedisTypedClientTests:";
			RedisTyped = Redis.As<CacheRecord>();
		}
 public void Send(TransportMessage message, Address address)
 {
    using(var redisClient = new RedisClient())
    {
        redisClient.Add(string.Format("{0}:{1}", address.Machine, address.Queue), message);
    }
 }
        public override void Run()
        {
            var client = new RedisClient<int>(RedisSettings.Default);

              // NOTE: This is for demonstartion purpose only
              //       real-world code should just use MGet and MSet which are made
              //       specifically for tasks like this

              // initialize 1000 counters with a number
              var success = client
            .Pipeline(c =>
            {
              var rand = new Random();
              for (var i = 0; i < CounterAmount; i++)
            c.Set("counter" + i.ToString(), rand.Next(100, 999));
            })
            .Cast<bool>()
            .All(b => b);

              WriteLine(success ?
            "All counters set to [100,999]." :
            "Unable to set some counters");

              var verified = client
            .Pipeline(c => Enumerable
              .Range(0, 1000)
              .Select(n => c.Get("counter" + n.ToString()))
              .AsEnumerable())
            .Cast<int>()
            .All(n => n >= 100 && n < 1000);

              WriteLine(verified ?
            "Counter values verified." :
            "Some counters are invalid.");
        }
		public virtual void OnBeforeEachTest()
		{
			if (Redis != null) Redis.Dispose();
			Redis = new RedisClient(TestConfig.SingleHost);
			Redis.FlushDb();
			RedisTyped = Redis.As<CacheRecord>();
		}
        public void Delete(Tile tile)
        {
            var client = new RedisClient();
            client.Del(new TileKeys().GetTileKey(tile.Id));

            new DataIdManager ().Remove (tile);
        }
        RedisMqServer CreateServer()
        {
            using (var redis = new RedisClient())
                redis.FlushAll();

            var mqServer = new RedisMqServer(new BasicRedisClientManager());
            mqServer.RegisterHandler<Spin0>(m => new Spin0 { Id = counter.Spin0++ });

            mqServer.RegisterHandler<Spin10>(m => {
                var sw = Stopwatch.StartNew();
                while (sw.ElapsedMilliseconds < 10) Thread.SpinWait(100000);
                return new Spin10 { Id = counter.Spin10++ };
            });
            mqServer.RegisterHandler<Spin100>(m => {
                var sw = Stopwatch.StartNew();
                while (sw.ElapsedMilliseconds < 100) Thread.SpinWait(100000);
                return new Spin100 { Id = counter.Spin100++ };
            });
            mqServer.RegisterHandler<Spin1000>(m => {
                var sw = Stopwatch.StartNew();
                while (sw.ElapsedMilliseconds < 1000) Thread.SpinWait(100000);
                return new Spin1000 { Id = counter.Spin1000++ };
            });


            return mqServer;
        }
		public void OnTestFixtureSetUp()
		{
			using (var redisClient = new RedisClient(TestConfig.SingleHost))
			{
				redisClient.FlushAll();
			}
		}
        private void Initialize()
        {
            try
            {
                // create the connection
                Client = new RedisClient(_config.Host, _config.Port)
                {
                    ReconnectAttempts = 3,
                    ReconnectTimeout = 200
                };

                // select the database
                Client.Select(_config.DatabaseId);

                // authenticate if needed.
                if (!string.IsNullOrEmpty(_config.Password))
                    Client.Auth(_config.Password);

                // check the version
                var version = GetVersion();
                if (version < _requiredMinimumVersion)
                    throw new Exception(string.Format("You are using redis version {0}, minimum required version is 2.6", version));

                _logger.Information("Redis storage initialized: {0:l}:{1}, v{2:l}.", _config.Host, _config.Port, version);
            }
            catch (Exception e)
            {
                _logger.Error("Redis storage initialization failed: {0:l}:{1} - {2:l}", _config.Host, _config.Port, e.Message);
            }
        }
 public void TestAuth()
 {
     using (var redis = new RedisClient(Host, Port, 0))
     {
         Assert.AreEqual("OK", redis.Auth(Password));
     }
 }
Exemple #31
0
 static RedisHelper()
 {
     redisClient = new RedisClient(host, Convert.ToInt32(port), pwd, Convert.ToInt64(db));
 }
Exemple #32
0
        /// <summary>
        /// 构造函数
        /// </summary>
        public LoginController()
        {
            var redisDbConfig = RedisDbConfig.Instance;

            this._redisClient = new RedisClient(redisDbConfig.Host, redisDbConfig.Port, redisDbConfig.Password, redisDbConfig.Db);
        }
Exemple #33
0
        private SessionStateStoreData GetSessionStoreItem(bool lockRecord,
                                                          HttpContext context,
                                                          string id,
                                                          out bool locked,
                                                          out TimeSpan lockAge,
                                                          out object lockId,
                                                          out SessionStateActions actionFlags)
        {
            // Initial values for return value and out parameters.
            SessionStateStoreData item = null;

            lockAge     = TimeSpan.Zero;
            lockId      = null;
            locked      = false;
            actionFlags = 0;

            // String to hold serialized SessionStateItemCollection.
            string serializedItems = "";

            // Timeout value from the data store.
            int timeout = 0;

            using (RedisClient client = this.RedisSessionClient)
            {
                try
                {
                    if (lockRecord)
                    {
                        locked = false;
                        SessionItem currentItem = client.Get <SessionItem>(this.RedisKey(id));

                        if (currentItem != null)
                        {
                            // If the item is locked then do not attempt to update it
                            if (!currentItem.Locked)
                            {
                                currentItem.Locked   = true;
                                currentItem.LockDate = DateTime.UtcNow;
                                client.Set <SessionItem>(this.RedisKey(id), currentItem, DateTime.UtcNow.AddMinutes(sessionStateConfig.Timeout.TotalMinutes));
                            }
                            else
                            {
                                locked = true;
                            }
                        }
                    }

                    SessionItem currentSessionItem = client.Get <SessionItem>(this.RedisKey(id));

                    if (currentSessionItem != null)
                    {
                        serializedItems = currentSessionItem.SessionItems;
                        lockId          = currentSessionItem.LockID;
                        lockAge         = DateTime.UtcNow.Subtract(currentSessionItem.LockDate);
                        actionFlags     = (SessionStateActions)currentSessionItem.Flags;
                        timeout         = currentSessionItem.Timeout;
                    }
                    else
                    {
                        locked = false;
                    }

                    if (currentSessionItem != null && !locked)
                    {
                        // Delete the old item before inserting the new one
                        client.Remove(this.RedisKey(id));

                        lockId = (int?)lockId + 1;
                        currentSessionItem.LockID = lockId != null ? (int)lockId : 0;
                        currentSessionItem.Flags  = 0;

                        client.Set <SessionItem>(this.RedisKey(id), currentSessionItem, DateTime.UtcNow.AddMinutes(sessionStateConfig.Timeout.TotalMinutes));

                        // If the actionFlags parameter is not InitializeItem,
                        // deserialize the stored SessionStateItemCollection.
                        if (actionFlags == SessionStateActions.InitializeItem)
                        {
                            item = CreateNewStoreData(context, 30);
                        }
                        else
                        {
                            item = Deserialize(context, serializedItems, timeout);
                        }
                    }
                }

                catch (Exception e)
                {
                    throw e;
                }
            }

            return(item);
        }
Exemple #34
0
 /// <summary>
 /// 获取旧值赋上新值
 /// </summary>
 public string GetAndSetValue(string key, string value)
 {
     return(RedisClient.GetAndSetValue(key, value));
 }
Exemple #35
0
 /// <summary>
 /// 获取多个key的value值
 /// </summary>
 public List <T> Get <T>(List <string> keys)
 {
     return(RedisClient.GetValues <T>(keys));
 }
Exemple #36
0
 /// <summary>
 /// 获取key的value值
 /// </summary>
 public string Get(string key)
 {
     return(RedisClient.GetValue(key));
 }
Exemple #37
0
        public static async Task Post_XAGL_WM1000KZG_StopWell(ModbusRtuOverTcp client, RedisClient redisClient, string messageString)
        {
            var par = messageString.FromJson <ControlRequest>();

            //用于通过ServerEvent给调用着返回消息
            if (!par.UserName.IsNullOrEmpty())
            {
                ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, 0, "ok");
            }

            return;

            try
            {
                var modbusAddress = par.ModbusAddress;

                ClientInfo.CurrentModbusPoolAddress = modbusAddress;

                //写入0值到4121(Holding register)寄存器,设置油井的状态为开启。
                // var result2 = await client.WriteAsync("4126", 2);

                var startAddress = (ushort)4126;

                var address = $"s={par.ModbusAddress};{startAddress}";

                var result2 = await client.WriteOneRegisterAsync(address, (ushort)(2));

                if (result2.IsSuccess)
                {
                    //用于通过ServerEvent给调用着返回消息
                    if (!par.UserName.IsNullOrEmpty())
                    {
                        ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, 0, "ok");
                    }
                }
                else
                {
                    //用于通过ServerEvent给调用着返回消息
                    if (!par.UserName.IsNullOrEmpty())
                    {
                        ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, "error");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Logger.Error(ex.Source);

                if (!par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, ex.Message);
                }
            }

            //
        }
Exemple #38
0
        public void MemberPageBase_Load(object sender, EventArgs e)
        {
            DateTime       now;
            cz_stat_online _online;
            cz_stat_online _online2;

            if (HttpContext.Current.Session["user_name"] == null)
            {
                HttpContext.Current.Response.Write("<script>top.location.href='/'</script>");
                HttpContext.Current.Response.End();
            }
            string str = this.get_children_name();

            if (FileCacheHelper.get_RedisStatOnline().Equals(1))
            {
                if (HttpContext.Current.Request.Path.ToLower().IndexOf("resetpasswd.aspx") > 0)
                {
                    now     = DateTime.Now;
                    _online = new cz_stat_online();
                    _online.set_u_name((str == "") ? HttpContext.Current.Session["user_name"].ToString() : str);
                    _online.set_is_out(0);
                    _online.set_u_type(HttpContext.Current.Session["user_type"].ToString());
                    _online.set_ip(LSRequest.GetIP());
                    _online.set_first_time(new DateTime?(now));
                    _online.set_last_time(new DateTime?(now));
//                    CallBLL.redisHelper.HashGet<cz_stat_online>("useronline:list", (str == "") ? HttpContext.Current.Session["user_name"].ToString() : str, _online);
                }
//                if (CallBLL.redisHelper.HashExists("useronline:list", (str == "") ? HttpContext.Current.Session["user_name"].ToString() : str))
//                {
//                    _online2 = CallBLL.redisHelper.HashGet<cz_stat_online>("useronline:list", (str == "") ? HttpContext.Current.Session["user_name"].ToString() : str);
//                    if ((_online2 != null) && _online2.get_is_out().Equals(1))
//                    {
//                        HttpContext.Current.Session.Abandon();
//                        HttpContext.Current.Response.Write("<script>top.location.href='/'</script>");
//                        HttpContext.Current.Response.End();
//                    }
//                }
                if (PageBase.IsNeedPopBrower((str == "") ? HttpContext.Current.Session["user_name"].ToString() : str))
                {
                    HttpContext.Current.Session.Abandon();
                    HttpContext.Current.Response.Write("<script>top.location.href='/'</script>");
                    HttpContext.Current.Response.End();
                }
            }
            else if (FileCacheHelper.get_RedisStatOnline().Equals(2))
            {
                RedisClient client;
                if (HttpContext.Current.Request.Path.ToLower().IndexOf("resetpasswd.aspx") > 0)
                {
                    now     = DateTime.Now;
                    _online = new cz_stat_online();
                    _online.set_u_name((str == "") ? HttpContext.Current.Session["user_name"].ToString() : str);
                    _online.set_is_out(0);
                    _online.set_u_type(HttpContext.Current.Session["user_type"].ToString());
                    _online.set_ip(LSRequest.GetIP());
                    _online.set_first_time(new DateTime?(now));
                    _online.set_last_time(new DateTime?(now));
                    using (client = new RedisClient(RedisConnectSplit.get_RedisIP(), RedisConnectSplit.get_RedisPort(), RedisConnectSplit.get_RedisPassword(), (long)FileCacheHelper.get_GetRedisDBIndex()))
                    {
                        client.ConnectTimeout = int.Parse(RedisConnectSplit.get_RedisConnectTimeout());
                        client.SetEntryInHash("useronline:list", (str == "") ? HttpContext.Current.Session["user_name"].ToString() : str, JsonHandle.ObjectToJson(_online));
                    }
                }
                using (client = new RedisClient(RedisConnectSplit.get_RedisIP(), RedisConnectSplit.get_RedisPort(), RedisConnectSplit.get_RedisPassword(), (long)FileCacheHelper.get_GetRedisDBIndex()))
                {
                    client.ConnectTimeout = int.Parse(RedisConnectSplit.get_RedisConnectTimeout());
                    if (client.HashContainsEntry("useronline:list", (str == "") ? HttpContext.Current.Session["user_name"].ToString() : str))
                    {
                        _online2 = JsonHandle.JsonToObject <cz_stat_online>(client.GetValueFromHash("useronline:list", (str == "") ? HttpContext.Current.Session["user_name"].ToString() : str)) as cz_stat_online;
                        if ((_online2 != null) && _online2.get_is_out().Equals(1))
                        {
                            HttpContext.Current.Session.Abandon();
                            HttpContext.Current.Response.Write("<script>top.location.href='/'</script>");
                            HttpContext.Current.Response.End();
                        }
                    }
                }
                if (PageBase.IsNeedPopBrower((str == "") ? HttpContext.Current.Session["user_name"].ToString() : str))
                {
                    HttpContext.Current.Session.Abandon();
                    HttpContext.Current.Response.Write("<script>top.location.href='/'</script>");
                    HttpContext.Current.Response.End();
                }
            }
            else if (base.IsUserOut((str == "") ? HttpContext.Current.Session["user_name"].ToString() : str) || PageBase.IsNeedPopBrower((str == "") ? HttpContext.Current.Session["user_name"].ToString() : str))
            {
                HttpContext.Current.Session.Abandon();
                HttpContext.Current.Response.Write("<script>top.location.href='/'</script>");
                HttpContext.Current.Response.End();
            }
            string str3 = HttpContext.Current.Session["user_name"].ToString();

            this.UserCurrentSkin = (HttpContext.Current.Session[str3 + "lottery_session_user_info"] as agent_userinfo_session).get_u_skin();
            this.ForcedModifyPassword();
            this.AgentCurrentLottery();
            this.RedirectReport();
            this.IsOpenLottery();
            if (((((HttpContext.Current.Request.Path.ToLower().IndexOf("fgs_list") > -1) || (HttpContext.Current.Request.Path.ToLower().IndexOf("gd_list") > -1)) || ((HttpContext.Current.Request.Path.ToLower().IndexOf("zd_list") > -1) || (HttpContext.Current.Request.Path.ToLower().IndexOf("dl_list") > -1))) || ((HttpContext.Current.Request.Path.ToLower().IndexOf("hy_list") > -1) || (HttpContext.Current.Request.Path.ToLower().IndexOf("child_list") > -1))) || (HttpContext.Current.Request.Path.ToLower().IndexOf("filluser_list") > -1))
            {
                CookieHelper.SetCookie("userreturnbackurl", HttpContext.Current.Request.ServerVariables["Path_Info"] + "?" + HttpContext.Current.Request.ServerVariables["Query_String"]);
            }
        }
Exemple #39
0
 /// <summary>
 /// 设置key的value并设置过期时间
 /// </summary>
 public bool Set(string key, string value, DateTime dt)
 {
     return(RedisClient.Set <string>(key, value, dt));
 }
Exemple #40
0
 /// <summary>
 /// 设置key的value
 /// </summary>
 public bool Set(string key, string value)
 {
     return(RedisClient.Set <string>(key, value));
 }
Exemple #41
0
 /// <summary>
 /// 自减count,返回自减后的值
 /// </summary>
 /// <param name="key"></param>
 /// <param name="count"></param>
 /// <returns></returns>
 public long DecrBy(string key, int count)
 {
     return(RedisClient.DecrementValueBy(key, count));
 }
Exemple #42
0
 /// <summary>
 /// 自减1,返回自减后的值
 /// </summary>
 public long Decr(string key)
 {
     return(RedisClient.DecrementValue(key));
 }
Exemple #43
0
 /// <summary>
 /// 获取值的长度
 /// </summary>
 public long GetLength(string key)
 {
     return(RedisClient.GetStringCount(key));
 }
Exemple #44
0
        private static void RedisOperationTest(object sender, bool status)
        {
            RedisClient redisClient = (RedisClient)sender;

            if (status)
            {
                ConsoleHelper.WriteLine("连接redis服务器成功!");

                #region key value

                ConsoleHelper.WriteLine("回车开始kv插值操作...");
                ConsoleHelper.ReadLine();
                for (int i = 0; i < 1000; i++)
                {
                    redisClient.GetDataBase().Set("key" + i, "val" + i);
                }
                //redisConnection.GetDataBase().Exists("key0");
                ConsoleHelper.WriteLine("kv插入完成...");

                ConsoleHelper.WriteLine("回车开始获取kv值操作...");
                ConsoleHelper.ReadLine();

                var keys = redisClient.GetDataBase().Keys().Data.ToArray(false, "\r\n");

                foreach (var key in keys)
                {
                    var val = redisClient.GetDataBase().Get(key);
                    ConsoleHelper.WriteLine("Get val:" + val);
                }
                ConsoleHelper.WriteLine("获取kv值完成...");

                ConsoleHelper.WriteLine("回车开始开始kv移除操作...");
                ConsoleHelper.ReadLine();
                for (int i = 0; i < 1000; i++)
                {
                    redisClient.GetDataBase().Del("key" + i);
                }
                ConsoleHelper.WriteLine("移除kv值完成...");
                #endregion


                #region hashset
                string hid = "wenli";

                ConsoleHelper.WriteLine("回车开始HashSet插值操作...");
                ConsoleHelper.ReadLine();
                for (int i = 0; i < 1000; i++)
                {
                    redisClient.GetDataBase().HSet(hid, "key" + i, "val" + i);
                }
                ConsoleHelper.WriteLine("HashSet插值完成...");

                ConsoleHelper.WriteLine("回车开始HashSet插值操作...");
                ConsoleHelper.ReadLine();
                var hkeys = redisClient.GetDataBase().GetHKeys(hid).Data.ToArray();
                foreach (var hkey in hkeys)
                {
                    var val = redisClient.GetDataBase().HGet(hid, hkey);
                    ConsoleHelper.WriteLine("HGet val:" + val.Data);
                }

                var hall = redisClient.GetDataBase().HGetAll("wenli");
                ConsoleHelper.WriteLine("HashSet查询完成...");

                ConsoleHelper.WriteLine("回车开始HashSet移除操作...");
                ConsoleHelper.ReadLine();
                foreach (var hkey in hkeys)
                {
                    redisClient.GetDataBase().HDel(hid, hkey);
                }
                ConsoleHelper.WriteLine("HashSet移除完成...");


                #endregion


                //redisConnection.GetDataBase().Suscribe((c, m) =>
                //{
                //    ConsoleHelper.WriteLine("channel:{0} msg:{1}", c, m);
                //    redisConnection.GetDataBase().UNSUBSCRIBE(c);
                //}, "c39654");


                ConsoleHelper.WriteLine("测试完成!");
            }
            else
            {
                ConsoleHelper.WriteLine("连接失败!");
            }
        }
        /// <summary>
        /// Handles the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        public void Handle(DeployRequestDto request)
        {
            var client = new RedisClient();

            client.FlushAll();
        }
Exemple #46
0
 internal void SetClient(RedisClientFactory factory, IClient client)
 {
     _factory    = factory;
     _client     = client as RedisClient;
     IsConnected = client.IsConnected;
 }
Exemple #47
0
 public Redis(string redisURL)
 {
     redis = new RedisClient(redisURL, 6379);
 }
Exemple #48
0
        static void Main(string[] args)
        {
            ConsoleHelper.Title = "SAEA.RedisSocketTest";

            ConsoleHelper.WriteLine("输入连接字符串连接RedisServer,格式为\r\nserver=127.0.0.1:6379;passwords=yswenli");

            var cnnStr = ConsoleHelper.ReadLine();

            if (string.IsNullOrEmpty(cnnStr))
            {
                cnnStr = "server=127.0.0.1:6379;passwords=yswenli";
            }
            RedisClient redisClient = new RedisClient(cnnStr, false);

            redisClient.Connect();

            var info = redisClient.Info();

            #region 异步测试

            redisClient.GetDataBase().HSetAsync(TimeSpan.FromSeconds(5), "hid", "key", "val");
            var r  = redisClient.GetDataBase().HGetAsync(TimeSpan.FromSeconds(5), "hid", "key").Result;
            var rr = redisClient.GetDataBase().HDelAsync(TimeSpan.FromSeconds(5), "hid", "key").Result;


            //var batch = redisClient.GetDataBase().CreatedBatch();
            //for (int i = 0; i < 100000; i++)
            //{
            //    batch.ZAddAsync("yswenliG", i.ToString(), i);
            //}
            //_ = batch.Execute().ToList();
            #endregion

            #region scan

            var sresult1 = redisClient.GetDataBase().Scan();
            var sresult2 = redisClient.GetDataBase().Scan(0, "*", -1);

            #endregion

            StringPerformanceTest(redisClient);

            BatchTest(redisClient);


            var rk = redisClient.GetDataBase().RandomKey();

            var crk = redisClient.Console("RandomKey");

            ConsoleHelper.ReadLine();

            KeysTest(redisClient);

            var db = redisClient.GetDataBase(0);

            StringTest(db);

            ConsoleHelper.ReadLine();

            HashTest(db);

            ListTest(db);

            SetTest(db);

            GeoTest(db);

            ConsoleHelper.ReadLine();
        }
Exemple #49
0
 public AuthBusiness(IAuthRepository authRepository, IConfig config, ILogger <AuthBusiness> logger, ISqlSugarDbRepository <UserInfo> userDbRepository, RedisClient redisClient)
 {
     _authRepository   = authRepository;
     _config           = config;
     _logger           = logger;
     _userDbRepository = userDbRepository;
     _redisClient      = redisClient;
 }
Exemple #50
0
 public RedisCacheProvider(string redisServerIP)
 {
     this.RedisServerIP = redisServerIP;
     redisClient        = new RedisClient(redisServerIP);
 }
        //在Redis中存储常用的5种数据类型:String,Hash,List,SetSorted set
        //这种方式要引用ServiceStack,ServiceStack.Interfaces,ServiceStack.ServiceInterface三个dll
        public static void MainHelper()
        {
            RedisClient client = new RedisClient("127.0.0.1", 6379);

            client.FlushAll();

            #region string
            client.Add <string>("StringValueTime", "我已设置过期时间噢30秒后会消失", DateTime.Now.AddMilliseconds(3000));
            while (true)
            {
                if (client.ContainsKey("StringValueTime"))
                {
                    Console.WriteLine("String.键:StringValue,值:{0} {1}", client.Get <string>("StringValueTime"), DateTime.Now);
                    Thread.Sleep(1000);
                }
                else
                {
                    Console.WriteLine("键:StringValue,值:我已过期 {0}", DateTime.Now);
                    break;
                }
            }

            client.Add <string>("StringValue", " String和Memcached操作方法差不多");
            Console.WriteLine("数据类型为:String.键:StringValue,值:{0}", client.Get <string>("StringValue"));
            #endregion

            #region 存储Entity
            #region 如果想直接存储Entity,对象成员要有{get; set;}属性才行
            Student stu = new Student()
            {
                id = "1001", name = "李四"
            };
            client.Add <Student>("student", stu);
            Student student = client.Get <Student>("student");
            Console.WriteLine("数据类型为:String.键:StringEntity,值:{0} {1}", student.id, student.name);
            #endregion

            #region 如果对象成员没有{get; set;},可以通过把对象转换为数据流存储
            Student stud = new Student()
            {
                id = "1001", name = "李四"
            };
            byte[] buff;
            //先将对象转换为数组
            using (MemoryStream ms = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, stud);
                buff = ms.GetBuffer();
            }
            //把数组存入Redis
            client.Add <byte[]>("Entity", buff);
            //取出数组,解析成对象
            if (client.ContainsKey("Entity"))
            {
                using (MemoryStream ms = new MemoryStream(client.Get("Entity")))
                {
                    IFormatter formatter = new BinaryFormatter();
                    Student    Get_stud  = (Student)formatter.Deserialize(ms);
                    Console.WriteLine("数据类型为:String.键:StringEntity,值:{0} {1}", Get_stud.id, Get_stud.name);
                }
            }
            #endregion
            #endregion

            #region Hash
            client.SetEntryInHash("HashID", "Name", "张三");
            client.SetEntryInHash("HashID", "Age", "24");
            client.SetEntryInHash("HashID", "Sex", "男");
            client.SetEntryInHash("HashID", "Address", "上海市XX号XX室");

            List <string> HaskKey = client.GetHashKeys("HashID");
            foreach (string key in HaskKey)
            {
                Console.WriteLine("HashID--Key:{0}", key);
            }

            List <string> HaskValue = client.GetHashValues("HashID");
            foreach (string value in HaskValue)
            {
                Console.WriteLine("HashID--Value:{0}", value);
            }

            List <string> AllKey = client.GetAllKeys(); //获取所有的key。
            foreach (string Key in AllKey)
            {
                Console.WriteLine("AllKey--Key:{0}", Key);
            }
            #endregion

            #region List

            /*
             * list是一个链表结构,主要功能是push,pop,获取一个范围的所有的值等,操作中key理解为链表名字。
             * Redis的list类型其实就是一个每个子元素都是string类型的双向链表。我们可以通过push,pop操作从链表的头部或者尾部添加删除元素,
             * 这样list既可以作为栈,又可以作为队列。Redis list的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销,
             * Redis内部的很多实现,包括发送缓冲队列等也都是用的这个数据结构
             */
            client.EnqueueItemOnList("QueueListId", "1.张三");  //入队
            client.EnqueueItemOnList("QueueListId", "2.张四");
            client.EnqueueItemOnList("QueueListId", "3.王五");
            client.EnqueueItemOnList("QueueListId", "4.王麻子");
            int q = client.GetListCount("QueueListId");
            for (int i = 0; i < q; i++)
            {
                Console.WriteLine("QueueListId出队值:{0}", client.DequeueItemFromList("QueueListId"));   //出队(队列先进先出)
            }

            client.PushItemToList("StackListId", "1.张三");  //入栈
            client.PushItemToList("StackListId", "2.张四");
            client.PushItemToList("StackListId", "3.王五");
            client.PushItemToList("StackListId", "4.王麻子");
            int p = client.GetListCount("StackListId");
            for (int i = 0; i < p; i++)
            {
                Console.WriteLine("StackListId出栈值:{0}", client.PopItemFromList("StackListId"));   //出栈(栈先进后出)
            }
            #endregion

            #region Set无序集合

            /*
             * 它是string类型的无序集合。set是通过hash table实现的,添加,删除和查找,对集合我们可以取并集,交集,差集
             */
            client.AddItemToSet("Set1001", "小A");
            client.AddItemToSet("Set1001", "小B");
            client.AddItemToSet("Set1001", "小C");
            client.AddItemToSet("Set1001", "小D");
            HashSet <string> hastsetA = client.GetAllItemsFromSet("Set1001");
            foreach (string item in hastsetA)
            {
                Console.WriteLine("Set无序集合ValueA:{0}", item); //出来的结果是无须的
            }

            client.AddItemToSet("Set1002", "小K");
            client.AddItemToSet("Set1002", "小C");
            client.AddItemToSet("Set1002", "小A");
            client.AddItemToSet("Set1002", "小J");
            HashSet <string> hastsetB = client.GetAllItemsFromSet("Set1002");
            foreach (string item in hastsetB)
            {
                Console.WriteLine("Set无序集合ValueB:{0}", item); //出来的结果是无须的
            }

            HashSet <string> hashUnion = client.GetUnionFromSets(new string[] { "Set1001", "Set1002" });
            foreach (string item in hashUnion)
            {
                Console.WriteLine("求Set1001和Set1002的并集:{0}", item); //并集
            }

            HashSet <string> hashG = client.GetIntersectFromSets(new string[] { "Set1001", "Set1002" });
            foreach (string item in hashG)
            {
                Console.WriteLine("求Set1001和Set1002的交集:{0}", item);  //交集
            }

            HashSet <string> hashD = client.GetDifferencesFromSet("Set1001", new string[] { "Set1002" });  //[返回存在于第一个集合,但是不存在于其他集合的数据。差集]
            foreach (string item in hashD)
            {
                Console.WriteLine("求Set1001和Set1002的差集:{0}", item);  //差集
            }
            #endregion

            #region  SetSorted 有序集合

            /*
             * sorted set 是set的一个升级版本,它在set的基础上增加了一个顺序的属性,这一属性在添加修改.元素的时候可以指定,
             * 每次指定后,zset(表示有序集合)会自动重新按新的值调整顺序。可以理解为有列的表,一列存 value,一列存顺序。操作中key理解为zset的名字.
             */
            client.AddItemToSortedSet("SetSorted1001", "1.刘仔");
            client.AddItemToSortedSet("SetSorted1001", "2.星仔");
            client.AddItemToSortedSet("SetSorted1001", "3.猪仔");
            List <string> listSetSorted = client.GetAllItemsFromSortedSet("SetSorted1001");
            foreach (string item in listSetSorted)
            {
                Console.WriteLine("SetSorted有序集合{0}", item);
            }
            #endregion
        }
Exemple #52
0
 /// <summary>
 /// Notifies that the current test expects an empty database.
 /// </summary>
 public override void NotifyEmptyExpected()
 {
     _client = null;
 }
Exemple #53
0
        public void Execute()
        {
            RedisConfig.DisableVerboseLogging = true;
            LogManager.LogFactory             = new ConsoleLogFactory(debugEnabled: true);
            log = LogManager.GetLogger(GetType());

            RedisConfig.DefaultReceiveTimeout = 10000;

            OnSetUp();

            using (var sentinel = CreateSentinel())
            {
                if (UseRedisManagerPool)
                {
                    sentinel.RedisManagerFactory = (masters, slaves) =>
                                                   new RedisManagerPool(masters);
                }

                var redisManager = sentinel.Start();

                int i           = 0;
                var clientTimer = new Timer
                {
                    Interval = MessageInterval,
                    Enabled  = true
                };
                clientTimer.Elapsed += (sender, args) =>
                {
                    log.Debug("clientTimer.Elapsed: " + (i++));

                    try
                    {
                        string key = null;
                        using (var master = (RedisClient)redisManager.GetClient())
                        {
                            var counter = master.Increment("key", 1);
                            key = "key" + counter;
                            log.DebugFormat("Set key {0} in read/write client #{1}@{2}", key, master.Id, master.GetHostString());
                            master.SetValue(key, "value" + 1);
                        }
                        using (var readOnly = (RedisClient)redisManager.GetReadOnlyClient())
                        {
                            log.DebugFormat("Get key {0} in read-only client #{1}@{2}", key, readOnly.Id, readOnly.GetHostString());
                            var value = readOnly.GetValue(key);
                            log.DebugFormat("{0} = {1}", key, value);
                        }
                    }
                    catch (ObjectDisposedException ex)
                    {
                        log.DebugFormat("ObjectDisposedException detected, disposing timer...");
                        clientTimer.Dispose();
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error in Timer", ex);
                    }

                    if (i % 10 == 0)
                    {
                        log.Debug(RedisStats.ToDictionary().Dump());
                    }
                };

                log.Debug("Sleeping for 5000ms...");
                Thread.Sleep(5000);

                log.Debug("Failing over master...");
                var masterHost = sentinel.ForceMasterFailover();
                log.Debug("{0} was failed over".Fmt(masterHost));

                log.Debug("Sleeping for 20000ms...");
                Thread.Sleep(20000);

                try
                {
                    var debugConfig = sentinel.GetMaster();
                    using (var master = new RedisClient(debugConfig))
                    {
                        log.Debug("Putting master '{0}' to sleep for 35 seconds...".Fmt(master.GetHostString()));
                        master.DebugSleep(35);
                    }
                }
                catch (Exception ex)
                {
                    log.Error("Error retrieving master for DebugSleep()", ex);
                }

                log.Debug("After DEBUG SLEEP... Sleeping for 5000ms...");
                Thread.Sleep(5000);

                log.Debug("RedisStats:");
                log.Debug(RedisStats.ToDictionary().Dump());

                System.Console.ReadLine();
            }

            OnTearDown();
        }
        public Tuple <Int64, TimeSpan> Test(Int32 threads, Int32 loops)
        {
            var options = new RedisClientOptions()
            {
                Logger = new ConsoleLogger(false)
            };

            options.MultiplexPool.CommandConnections  = 1;
            options.MultiplexPool.SubscriptionOptions = 1;
            using (var client = new RedisClient(_endpoint, options))
            {
                client.ConnectAsync(CancellationToken.None).Wait();

                using (var channel = client.CreateChannel())
                    channel.Execute("flushall");

                var cancel   = new CancellationTokenSource();
                var taskList = new List <Thread>();

                var total    = threads * loops;
                var progress = 0;
                var bars     = 0;

                var sw = new Stopwatch();
                sw.Start();
                for (int threadId = 0; threadId < threads; threadId++)
                {
                    var ts = new ThreadStart(() =>
                    {
                        try
                        {
                            for (int loop = 0; loop < loops; loop++)
                            {
                                using (var channel = client.CreateChannel())
                                    RunClient(threadId.ToString() + "_" + loop.ToString(), channel, cancel.Token).Wait();

                                var p          = Interlocked.Increment(ref progress);
                                var percentage = (Int32)((p * 100D) / total);
                                while (bars < percentage)
                                {
                                    Interlocked.Increment(ref bars);
                                    Console.Write("|");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.Write("[{0}]", ex.GetType());
                        }
                    });

                    var thread = new Thread(ts);
                    thread.Start();
                    taskList.Add(thread);
                }

                foreach (var t in taskList)
                {
                    t.Join();
                }
                sw.Stop();

                cancel.Cancel();

                return(new Tuple <Int64, TimeSpan>(progress, sw.Elapsed));
            }
        }
Exemple #55
0
 /// <summary>
 /// 设置key的value并设置过期时间
 /// </summary>
 public bool Set(string key, string value, TimeSpan sp)
 {
     return(RedisClient.Set <string>(key, value, sp));
 }
Exemple #56
0
        private void buttonServerConnect_Click(object sender, EventArgs e)
        {
            try
            {
                //云服务器连接ip,por,password设置
                for (int i = 1; i <= 4; ++i)
                {
                    //检验输入是否为数字,数字是否介于0~255之间
                    int     tmp     = -1;
                    TextBox objText = (TextBox)this.panel1.Controls["textBox" + i.ToString()];
                    if (int.TryParse(objText.Text, out tmp) != true)
                    {
                        throw new Exception("错误:云服务器IP地址输入错误,请重新输入!");
                    }
                    else if (!(tmp >= 0 && tmp <= 255))
                    {
                        throw new Exception("错误:云服务器IP地址输入错误,请重新输入!");
                    }
                }
                String IP   = textBox1.Text + '.' + textBox2.Text + '.' + textBox3.Text + '.' + textBox4.Text;
                int    port = 0;
                if (int.TryParse(textBox5.Text, out port) != true)
                {
                    throw new Exception("错误:云服务器端口号输入错误,请重新输入!");
                }
                serverpara.RedisIP       = IP;
                serverpara.RedisPort     = textBox5.Text;
                serverpara.RedisPassword = textBox6.Text;
                serverpara.connectvalid  = false;

                //host主机参数  格式“password@ip:port”
                string[] host = { serverpara.RedisPassword + '@' + serverpara.RedisIP + ':' + serverpara.RedisPort };
                //从连接池获得只读连接客户端
                long        initialDB = 0;
                RedisClient Client    = (RedisClient)redismanager.GetReadOnlyClient(ref (initialDB), ref (host));
                if (Client == null || !Client.Ping())
                {
                    throw new Exception("连接云服务器失败!");
                }
                //云服务器连接成功
                serverpara.connectvalid = true;

                //本地服务器连接ip,por,password设置
                for (int i = 7; i <= 10; ++i)
                {
                    //检验输入是否为数字,数字是否介于0~255之间
                    int     tmpint  = -1;
                    TextBox objText = (TextBox)this.panel2.Controls["textBox" + i.ToString()];
                    if (int.TryParse(objText.Text, out tmpint) != true)
                    {
                        throw new Exception("错误:云服务器IP地址输入错误,请重新输入!");
                    }
                    else if (!(tmpint >= 0 && tmpint <= 255))
                    {
                        throw new Exception("错误:云服务器IP地址输入错误,请重新输入!");
                    }
                }
                IP   = textBox7.Text + '.' + textBox8.Text + '.' + textBox9.Text + '.' + textBox10.Text;
                port = 0;
                if (int.TryParse(textBox11.Text, out port) != true)
                {
                    throw new Exception("错误:云服务器端口号输入错误,请重新输入!");
                }

                redispara.RedisIP       = IP;
                redispara.RedisPort     = textBox11.Text;
                redispara.RedisPassword = textBox12.Text;
                redispara.connectvalid  = false;

                //localhost主机参数  格式“password@ip:port”
                string[] localhost = { redispara.RedisPassword + '@' + redispara.RedisIP + ':' + redispara.RedisPort };
                //从连接池获得只读连接客户端
                initialDB = 0;
                Client    = (RedisClient)localredismanager.GetReadOnlyClient(ref (initialDB), ref (localhost));
                if (Client == null || !Client.Ping())
                {
                    throw new Exception("连接本地服务器失败!");
                }
                //本地服务器连接成功
                redispara.connectvalid = true;

                /*if (redispara.connectvalid)
                 * {
                 *  try
                 *  {
                 *      FileStream fs = new FileStream(@"../LocalRedisPara.conf", FileMode.Create);
                 *      StreamWriter sw = new StreamWriter(fs);
                 *      sw.Write("RedisIP=" + redispara.RedisIP + ";RedisPort=" + redispara.RedisPort + ";RedisPassword="******"服务器参数设置完毕", "提示");
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR:" + ex.Message, "ERROR");
                redismanager.dispose();
            }
        }
Exemple #57
0
 /// <summary>
 /// 设置多个key/value
 /// </summary>
 public void Set(Dictionary <string, string> dic)
 {
     RedisClient.SetAll(dic);
 }
Exemple #58
0
 /// <summary>
 /// 在原有key的value值之后追加value
 /// </summary>
 public long Append(string key, string value)
 {
     return(RedisClient.AppendToValue(key, value));
 }
Exemple #59
0
 /// <summary>
 /// 自增count,返回自增后的值
 /// </summary>
 public double IncrBy(string key, double count)
 {
     return(RedisClient.IncrementValueBy(key, count));
 }
Exemple #60
0
        public static async Task Post_XAGL_WM1000KZG_StartWell(ModbusRtuOverTcp client, RedisClient redisClient, string messageString)
        {
            var par = messageString.FromJson <ControlRequest>();

            //用于通过ServerEvent给调用着返回消息
            if (!par.UserName.IsNullOrEmpty())
            {
                ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, 0, "ok");
            }

            return;

            try
            {
                var modbusAddress = par.ModbusAddress;

                //var reg = new AMWD.Modbus.Common.Structures.Register
                //{
                //    Address = 4126,
                //    HiByte = 0,
                //    LoByte = 1
                //};

                //(2)写入1值到4121(Holding register)寄存器,设置油井的状态为开启。
                // var result2 = await client.WriteAsync("4126", 1);

                var startAddress = (ushort)4126;

                var address = $"s={par.ModbusAddress};{startAddress}";

                var result2 = await client.WriteOneRegisterAsync(address, (ushort)(1));


                if (result2.IsSuccess == true)
                {
                    //用于通过ServerEvent给调用着返回消息
                    if (!par.UserName.IsNullOrEmpty())
                    {
                        ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, 0, "ok");
                    }
                }
                else
                {
                    //用于通过ServerEvent给调用着返回消息
                    if (!par.UserName.IsNullOrEmpty())
                    {
                        ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, "error");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                Logger.Error(ex.StackTrace);
                Logger.Error(ex.Source);

                if (par.UserName.IsNullOrEmpty())
                {
                    ServerEventHelper.SendSseMessage(par.UserName, par.SessionId, -1, ex.Message);
                }
            }
        }