public RedisMessageBus(string server, int port, string password, int db, IEnumerable<string> keys, IDependencyResolver resolver)
            : base(resolver)
        {
            _db = db;
            _keys = keys.ToArray();

            _connection = new RedisConnection(host: server, port: port, password: password);

            _connection.Closed += OnConnectionClosed;
            _connection.Error += OnConnectionError;

            // Start the connection
            _connectTask = _connection.Open().Then(() => {
                // Create a subscription channel in redis
                _channel = _connection.GetOpenSubscriberChannel();

                // Subscribe to the registered connections
                _channel.Subscribe(_keys, OnMessage);

                // Dirty hack but it seems like subscribe returns before the actual
                // subscription is properly setup in some cases
                while (_channel.SubscriptionCount == 0) {
                    Thread.Sleep(500);
                }
            });
        }
 public VerifyQueueData(string queueName, QueueProducerConfiguration configuration, string connectionString)
 {
     _configuration = configuration;
     var connection = new BaseConnectionInformation(queueName, connectionString);
     _redisNames = new RedisNames(connection);
     _connection = new RedisConnection(connection);
 }
 private void UseConnection(Action<RedisConnection> action)
 {
     using (var connection = new RedisConnection(RedisUtils.CreateClient()))
     {
         action(connection);
     }
 }
 private void UseConnections(Action<IRedisClient, RedisConnection> action)
 {
     using (var redis = RedisUtils.CreateClient())
     using (var connection = new RedisConnection(redis))
     {
         action(redis, connection);
     }
 }
Beispiel #5
0
 /// <summary>
 /// 初始化
 /// </summary>
 public static void Initialize()
 {
     for (int i = 0; i < PoolMinSize; i++)
     {
         var connection = new RedisConnection(Host, Port, Password, DbIndex);
         _connectionPools.Enqueue(connection);
     }
 }
 public static void SetError(string queueName, string connectionString)
 {
     var connectionInfo = new BaseConnectionInformation(queueName, connectionString);
     var conn = new RedisConnection(connectionInfo);
     var redisNames = new RedisNames(connectionInfo);
     var db = conn.Connection.GetDatabase();
     var id = db.HashGet(redisNames.JobNames, "job1");
     db.HashSet(redisNames.Status, id,
        "2");
 }
 public static void Verify(string queueName, string connectionString, long messageCount)
 {
     var connectionInfo = new BaseConnectionInformation(queueName, connectionString);
     var redisNames = new RedisNames(connectionInfo);
     using (var connection = new RedisConnection(connectionInfo))
     {
         var db = connection.Connection.GetDatabase();
         var records = db.HashLength(redisNames.Values);
         Assert.Equal(messageCount, records);
     }
 }
Beispiel #8
0
 public void CountThread2()
 {
     RedisConnection redisConnection = new RedisConnection();
     while(true)
     {
         redisConnection.AddWatch("sync-counter");
         redisConnection.BeginTransaction();
         redisConnection.Increment<string>("sync-counter");
         if(redisConnection.CommitTransaction() != null)
             Console.WriteLine("Thread 2:" + redisConnection.Get<int, string>("sync-counter"));
         else
             Console.WriteLine("Thread 2 Transaction failed. Retrying");
     }
 }
Beispiel #9
0
 /// <summary>
 /// Create new instance of subscribe-only RedisClient
 /// </summary>
 /// <param name="host">Redis server host or IP</param>
 /// <param name="port">Redis server port</param>
 /// <param name="password">Redis server password</param>
 public RedisSubscriptionClient(string host, int port, string password = null)
 {
     _activity = new ActivityTracer("New Redis subscription client");
     _connection = new RedisConnection(host, port);
     _connection.Connect(0, 1000);
     if (!String.IsNullOrEmpty(password))
     {
         var cmd = RedisCommand.Auth(password);
         _connection.Call(cmd.Parser, cmd.Command, cmd.Arguments);
     }
     _readCancel = new CancellationTokenSource();
     _reader = Task.Factory.StartNew(Read_Task);
     _callbackDispatchers = new Dictionary<string, RedisSubscriptionDispatcher>();
 }
 /// <summary>
 /// check connect to redis.
 /// </summary>
 /// <returns></returns>
 public static bool CheckConnect()
 {
     try
     {
         using (var con = new RedisConnection(Host, Port, Password, DbIndex))
         {
             return con.IsConnected;
         }
     }
     catch (Exception)
     {
         return false;
     }
 }
        /// <summary>
        ///     初始化数据库环境、实例化子类中,所有Set属性
        /// </summary>
        public void Initializer()
        {
            if (IsInitializer) { return; }
            _client = new RedisClient(_redisConnection);
            IsInitializer = true;

            Connection = new RedisConnection(_client);
            Hash = new RedisHash(_client);
            Key = new RedisKey(_client);
            List = new RedisList(_client);
            PubSub = new RedisPubSub(_client);
            Script = new RedisScript(_client);
            Server = new RedisServer(_client);
            Set = new RedisSet(_client);
            SortedSet = new RedisSortedSet(_client);
            String = new RedisString(_client);
            Transaction = new RedisTransaction(_client);
            Bit = new RedisBit(_client);
            Expire = new RedisExpire(_client);
            Sort = new RedisSort(_client);
            Number = new RedisNumber(_client);
        }
Beispiel #12
0
 public RedisClient(RedisConfig config, bool debugModel = false)
 {
     _debugModel = debugModel;
     RedisConfig = config;
     _cnn        = new RedisConnection(RedisConfig.GetIPPort(), debugModel);
 }
 public static IDatabase GetDatabase() => RedisConnection.GetConnectionMultiplexer().GetDatabase();
Beispiel #14
0
 /// <summary>
 /// Creates instance.
 /// </summary>
 /// <param name="connection"></param>
 /// <param name="key"></param>
 /// <param name="defaultExpiry"></param>
 public RedisBit(RedisConnection connection, RedisKey key, TimeSpan?defaultExpiry)
 {
     this.Connection    = connection ?? throw new ArgumentNullException(nameof(connection));
     this.Key           = key;
     this.DefaultExpiry = defaultExpiry;
 }
Beispiel #15
0
 private void btnAddConnect_Click(object sender, EventArgs e)
 {
     try
     {
         var manager = ConfigManager.Instance;
         var endPoint = txtEndPiont.Text.Trim();
         var password = txtPassword.Text.Trim();
         if (!manager.Config.Connections.ContainsKey(endPoint))
         {
             var cont = new RedisConnection(endPoint, password);
             manager.Config.Connections.Add(endPoint, cont);
             AddConnectionToDataTree(endPoint, cont);
         }
         else
         {
             Show("Existed");
         }
     }
     catch (Exception ex)
     {
         Show(ex.Message);
     }
 }
Beispiel #16
0
        /// <summary>
        /// redis cluster中重置连接事件
        /// </summary>
        /// <param name="ipPort"></param>
        /// <param name="operationType"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private Interface.IResult _redisConnection_OnRedirect(string ipPort, OperationType operationType, params object[] args)
        {
            var cnn = RedisConnectionManager.Get(ipPort);

            if (cnn == null || !cnn.IsConnected)
            {
                this.IsConnected = false;
                this.RedisConfig = new RedisConfig(ipPort, this.RedisConfig.Passwords, this.RedisConfig.ActionTimeOut);
                if (_debugModel)
                {
                    cnn = new RedisConnectionDebug(RedisConfig.GetIPPort(), this.RedisConfig.ActionTimeOut);
                }
                else
                {
                    cnn = new RedisConnection(RedisConfig.GetIPPort(), this.RedisConfig.ActionTimeOut);
                }
                cnn.OnRedirect     += _redisConnection_OnRedirect;
                cnn.OnDisconnected += _cnn_OnDisconnected;
                if (cnn.Connect())
                {
                    if (!string.IsNullOrEmpty(this.RedisConfig.Passwords))
                    {
                        cnn.Auth(this.RedisConfig.Passwords);
                    }
                    _cnn             = cnn;
                    this.IsConnected = true;
                    RedisConnectionManager.Set(ipPort, cnn);
                }
                else
                {
                    throw new Exception($"当前节点不可达ipport:{ipPort}");
                }
            }
            else
            {
                _cnn = cnn;
            }

            switch (operationType)
            {
            case OperationType.Do:
                return(_cnn.Do((RequestType)args[0]));

            case OperationType.DoBatchWithList:
                return(_cnn.DoBatchWithList((RequestType)args[0], (string)args[1], (List <string>)args[2]));

            case OperationType.DoBatchWithDic:
                return(_cnn.DoBatchWithDic((RequestType)args[0], (Dictionary <string, string>)args[1]));

            case OperationType.DoBatchWithIDDic:
                return(_cnn.DoBatchWithIDDic((RequestType)args[0], (string)args[1], (Dictionary <string, string>)args[2]));

            case OperationType.DoBatchZaddWithIDDic:
                return(_cnn.DoBatchZaddWithIDDic((RequestType)args[0], (string)args[1], (Dictionary <double, string>)args[2]));

            case OperationType.DoBatchWithIDKeys:
                return(_cnn.DoBatchWithIDKeys((RequestType)args[0], (string)args[1], (string[])args[3]));

            case OperationType.DoBatchWithParams:
                return(_cnn.DoWithMutiParams((RequestType)args[0], (string[])args[1]));

            case OperationType.DoCluster:
                return(_cnn.DoMutiCmd((RequestType)args[0], (object[])args[1]));

            case OperationType.DoClusterSetSlot:
                return(_cnn.DoClusterSetSlot((RequestType)args[0], (string)args[1], (int)args[2], (string)args[3]));

            case OperationType.DoExpire:
                _cnn.DoExpire((string)args[0], (int)args[1]);
                break;

            case OperationType.DoExpireAt:
                _cnn.DoExpireAt((string)args[0], (int)args[1]);
                break;

            case OperationType.DoExpireInsert:
                _cnn.DoExpireInsert((RequestType)args[0], (string)args[1], (string)args[2], (int)args[3]);
                break;

            case OperationType.DoWithID:
                return(_cnn.DoWithID((RequestType)args[0], (string)args[1], (string)args[2], (string)args[3]));

            case OperationType.DoRang:
                return(_cnn.DoRang((RequestType)args[0], (string)args[1], (double)args[2], (double)args[3]));

            case OperationType.DoRangByScore:
                return(_cnn.DoRangByScore((RequestType)args[0], (string)args[1], (double)args[2], (double)args[3], (RangType)args[4], (long)args[5], (int)args[6], (bool)args[7]));

            case OperationType.DoScan:
                return(_cnn.DoScan((RequestType)args[0], (int)args[1], (string)args[2], (int)args[3]));

            case OperationType.DoScanKey:
                return(_cnn.DoScanKey((RequestType)args[0], (string)args[1], (int)args[2], (string)args[3], (int)args[4]));

            case OperationType.DoSub:
                _cnn.DoSub((string[])args[0], (Action <string, string>)args[1]);
                break;

            case OperationType.DoWithKey:
                return(_cnn.DoWithKey((RequestType)args[0], (string)args[1]));

            case OperationType.DoWithKeyValue:
                return(_cnn.DoWithKeyValue((RequestType)args[0], (string)args[1], (string)args[2]));

            default:
                return(null);
            }
            return(null);
        }
Beispiel #17
0
 /// <summary>
 /// update serdis-server info
 /// </summary>
 /// <param name="redisServer"></param>
 /// <param name="connection"></param>
 public static void updateConnection(RedisServer redisServer, RedisConnection connection)
 {
     redisServer.Connection           = connection;
     redisServer.RedisClient          = new RedisClient(connection.Host, Convert.ToInt32(connection.Port));
     redisServer.RedisClient.Encoding = Encoding.UTF8;
 }
Beispiel #18
0
 public RedisStore(RedisConnection connection, int databaseId = 0, bool dispose = true)
 {
     _databaseId = databaseId;
     _dispose    = dispose;
     _connection = connection;
 }
Beispiel #19
0
        public static void Main(string[] args)
        {
            redis = new RedisConnection("localhost", 6379);

            redis.ClearAllDB();
            redis.Set<string, int>("sync-counter", 0);
             	Counter syncCounter = new Counter();
            syncCounter.Count();

            /*redis._Set<string, string>("testkey1", "testval1");

            redis._Set<string, string>("testkey2", "testval2");

            Log("Get testkey1", redis.Get<string, string>("testkey1"));

            Log("Set testkey1", redis.Set<string, string>("testkey1", "testval1"));

            Log("Set testkey2", redis.Set<string, string>("testkey2", "testval2"));

            Log("Set testkey4", redis.Set<string, int>("testkey4",  5));

            Log("Random key", redis.GetRandomKey());

            Log("Exist testkey1", redis.IfExists<string>("testkey1"));

            Log("Exist testkey3", redis.IfExists<string>("testkey3"));

            Log("Type of testkey2", redis.GetKeyType<string>("testkey2"));

            Log("Pattern *1", redis.GetKeysByPattern("*1"));

            Log("Increment testkey4", redis.Increment<string>("testkey4"));

            Log("Increment testkey4 by 4", redis.IncrementBy<string>("testkey4", 4));

            Log("Decrement testkey4", redis.Decrement<string>("testkey4"));

            Log("Decrement testkey4 by 3", redis.DecrementBy<string>("testkey4", 3));

            Log("Get testkey4", redis.Get<string, string>("testkey4"));

            Log("Get testkey4", redis.Get<int, string>("testkey4"));

            Log("Get testkey1", redis.Get<string, string>("testkey1"));

            Log("TTL testkey4", redis.GetTTL<string>("testkey4"));

            Log("Multi Get", redis.MultiGet<string, string>(new string[] {"testkey1", "testkey2", "testkey4"}));

            Log("Persist testkey4", redis.Persist<string>("testkey4"));

            Log("Rename testkey4 to testkey5", redis.RenameKey<string, string>("testkey4", "testkey5"));

            Log("Get testkey5", redis.Get<string, string>("testkey5"));

            Log("Rename testkey5 NX", redis.RenameKeyIfNotExist<string, string>("testkey5", "testkey6"));

            Log("Get testkey6", redis.Get<string, string>("testkey6"));

            Log("Set testkey1 expiry", redis.SetKeyExpiry<string>("testkey1", 3));

            Log("Set testkey7 with expiry", redis.SetKeyWithExpiry<string, string>("testkey7", 5, "testval7"));

            Log("Length testkey2", redis.Strlen<string>("testkey2"));

            Log("SS add member+score", redis.SSAddMemberWithScore("ss1", 6, "ss1mem1"));

            Log("Get SS1 mem1", redis.SSGetScore("ss1", "ss1mem1"));

            Log("Get SS1 Card", redis.SSGetCardinality("ss1"));

            //Log("Server Info", redis.GetServerInfo());

            //Log("Last save timestamp", redis.GetLastSaveTimestamp());

            //Log("Hash code", redis.GetHashCode());

            Log("DB Size", redis.GetDBSize());

            //redis.ClearAllDB();

            consumer = new RedisSubscription();

            consumer.OnMessageReceived += HandleConsumerOnMessageReceived;
            consumer.OnSubscribe += HandleConsumerOnSubscribe;
            consumer.OnUnsubscribe += HandleConsumerOnUnsubscribe;
            consumer.Subscribe(new string[] {"gameplay"});*/

            //consumer.Unsubscribe(new string[] {"gameplay"});
            //connection.DestroySubscription();
            /*Console.WriteLine(connection.Get<string, string>("vagabond"));
            connection.Set<string, string>("vagabond", "redisU");
            Console.WriteLine(connection.Get<string, string>("vagabond"));
            Console.WriteLine(connection.DeleteKeys<string>("vagabond", "notexixts"));
            Console.WriteLine(connection.GetKeyType<string>("game"));*/
        }
Beispiel #20
0
 public MemoryDoctorEntry(RedisConnection connection, string name, EndPoint endpoint) : base(connection, name)
 {
     Endpoint = endpoint;
 }
        internal async Task <long> InternalCount(RedisConnection connection)
        {
            var result = await connection.Strings.CountSetBits(Db, Key);

            return(result);
        }
Beispiel #22
0
 public RedisOprationTests()
 {
     this.redis = Framework.Container.GetInstance <RedisConnection>("redis");
 }
Beispiel #23
0
 /// <summary>
 /// RedisProducer
 /// </summary>
 /// <param name="redisConnection"></param>
 internal RedisProducer(RedisConnection redisConnection)
 {
     _redisQueue = new RedisQueue(redisConnection);
 }
Beispiel #24
0
        public async Task UpdateLocation(DeviceUpdateLocationModel device)
        {
            try
            {
                var key = KeyPrefix + Context.ConnectionId;

                if (await _rediscache.KeyExistsAsync(key))
                {
                    string udid = await _rediscache.StringGetAsync(key);

                    _logger.LogInformation($"Start UpdateLocation {Context.ConnectionId}, udid: {udid}", Context.ConnectionId, udid);

                    var deviceFromDb = await _deviceService.GetDeviceByUdidAsync(udid);

                    var lastHistoryByDevice = (await _deviceHistoryRepository.GetAsync(x => x.DeviceId == deviceFromDb.Id))
                                              .OrderByDescending(y => y.CreatedOn)
                                              .FirstOrDefault();

                    bool calcIsLocation = CalculateDistanceForDevice.DeviceIsInLocation(
                        deviceFromDb.Latitude,
                        deviceFromDb.Longitude,
                        device.Lat,
                        device.Long,
                        deviceFromDb.Radius);

                    _logger.LogInformation($"location changed devHub: calc {calcIsLocation.ToString()}, lastcurr: " +
                                           $"{lastHistoryByDevice.CurrentDeviceLocationLatitude} {lastHistoryByDevice.CurrentDeviceLocationLongitude} newCoord" +
                                           $"{device.Lat} {device.Long}");

                    if ((calcIsLocation != lastHistoryByDevice.IsInLocation) || (!calcIsLocation))
                    {
                        await AddAndSendDeviceHistory(udid, new DeviceHistory()
                        {
                            CreatedOn = DateTime.UtcNow,
                            IsOnline  = true,
                            CurrentDeviceLocationLatitude  = device.Lat,
                            CurrentDeviceLocationLongitude = device.Long,
                            DeviceLocationLatitude         = deviceFromDb.Latitude,
                            DeviceLocationLongitude        = deviceFromDb.Longitude,
                            DeviceRadius   = deviceFromDb.Radius,
                            LoggedInUserId = lastHistoryByDevice?.LoggedInUserId ?? null,
                            DeviceId       = deviceFromDb.Id,
                            CompanyId      = deviceFromDb.CompanyId,
                            IsInLocation   = calcIsLocation
                        });

                        await _notificationSenderExtention.NotificationForChangeLocation(udid, calcIsLocation);
                    }

                    _logger.LogInformation($"Finish UpdateLocation {Context.ConnectionId}, udid: {udid}", Context.ConnectionId, udid);
                }
                else
                {
                    _logger.LogWarning("Device not found in UpdateLocation");
                }
            }
            catch (RedisConnectionException exm)
            {
                RedisConnection.ForceReconnect();
                _logger.LogError($"Error RedisConnectionException ContextID: {Context.ConnectionId} EXC: {exm.Message} {exm.StackTrace} {exm.Source}");
                return;
            }
            catch (ObjectDisposedException ex)
            {
                RedisConnection.ForceReconnect();
                _logger.LogCritical("Cannot force reconnect to redis cache!!", ex);
            }
        }
Beispiel #25
0
 /// <summary>
 /// Creates instance.
 /// </summary>
 /// <param name="connection"></param>
 /// <param name="key"></param>
 /// <param name="defaultExpiry"></param>
 public RedisString(RedisConnection connection, in RedisKey key, TimeSpan?defaultExpiry)
        static public void Init(string name, string address)
        {
            var config = new RedisConfig(name, address);

            Connection = new RedisConnection(config);
        }
Beispiel #27
0
 public RedisPipelineHandler(RedisConnection connection, RedisTransactionHandler transactionHandler)
 {
     _connection         = connection;
     _transactionhandler = transactionHandler;
     Results             = new Queue <object>();
 }
 private RedisConnectionGateway()
 {
     _connection = getNewConnection();
 }
 /// <summary>
 /// Creates instance.
 /// </summary>
 /// <param name="connection"></param>
 /// <param name="key"></param>
 public RedisLua(RedisConnection connection, in RedisKey key)
Beispiel #30
0
 public InfoViewModel(RedisConnection connection, EndPoint endpoint)
 {
     Connection = connection;
     Endpoint   = endpoint;
     Info       = Connection.Info(Endpoint).GetAwaiter().GetResult();
 }
Beispiel #31
0
 public RedisTransactionHandler(RedisConnection connection)
 {
     _connection = connection;
     _parsers    = new Queue <Delegate>();
 }
Beispiel #32
0
 private void AddConnectionToDataTree(string name, RedisConnection cont)
 {
     if (!string.IsNullOrWhiteSpace(name) && cont != null)
     {
         string desc = GetString(cont.Description, MAX_STRING_LENGTH, true);
         string text = string.IsNullOrWhiteSpace(desc) ?
             name : string.Format("{0} ({1})", name, desc);
         var node = new TreeNode(text);
         node.ImageIndex = 1;
         node.SelectedImageIndex = 1;
         node.Tag = new ConnectionItem(cont, name);
         node.ContextMenu = GetConnectionNodeMenu(node);
         tvDataTree.Nodes.Add(node);
     }
 }
Beispiel #33
0
 private void UpdateStatus(object state)
 {
     //Kinda look bulky but two of them is requrired
     RedisConnection.GetDatabase().StringSetAsync($"server-status:{PlatformRacing3Server.ServerConfig.ServerId}", $"{PlatformRacing3Server.ClientManager.Count} online", TimeSpan.FromSeconds(3), When.Always, CommandFlags.FireAndForget);
     RedisConnection.GetDatabase().PublishAsync("ServerStatusUpdated", $"{PlatformRacing3Server.ServerConfig.ServerId}\0{PlatformRacing3Server.ClientManager.Count} online");
 }
Beispiel #34
0
        internal override ICollection <RedisConnection> CreateRedisConnections()
        {
            if (this.EndPoints == null || !this.EndPoints.Any())
            {
                throw new ArgumentException("No endpoints specified");
            }

            var logger = loggerFactory.CreateLogger <InternallyManagedRedLockConnectionProvider>();

            connections = new List <RedisConnection>(this.EndPoints.Count);

            foreach (var endPoint in this.EndPoints)
            {
                var redisConfig = new ConfigurationOptions
                {
                    AbortOnConnectFail = false,
                    ConnectTimeout     = endPoint.ConnectionTimeout ?? DefaultConnectionTimeout,
                    SyncTimeout        = endPoint.SyncTimeout ?? DefaultSyncTimeout,
                    Ssl                = endPoint.Ssl,
                    Password           = endPoint.Password,
                    ConfigCheckSeconds = endPoint.ConfigCheckSeconds ?? DefaultConfigCheckSeconds
                };

                foreach (var e in endPoint.EndPoints)
                {
                    redisConfig.EndPoints.Add(e);
                }

                var redisConnection = new RedisConnection
                {
                    ConnectionMultiplexer = ConnectionMultiplexer.Connect(redisConfig),
                    RedisDatabase         = endPoint.RedisDatabase ?? DefaultRedisDatabase,
                    RedisKeyFormat        = string.IsNullOrEmpty(endPoint.RedisKeyFormat) ? DefaultRedisKeyFormat : endPoint.RedisKeyFormat
                };

                redisConnection.ConnectionMultiplexer.ConnectionFailed += (sender, args) =>
                {
                    logger.LogWarning($"ConnectionFailed: {args.EndPoint.GetFriendlyName()} ConnectionType: {args.ConnectionType} FailureType: {args.FailureType}");
                };

                redisConnection.ConnectionMultiplexer.ConnectionRestored += (sender, args) =>
                {
                    logger.LogWarning($"ConnectionRestored: {args.EndPoint.GetFriendlyName()} ConnectionType: {args.ConnectionType} FailureType: {args.FailureType}");
                };

                redisConnection.ConnectionMultiplexer.ConfigurationChanged += (sender, args) =>
                {
                    logger.LogDebug($"ConfigurationChanged: {args.EndPoint.GetFriendlyName()}");
                };

                redisConnection.ConnectionMultiplexer.ConfigurationChangedBroadcast += (sender, args) =>
                {
                    logger.LogDebug($"ConfigurationChangedBroadcast: {args.EndPoint.GetFriendlyName()}");
                };

                redisConnection.ConnectionMultiplexer.ErrorMessage += (sender, args) =>
                {
                    logger.LogWarning($"ErrorMessage: {args.EndPoint.GetFriendlyName()} Message: {args.Message}");
                };

                connections.Add(redisConnection);
            }

            return(connections);
        }
Beispiel #35
0
 /// <summary>
 /// Creates instance.
 /// </summary>
 /// <param name="connection"></param>
 /// <param name="key"></param>
 /// <param name="defaultExpiry"></param>
 public RedisDictionary(RedisConnection connection, in RedisKey key, TimeSpan?defaultExpiry)
 public RedisRateLimitCounterStore(RedisConnection connection)
 {
     _connection = connection;
     _connection.RegisterScript("INCREMENT", IncrementScript);
     _connection.RegisterScript("INCREMENT_SLIDING", IncrementScriptSliding);
 }
        public void RedisConnection_WithoutServerAndPort_Test()
        {
            var serviceCollection = Mock.Of <IServiceCollection>();

            Assert.ThrowsException <RedisConnException>(() => RedisConnection.SetupRedisConnection(serviceCollection, null));
        }
Beispiel #38
0
        public static void Main(string[] args)
        {
            redis = new RedisConnection("localhost", 6379);

            redis.ClearAllDB();
            redis.Set <string, int>("sync-counter", 0);
            Counter syncCounter = new Counter();

            syncCounter.Count();

            /*redis._Set<string, string>("testkey1", "testval1");
             *
             * redis._Set<string, string>("testkey2", "testval2");
             *
             * Log("Get testkey1", redis.Get<string, string>("testkey1"));
             *
             * Log("Set testkey1", redis.Set<string, string>("testkey1", "testval1"));
             *
             * Log("Set testkey2", redis.Set<string, string>("testkey2", "testval2"));
             *
             * Log("Set testkey4", redis.Set<string, int>("testkey4",  5));
             *
             * Log("Random key", redis.GetRandomKey());
             *
             * Log("Exist testkey1", redis.IfExists<string>("testkey1"));
             *
             * Log("Exist testkey3", redis.IfExists<string>("testkey3"));
             *
             * Log("Type of testkey2", redis.GetKeyType<string>("testkey2"));
             *
             * Log("Pattern *1", redis.GetKeysByPattern("*1"));
             *
             * Log("Increment testkey4", redis.Increment<string>("testkey4"));
             *
             * Log("Increment testkey4 by 4", redis.IncrementBy<string>("testkey4", 4));
             *
             * Log("Decrement testkey4", redis.Decrement<string>("testkey4"));
             *
             * Log("Decrement testkey4 by 3", redis.DecrementBy<string>("testkey4", 3));
             *
             * Log("Get testkey4", redis.Get<string, string>("testkey4"));
             *
             * Log("Get testkey4", redis.Get<int, string>("testkey4"));
             *
             * Log("Get testkey1", redis.Get<string, string>("testkey1"));
             *
             * Log("TTL testkey4", redis.GetTTL<string>("testkey4"));
             *
             * Log("Multi Get", redis.MultiGet<string, string>(new string[] {"testkey1", "testkey2", "testkey4"}));
             *
             * Log("Persist testkey4", redis.Persist<string>("testkey4"));
             *
             * Log("Rename testkey4 to testkey5", redis.RenameKey<string, string>("testkey4", "testkey5"));
             *
             * Log("Get testkey5", redis.Get<string, string>("testkey5"));
             *
             * Log("Rename testkey5 NX", redis.RenameKeyIfNotExist<string, string>("testkey5", "testkey6"));
             *
             * Log("Get testkey6", redis.Get<string, string>("testkey6"));
             *
             * Log("Set testkey1 expiry", redis.SetKeyExpiry<string>("testkey1", 3));
             *
             * Log("Set testkey7 with expiry", redis.SetKeyWithExpiry<string, string>("testkey7", 5, "testval7"));
             *
             * Log("Length testkey2", redis.Strlen<string>("testkey2"));
             *
             * Log("SS add member+score", redis.SSAddMemberWithScore("ss1", 6, "ss1mem1"));
             *
             * Log("Get SS1 mem1", redis.SSGetScore("ss1", "ss1mem1"));
             *
             * Log("Get SS1 Card", redis.SSGetCardinality("ss1"));
             *
             * //Log("Server Info", redis.GetServerInfo());
             *
             * //Log("Last save timestamp", redis.GetLastSaveTimestamp());
             *
             * //Log("Hash code", redis.GetHashCode());
             *
             * Log("DB Size", redis.GetDBSize());
             *
             * //redis.ClearAllDB();
             *
             * consumer = new RedisSubscription();
             *
             * consumer.OnMessageReceived += HandleConsumerOnMessageReceived;
             * consumer.OnSubscribe += HandleConsumerOnSubscribe;
             * consumer.OnUnsubscribe += HandleConsumerOnUnsubscribe;
             * consumer.Subscribe(new string[] {"gameplay"});*/

            //consumer.Unsubscribe(new string[] {"gameplay"});
            //connection.DestroySubscription();

            /*Console.WriteLine(connection.Get<string, string>("vagabond"));
             * connection.Set<string, string>("vagabond", "redisU");
             * Console.WriteLine(connection.Get<string, string>("vagabond"));
             * Console.WriteLine(connection.DeleteKeys<string>("vagabond", "notexixts"));
             * Console.WriteLine(connection.GetKeyType<string>("game"));*/
        }
Beispiel #39
0
        /// <summary>
        /// redis cluster中重置连接事件
        /// </summary>
        /// <param name="ipPort"></param>
        /// <param name="operationType"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private IResult _redisConnection_OnRedirect(string ipPort, OperationType operationType, params object[] args)
        {
            var cnn = RedisConnectionManager.Get(ipPort);

            var requestType = (RequestType)args[0];

            switch (requestType)
            {
            case RequestType.GET:
            case RequestType.EXISTS:
            case RequestType.SCAN:
            case RequestType.TTL:
            case RequestType.PTTL:
            case RequestType.TYPE:
            case RequestType.HGET:
            case RequestType.HEXISTS:
            case RequestType.HLEN:
            case RequestType.SMEMBERS:
            case RequestType.SISMEMBER:
            case RequestType.SSCAN:
            case RequestType.HSCAN:
            case RequestType.ZSCAN:
            case RequestType.ZSCORE:
            case RequestType.RANDOMKEY:
            case RequestType.ZLEXCOUNT:
            case RequestType.ZCARD:
            case RequestType.ZCOUNT:
            case RequestType.ZRANGE:
            case RequestType.ZRANGEBYLEX:
            case RequestType.ZRANGEBYSCORE:
            case RequestType.ZRANK:
            case RequestType.ZREVRANGE:
            case RequestType.ZREVRANGEBYSCORE:
            case RequestType.ZREVRANK:
            case RequestType.LINDEX:
            case RequestType.LLEN:

                var slave = RedisConnectionManager.Get(ipPort, false);

                if (slave != null)
                {
                    cnn = slave;
                }
                break;
            }

            if (cnn == null || !cnn.IsConnected)
            {
                this.IsConnected = false;
                this.RedisConfig = new RedisConfig(ipPort, this.RedisConfig.Passwords, this.RedisConfig.ActionTimeOut);
                if (_debugModel)
                {
                    cnn = new RedisConnectionDebug(RedisConfig.GetIPPort(), this.RedisConfig.ActionTimeOut);
                }
                else
                {
                    cnn = new RedisConnection(RedisConfig.GetIPPort(), this.RedisConfig.ActionTimeOut);
                }
                cnn.OnRedirect     += _redisConnection_OnRedirect;
                cnn.OnDisconnected += _cnn_OnDisconnected;
                if (cnn.Connect())
                {
                    if (!string.IsNullOrEmpty(this.RedisConfig.Passwords))
                    {
                        cnn.Auth(this.RedisConfig.Passwords);
                    }
                    _cnn             = cnn;
                    this.IsConnected = true;
                    RedisConnectionManager.Set(ipPort, IsMaster, cnn);
                }
                else
                {
                    throw new Exception($"当前节点不可达ipport:{ipPort}");
                }
            }
            else
            {
                _cnn = cnn;
            }

            switch (operationType)
            {
            case OperationType.Do:
                return(_cnn.Do((RequestType)args[0]));

            case OperationType.DoBatchWithList:
                return(_cnn.DoMultiLineWithList((RequestType)args[0], (string)args[1], (List <string>)args[2]));

            case OperationType.DoBatchWithDic:
                return(_cnn.DoMultiLineWithDic((RequestType)args[0], (Dictionary <string, string>)args[1]));

            case OperationType.DoBatchWithIDDic:
                return(_cnn.DoBatchWithIDDic((RequestType)args[0], (string)args[1], (Dictionary <string, string>)args[2]));

            case OperationType.DoBatchZaddWithIDDic:
                return(_cnn.DoBatchZaddWithIDDic((RequestType)args[0], (string)args[1], (Dictionary <double, string>)args[2]));

            case OperationType.DoBatchWithIDKeys:
                return(_cnn.DoBatchWithIDKeys((RequestType)args[0], (string)args[1], (string[])args[3]));

            case OperationType.DoBatchWithParams:
                return(_cnn.DoWithMutiParams((RequestType)args[0], (string[])args[1]));

            case OperationType.DoCluster:
                return(_cnn.DoMutiCmd((RequestType)args[0], (object[])args[1]));

            case OperationType.DoClusterSetSlot:
                return(_cnn.DoClusterSetSlot((RequestType)args[0], (string)args[1], (int)args[2], (string)args[3]));

            case OperationType.DoExpire:
                return(_cnn.DoExpire((string)args[0], (int)args[1]));

            case OperationType.DoExpireAt:
                return(_cnn.DoExpireAt((string)args[0], (int)args[1]));

            case OperationType.DoExpireInsert:
                return(_cnn.DoExpireInsert((RequestType)args[0], (string)args[1], (string)args[2], (int)args[3]));

            case OperationType.DoWithID:
                return(_cnn.DoWithID((RequestType)args[0], (string)args[1], (string)args[2], (string)args[3]));

            case OperationType.DoRang:
                return(_cnn.DoRang((RequestType)args[0], (string)args[1], (double)args[2], (double)args[3]));

            case OperationType.DoRangByScore:
                return(_cnn.DoRangByScore((RequestType)args[0], (string)args[1], (double)args[2], (double)args[3], (RangType)args[4], (long)args[5], (int)args[6], (bool)args[7]));

            case OperationType.DoScan:
                return(_cnn.DoScan((RequestType)args[0], (int)args[1], (string)args[2], (int)args[3]));

            case OperationType.DoScanKey:
                return(_cnn.DoScanKey((RequestType)args[0], (string)args[1], (int)args[2], (string)args[3], (int)args[4]));

            case OperationType.DoSub:
                _cnn.DoSub((string[])args[0], (Action <string, string>)args[1]);
                break;

            case OperationType.DoWithKey:
                return(_cnn.DoWithKey((RequestType)args[0], (string)args[1]));

            case OperationType.DoWithKeyValue:
                return(_cnn.DoWithKeyValue((RequestType)args[0], (string)args[1], (string)args[2]));

            default:
                return(null);
            }
            return(null);
        }
Beispiel #40
0
        public override async Task OnDisconnectedAsync(Exception ex)
        {
            try
            {
                var key = KeyPrefix + Context.ConnectionId;

                if (await _rediscache.KeyExistsAsync(key))
                {
                    string udid = await _rediscache.StringGetAsync(key);

                    _logger.LogInformation($"Start OnDisconnectedAsync {Context.ConnectionId}, udid: {udid}", Context.ConnectionId, udid);

                    string udidPrefix = KeyPrefix + udid;

                    string currentKeyInRedis = await _rediscache.StringGetAsync(udidPrefix);

                    if (!string.IsNullOrEmpty(currentKeyInRedis) && currentKeyInRedis.Equals(Context.ConnectionId))
                    {
                        var deviceFromDb = await _deviceService.GetDeviceByUdidAsync(udid);

                        var lastHistoryByDevice = (await _deviceHistoryRepository.GetAsync(x => x.DeviceId == deviceFromDb.Id))
                                                  .OrderByDescending(y => y.CreatedOn)
                                                  .FirstOrDefault();

                        await AddAndSendDeviceHistory(udid, new DeviceHistory()
                        {
                            CreatedOn = DateTime.UtcNow,
                            IsOnline  = false,
                            CurrentDeviceLocationLatitude  = lastHistoryByDevice?.CurrentDeviceLocationLatitude ?? deviceFromDb.Latitude,
                            CurrentDeviceLocationLongitude = lastHistoryByDevice?.CurrentDeviceLocationLongitude ?? deviceFromDb.Longitude,
                            DeviceLocationLatitude         = deviceFromDb.Latitude,
                            DeviceLocationLongitude        = deviceFromDb.Longitude,
                            DeviceRadius   = deviceFromDb.Radius,
                            LoggedInUserId = lastHistoryByDevice?.LoggedInUserId ?? null,
                            DeviceId       = deviceFromDb.Id,
                            CompanyId      = deviceFromDb.CompanyId,
                            IsInLocation   = lastHistoryByDevice?.IsInLocation ?? true
                        });

                        _logger.LogDebug("Before Send Notification in DeviceHub");
                        await _notificationSenderExtention.SendAlertOnOffLinePrepareByExpirationTime(SelectFunc.Offline, udid);

                        await _rediscache.KeyDeleteAsync(udidPrefix);
                    }

                    await _rediscache.KeyDeleteAsync(key);

                    _logger.LogInformation($"Finish OnDisconnectedAsync: {Context.ConnectionId}, udid: {udid}", Context.ConnectionId, udid);
                }
                else
                {
                    _logger.LogDebug("Redis key not found OnDisconnectedAsync");
                }

                _memoryCache.Remove(Context.ConnectionId);

                await base.OnDisconnectedAsync(ex);
            }
            catch (RedisConnectionException exm)
            {
                RedisConnection.ForceReconnect();
                _logger.LogError($"Error RedisConnectionException ContextID: {Context.ConnectionId} EXC: {exm.Message} {exm.StackTrace} {exm.Source}");
                return;
            }
            catch (Exception exm)
            {
                _logger.LogError($"Error OnDisconnectedAsync ContextID: {Context.ConnectionId} EXC: {exm.Message} {exm.StackTrace} {exm.Source}");
            }
        }
Beispiel #41
0
 /// <summary>
 /// changkey error occurred while removing more than 3 times.
 /// </summary>
 /// <param name="client"></param>
 /// <param name="key"></param>
 /// <param name="buffer"></param>
 public void ChangeKeyError(RedisConnection client, string key, byte[] buffer)
 {
     int errorCount;
     if (!_changeKeyError.TryGetValue(key, out errorCount))
     {
         errorCount = 1;
         _changeKeyError[key] = errorCount;
     }
     else
     {
         errorCount++;
         _changeKeyError[key] = errorCount;
     }
     if (errorCount > 2)
     {
         RemoveKey(client, buffer);
         _changeKeyError.TryRemove(key, out errorCount);
     }
 }
Beispiel #42
0
        public override async Task OnConnectedAsync()
        {
            try
            {
                var    httpContext = Context.Features.Get <IHttpContextFeature>().HttpContext;
                string udid        = httpContext.Request.Query["udid"];
                string udidPrefix  = KeyPrefix + udid;
                var    key         = KeyPrefix + Context.ConnectionId;

                _logger.LogInformation($"Start OnConnectedAsync {Context.ConnectionId} udid: {udid}", Context.ConnectionId, udid);
                _badDisconnectSocketService.InitConnectionMonitoring(Context);

                await _rediscache.StringSetAsync(key, udid);

                if (await _rediscache.KeyExistsAsync(udidPrefix))
                {
                    string oldConnectionId = await _rediscache.StringGetSetAsync(udidPrefix, Context.ConnectionId);

                    _badDisconnectSocketService.DisconnectClient(oldConnectionId);
                }
                else
                {
                    await _rediscache.StringSetAsync(udidPrefix, Context.ConnectionId);
                }

                var deviceFromDb = await _deviceService.GetDeviceByUdidAsync(udid);

                if (deviceFromDb == null)
                {
                    await _deviceService.Setup(new SetupDeviceRequest { Udid = udid });

                    deviceFromDb = await _deviceService.GetDeviceByUdidAsync(udid);

                    var lastHistoryByDevice = (await _deviceHistoryRepository.GetAsync(x => x.DeviceId == deviceFromDb.Id))
                                              .OrderByDescending(y => y.CreatedOn)
                                              .FirstOrDefault();

                    await AddAndSendDeviceHistoryToAll(CreateDeviceHistoryOnConnect(deviceFromDb, lastHistoryByDevice));
                }
                else
                {
                    var lastHistoryByDevice = (await _deviceHistoryRepository.GetAsync(x => x.DeviceId == deviceFromDb.Id))
                                              .OrderByDescending(y => y.CreatedOn)
                                              .FirstOrDefault();

                    await AddAndSendDeviceHistory(udid, CreateDeviceHistoryOnConnect(deviceFromDb, lastHistoryByDevice));

                    await _notificationSenderExtention.SendAlertOnOffLinePrepareByExpirationTime(SelectFunc.Online, udid);
                }

                await base.OnConnectedAsync();

                _memoryCache.Set(Context.ConnectionId, string.Empty, GetCacheEntryOptions());
                _logger.LogInformation($"Finish OnConnectedAsync: {Context.ConnectionId}, udid: {udid}", Context.ConnectionId, udid);
            }
            catch (RedisConnectionException exm)
            {
                RedisConnection.ForceReconnect();
                _logger.LogError($"Error RedisConnectionException ContextID: {Context.ConnectionId} EXC: {exm.Message} {exm.StackTrace} {exm.Source}");
            }
            catch (ObjectDisposedException ex)
            {
                RedisConnection.ForceReconnect();
                _logger.LogCritical("Cannot force reconnect to redis cache!!", ex);
            }
        }
Beispiel #43
0
 public void UpdateSqlKey(RedisConnection client, Dictionary<string, bool> dict)
 {
     string setId = GlobalRedisKey + "_temp";
     if (dict.Count == 0)
     {
         client.Remove(setId);
     }
     else
     {
         var data = ProtoBufUtils.Serialize(dict);
         client.Set(setId, data);
     }
 }
 /// <summary>
 /// 放入连接池
 /// </summary>
 /// <param name="connection"></param>
 public static void Put(RedisConnection connection)
 {
     if (_connectionPools.Count > PoolMaxSize)
     {
         return;
     }
     _connectionPools.Enqueue(connection);
 }
Beispiel #45
0
        private Task ConnectToRedis()
        {
            if (_connection != null)
            {
                _connection.Closed -= OnConnectionClosed;
                _connection.Error -= OnConnectionError;
                _connection.Dispose();
                _connection = null;
            }

            // Create a new connection to redis with the factory
            RedisConnection connection = _connectionFactory();

            connection.Closed += OnConnectionClosed;
            connection.Error += OnConnectionError;

            try
            {
                _trace.TraceInformation("Connecting...");

                // Start the connection
                return connection.Open().Then(() =>
                {
                    _trace.TraceInformation("Connection opened");

                    // Create a subscription channel in redis
                    RedisSubscriberConnection channel = connection.GetOpenSubscriberChannel();
                    channel.CompletionMode = ResultCompletionMode.PreserveOrder;

                    // Subscribe to the registered connections
                    return channel.Subscribe(_key, OnMessage).Then(() =>
                    {
                        _trace.TraceVerbose("Subscribed to event " + _key);

                        _channel = channel;
                        _connection = connection;
                    });
                });
            }
            catch (Exception ex)
            {
                _trace.TraceError("Error connecting to Redis - " + ex.GetBaseException());

                return TaskAsyncHelper.FromError(ex);
            }
        }
        private void UseConnections(Action<IDatabase, RedisConnection> action)
        {
			var redis = RedisUtils.CreateClient();
            using (var connection = new RedisConnection(redis, RedisUtils.CreateSubscriber()))
            {
				action(redis, connection);
            }
        }
Beispiel #47
0
 /// <summary>
 /// Creates instance.
 /// </summary>
 /// <param name="connection"></param>
 /// <param name="key"></param>
 public RedisLock(RedisConnection connection, RedisKey key)
 {
     this.Connection = connection ?? throw new ArgumentNullException(nameof(connection));
     this.Key        = key;
 }
        private Task ConnectToRedis()
        {
            if (_connection != null)
            {
                _connection.Closed -= OnConnectionClosed;
                _connection.Error -= OnConnectionError;
                _connection.Dispose();
                _connection = null;
            }

            // Create a new connection to redis with the factory
            RedisConnection connection = _connectionFactory();

            connection.Closed += OnConnectionClosed;
            connection.Error += OnConnectionError;

            try
            {
                Trace.TraceInformation("Connecting...");

                // Start the connection
                return connection.Open().Then(() =>
                {
                    Trace.TraceInformation("Connection opened");

                    // Create a subscription channel in redis
                    RedisSubscriberConnection channel = connection.GetOpenSubscriberChannel();

                    // Subscribe to the registered connections
                    channel.Subscribe(_key, OnMessage);

                    // Dirty hack but it seems like subscribe returns before the actual
                    // subscription is properly setup in some cases
                    while (channel.SubscriptionCount == 0)
                    {
                        Thread.Sleep(500);
                    }

                    Trace.TraceVerbose("Subscribed to event " + _key);

                    _channel = channel;
                    _connection = connection;
                });
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error connecting to redis - " + ex.GetBaseException());

                return TaskAsyncHelper.FromError(ex);
            }
        }
Beispiel #49
0
        /// <summary>
        /// pop sql change keys
        /// </summary>
        /// <param name="client"></param>
        public Dictionary<string, bool> PopSql(RedisConnection client)
        {
            Dictionary<string, bool> dict = null;

            string setId = GlobalRedisKey + "_temp";
            bool hasKey = client.ContainsKey(GlobalRedisKey);
            bool hasSetId = client.ContainsKey(setId);
            if (!hasSetId && !hasKey)
            {
                return dict;
            }
            if (!hasSetId && hasKey)
            {
                try
                {
                    client.Rename(GlobalRedisKey, setId);
                }
                catch
                {
                }
            }
            byte[] data = client.Get<byte[]>(setId) ?? new byte[0];
            dict = ProtoBufUtils.Deserialize<Dictionary<string, bool>>(data);

            return dict;
        }
Beispiel #50
0
 public void RemoveKey(RedisConnection client, byte[] buffer)
 {
     string setId = GlobalChangeKey + "_temp";
     client.ZRemove(setId, buffer);
 }
Beispiel #51
0
        /// <summary>
        /// redis cluster中重置连接事件
        /// </summary>
        /// <param name="ipPort"></param>
        /// <param name="operationType"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private Interface.IResult _redisConnection_OnRedirect(string ipPort, OperationType operationType, params object[] args)
        {
            var cnn = RedisConnectionManager.Get(ipPort);

            if (cnn == null)
            {
                this.IsConnected = false;
                this.RedisConfig = new RedisConfig(ipPort, this.RedisConfig.Passwords, this.RedisConfig.ActionTimeOut);
                if (_debugModel)
                {
                    cnn = new RedisConnectionDebug(RedisConfig.GetIPPort(), this.RedisConfig.ActionTimeOut);
                }
                else
                {
                    cnn = new RedisConnection(RedisConfig.GetIPPort(), this.RedisConfig.ActionTimeOut);
                }
                cnn.OnRedirect     += _redisConnection_OnRedirect;
                cnn.OnDisconnected += _cnn_OnDisconnected;
                this.Connect();
                RedisConnectionManager.Set(ipPort, cnn);
            }

            _cnn = cnn;


            switch (operationType)
            {
            case OperationType.Do:
                return(_cnn.Do((RequestType)args[0]));

            case OperationType.DoBatchWithDic:
                return(_cnn.DoBatchWithDic((RequestType)args[0], (Dictionary <string, string>)args[1]));

            case OperationType.DoBatchWithIDDic:
                return(_cnn.DoBatchWithIDDic((RequestType)args[0], (string)args[1], (Dictionary <double, string>)args[2]));

            case OperationType.DoBatchWithIDKeys:
                return(_cnn.DoBatchWithIDKeys((RequestType)args[0], (string)args[1], (string[])args[3]));

            case OperationType.DoBatchWithParams:
                return(_cnn.DoBatchWithParams((RequestType)args[0], (string[])args[1]));

            case OperationType.DoCluster:
                return(_cnn.DoCluster((RequestType)args[0], (object[])args[1]));

            case OperationType.DoClusterSetSlot:
                return(_cnn.DoClusterSetSlot((RequestType)args[0], (string)args[1], (int)args[2], (string)args[3]));

            case OperationType.DoExpire:
                _cnn.DoExpire((string)args[0], (int)args[1]);
                break;

            case OperationType.DoExpireInsert:
                _cnn.DoExpireInsert((RequestType)args[0], (string)args[1], (string)args[2], (int)args[3]);
                break;

            case OperationType.DoHash:
                return(_cnn.DoHash((RequestType)args[0], (string)args[1], (string)args[2], (string)args[3]));

            case OperationType.DoInOne:
                return(_cnn.DoInOne((RequestType)args[0], (string)args[1]));

            case OperationType.DoRang:
                return(_cnn.DoRang((RequestType)args[0], (string)args[1], (double)args[2], (double)args[3]));

            case OperationType.DoScan:
                return(_cnn.DoScan((RequestType)args[0], (int)args[1], (string)args[2], (int)args[3]));

            case OperationType.DoScanKey:
                return(_cnn.DoScanKey((RequestType)args[0], (string)args[1], (int)args[2], (string)args[3], (int)args[4]));

            case OperationType.DoSub:
                _cnn.DoSub((string[])args[0], (Action <string, string>)args[1]);
                break;

            case OperationType.DoWithKey:
                return(_cnn.DoWithKey((RequestType)args[0], (string)args[1]));

            case OperationType.DoWithKeyValue:
                return(_cnn.DoWithKeyValue((RequestType)args[0], (string)args[1], (string)args[2]));

            default:
                return(null);
            }
            return(null);
        }
        /// <summary>
        /// Invokes events will be occurred during the service start.
        /// </summary>
        protected override void ServiceStart()
        {
            if (!this.firstInit)
            {
                return;
            }

            this.firstInit = false;

            if (this.Configuration != null)
            {
                Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(this.Configuration.Culture);
            }

            this.Log.Write(LogLevel.Info, "Tasslehoff 0.9.7  (c) 2008-2016 Eser Ozvataf ([email protected]). All rights reserved.");
            this.Log.Write(LogLevel.Info, "This program is free software under the terms of the GPL v3 or later.");
            this.Log.Write(LogLevel.Info, string.Empty);

            if (this.Configuration != null)
            {
                if (!string.IsNullOrEmpty(this.Configuration.DatabaseConnectionString))
                {
                    this.DatabaseManager.Connections.Add(
                        this.DatabaseManager.DefaultDatabaseKey,
                        new DatabaseManagerConnection()
                        {
                            ProviderName = this.Configuration.DatabaseProviderName,
                            ConnectionString = this.Configuration.DatabaseConnectionString,
                        }
                    );
                }

                // search for extensions
                if (this.Configuration.ExtensionPaths != null)
                {
                    this.ExtensionFinder.SearchStructured(this.Configuration.ExtensionPaths);
                }
            }

            this.Log.Write(LogLevel.Info, string.Format("{0} extensions found:", this.ExtensionFinder.Assemblies.Count));
            foreach (string assemblyName in this.ExtensionFinder.Assemblies.Keys)
            {
                this.Log.Write(LogLevel.Info, string.Format("- {0}", assemblyName));
            }
            this.Log.Write(LogLevel.Info, string.Empty);

            if (this.Configuration != null)
            {
                if (!string.IsNullOrEmpty(this.Configuration.RabbitMQAddress))
                {
                    IQueueManager rabbitMq = new RabbitMQConnection(this.Configuration.RabbitMQAddress);
                    this.AddChild(rabbitMq);
                }

                if (!string.IsNullOrEmpty(this.Configuration.IronMQProjectId))
                {
                    IQueueManager ironMq = new IronMQConnection(this.Configuration.IronMQProjectId, this.Configuration.IronMQToken);
                    this.AddChild(ironMq);
                }

                if (!string.IsNullOrEmpty(this.Configuration.MemcachedAddress))
                {
                    ICacheManager memcached = new MemcachedConnection(this.Configuration.MemcachedAddress);
                    this.AddChild(memcached);
                }

                if (!string.IsNullOrEmpty(this.Configuration.RedisAddress))
                {
                    ICacheManager redis = new RedisConnection(this.Configuration.RedisAddress);
                    this.AddChild(redis);
                }

                if (!string.IsNullOrEmpty(this.Configuration.ElasticSearchAddress))
                {
                    ICacheManager elasticSearch = new ElasticSearchConnection(new Uri(this.Configuration.ElasticSearchAddress));
                    this.AddChild(elasticSearch);
                }
            }
        }
 public VerifyErrorCounts(string queueName, string connectionString)
 {
     var connection = new BaseConnectionInformation(queueName, connectionString);
     _redisNames = new RedisNames(connection);
     _connection = new RedisConnection(connection);
 }
Beispiel #54
0
 public RedisClient(RedisServer server, IConnectionLog log = null)
 {
     _connection = new RedisConnection(server, log);
 }
Beispiel #55
0
 public RedisCacheManager(IDistributedCache cache, DistributedCacheEntryOptions options,RedisConnection redisConnection)
 {
     _redisConnection = redisConnection;
     _options = options;
     _distributedCache = cache;
 }
 public SendContext(string key, IList<Message> messages, RedisConnection connection)
 {
     Key = key;
     Messages = messages;
     Connection = connection;
 }
Beispiel #57
0
 /// <summary>
 /// get entity keys
 /// </summary>
 /// <param name="client"></param>
 /// <param name="min"></param>
 /// <param name="max"></param>
 /// <returns></returns>
 public byte[][] GetKeys(RedisConnection client, int min = 0, int max = 0)
 {
     if (max == 0)
     {
         max = int.MaxValue;
     }
     string key = GlobalChangeKey;
     string setId = key + "_temp";
     try
     {
         bool hasKey = client.ContainsKey(key);
         bool hasSetId = client.ContainsKey(setId);
         if (!hasSetId && !hasKey)
         {
             return null;
         }
         if (!hasSetId && hasKey)
         {
             try
             {
                 client.Rename(key, setId);
             }
             catch { }
         }
         byte[][] buffers = client.ZRange(setId, min, max);
         if (buffers == null || buffers.Length == 0)
         {
             client.Remove(setId);
         }
         return buffers;
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("Entity change key Pop setId:{0} error:{1}", setId, ex);
     }
     return null;
 }