コード例 #1
0
 /// <summary>
 /// 关闭连接
 /// </summary>
 public static void Dispose()
 {
     _conn?.Close();
     _dbIndex = -1;
     _logger  = null;
     _prefix  = null;
 }
コード例 #2
0
 public void Dispose()
 {
     _connection?.Close();
     _connection?.Dispose();
     _redisLockFactory?.Dispose();
     _connection       = null;
     _redisLockFactory = null;
 }
コード例 #3
0
ファイル: Program.cs プロジェクト: Half-Shot/matrix-cache
        static void Main(string[] args)
        {
            Console.WriteLine($"Connecting to Redis at {REDIS_URL}");
            try
            {
                redis = ConnectionMultiplexer.Connect(REDIS_URL);
                db    = redis.GetDatabase();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to start redis: {0}", ex);
                redis?.Close();
                Environment.Exit(1);
            }
            try
            {
                var opts = new ServiceRegistrationOptions
                {
                    sender_localpart = "mc",
                    as_token         = "foobar",
                    hs_token         = "foobar",
                    id         = "matrix-cached",
                    url        = "http://*****:*****@_xmpp_.*",
                });
                var reg = new ServiceRegistration(opts);
                appservice          = new MatrixAppservice(reg, "localhost", "http://localhost:8008");
                appservice.OnEvent += AppserviceOnOnEvent;
                Thread t = new Thread(listenForRequests);
                t.Start();
                appservice.Run();
                t.Join();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to start appservice: {0}", ex);
                redis.Close();
                Environment.Exit(1);
            }
        }
コード例 #4
0
ファイル: RedisCache.cs プロジェクト: zhuiyi220/aspnetcore
        /// <inheritdoc />
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true;
            _connection?.Close();
        }
コード例 #5
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
             _redis?.Close();
         }
         _disposed = true;
     }
 }
コード例 #6
0
        private void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                if (disposing)
                {
                    _connection?.Close();
                }

                _isDisposed = true;
            }
        }
コード例 #7
0
        public void Close()
        {
            _connectionMultiplexer?.Close(allowCommandsToComplete: false);
            _connectionMultiplexer?.Dispose();

            if (_process != null)
            {
                SafeKillProcess();
            }

            _tempDirectory.Dispose();
            _fileSystem.Dispose();
            Closed = true;
        }
コード例 #8
0
        public void Close()
        {
            _connectionMultiplexer?.Close(allowCommandsToComplete: false);
            _connectionMultiplexer?.Dispose();

            if (_process != null)
            {
                _logger.Debug($"Killing the redis process {_process?.Id}...");
                SafeKillProcess();
            }

            _tempDirectory.Dispose();
            _fileSystem.Dispose();
            Closed = true;
        }
コード例 #9
0
        /// <summary>
        /// Example for basic usage of RedisTimeSeries RANGE command with "-" and "+" as range boundreis, a filter and MIN aggregation.
        /// NRedisTimeSeris MRange is expecting two TimeStamps objects as the range boundries.
        /// In this case, the strings are implicitly casted into TimeStamp objects.
        /// The TimeSeriesMRange command returns an IReadOnlyList (collection) of (string key, IReadOnlyList(TimeSeriesLabel) labels, IReadOnlyList(TimeSeriesTuple) values).
        /// </summary>
        public static void MRangeAggregationExample()
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            IDatabase             db    = redis.GetDatabase();
            var filter = new List <string> {
                "MRANGEkey=MRANGEvalue"
            };
            var results = db.TimeSeriesMRange("-", "+", filter, aggregation: TsAggregation.Min, timeBucket: 50);

            // Values extraction example. No lables in this case.
            foreach (var result in results)
            {
                Console.WriteLine(result.key);
                IReadOnlyList <TimeSeriesTuple> values = result.values;
                foreach (TimeSeriesTuple val in values)
                {
                    Console.WriteLine(val);
                }
            }
            redis.Close();
        }
コード例 #10
0
ファイル: Start.cs プロジェクト: sven-spanheimer/redis_test
        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            try
            {
                if (redis == null || !redis.IsConnected)
                {
                    throw new Exception("Verbindung ist nicht aufgebaut und kann daher nicht beendet werden!");
                }
                redis.Close();
                btnStartConnection.Enabled = true;
                btnDisconnect.Enabled      = false;
                btnServerStatus.Enabled    = false;
                btnTestTool.Enabled        = false;

                btnStartConnection.Focus();
            }
            catch (Exception ex)
            {
                DarkMessageBox.ShowError(ex.Message, "Fehler");
            }
        }
コード例 #11
0
ファイル: CBRedis.cs プロジェクト: yshong93/CloudBread
        /// @brief Get selected rank range members.
        /// Get my rank and then call this method to fetch +-10 rank(total 20) rank
        public static SortedSetEntry[] GetSortedSetRankByRange(long startRank, long endRank)
        {
            ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(redisConnectionStringRank);

            try
            {
                IDatabase cache = connection.GetDatabase(1);
                //SortedSetEntry[] rank = cache.SortedSetRangeByScoreWithScores(globalVal.CloudBreadRankSortedSet, startRank, endRank, Exclude.None, Order.Descending);
                SortedSetEntry[] se = cache.SortedSetRangeByRankWithScores(globalVal.CloudBreadRankSortedSet, startRank, endRank, Order.Descending);
                //return JsonConvert.SerializeObject(se);

                connection.Close();
                connection.Dispose();

                return(se);
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #12
0
ファイル: CBRedis.cs プロジェクト: cupercuper/ServerChecker
        /// @brief get socket auth key redis data by key value
        public static string GetRedisKeyValue(string key)
        {
            string result = "";
            ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(redisConnectionStringSocket);

            // try to connect database
            try
            {
                // StringGet task
                IDatabase cache = connection.GetDatabase(0);
                result = cache.StringGet(key);

                connection.Close();
                connection.Dispose();

                return(result);
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #13
0
        public static bool UnLockByRedis(string key)
        {
            ConnectionMultiplexer conn = ConnectionMultiplexer.Connect(ConnectionRedisStr);

            try
            {
                IDatabase database1 = conn.GetDatabase();
                return(database1.LockRelease(key, Thread.CurrentThread.ManagedThreadId));
            }
            catch (Exception ex)
            {
                throw new Exception($"Redis加锁异常:原因{ex.Message}");
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
コード例 #14
0
 // Check if key "device:860585005101885" exists
 public bool Exist(string key = "860585005101885")
 {
     try
     {
         ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(connectionString);
         IDatabase             db    = redis.GetDatabase(0);
         var isExist = db.KeyExists("device:" + key);
         if (redis != null)
         {
             redis.Close();
         }
         if (isExist)
         {
             return(true);
         }
         return(false);
     }
     catch (Exception err)
     {
         return(false);
     }
 }
コード例 #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Please, enter your username to connect to the chat system:");
            var username = Console.ReadLine();

            if (!Connect(username))
            {
                Console.WriteLine("Cannot connect, try run again");
                return;
            }

            Console.WriteLine("To end this chat just press Enter");
            Console.WriteLine("Please, enter target username and message to him. For example: @Bob Let's party");
            string msg;

            do
            {
                msg = Console.ReadLine();
                SendMessage(username, msg);
            } while (!string.IsNullOrEmpty(msg));
            subscriber.Unsubscribe(username);
            connection.Close(false);
        }
コード例 #16
0
        static void Main(string[] args)
        {
            if (!(args.Length == 3 || args.Length == 4))
            {
                Console.WriteLine("Usage host port service password");
                System.Environment.Exit(1);
            }
            sentinelHost = args[0];
            sentinelPort = int.Parse(args[1]);
            serviceName  = args[2];
            if (args.Length == 4)
            {
                password = args[3];
            }

            ConnectionMultiplexer redis = getMultiplexer();

            IDatabase db = redis.GetDatabase();

            Console.WriteLine("Set foo: " + db.StringSet("foo", "bar"));
            Console.WriteLine("Get foo: " + db.StringGet("foo"));
            redis.Close();
        }
コード例 #17
0
 static void Main(string[] args)
 {
     //estabelecer a conexão com Redis
     using (ConnectionMultiplexer connectionRedis = ConnectionMultiplexer.Connect("localhost:13919,password=senhadoredis"))
     {
         //obter o database para envio de comandos ao Redis
         IDatabase clientRedis = connectionRedis.GetDatabase();
         //gravando uma chave
         clientRedis.StringSet("admin_sistema", "Desenvolvedor Ninja");
         //lendo uma chave
         Console.WriteLine(clientRedis.StringGet("admin_sistema"));
         //definindo 600 segundos como tempo de expiração
         clientRedis.KeyExpire("admin_sistema", TimeSpan.FromSeconds(600));
         //consultando o tempo de expiração da chave
         Console.WriteLine(clientRedis.KeyTimeToLive("admin_sistema"));
         //retirando o tempo de expiração da chave tornando-a permanente
         clientRedis.KeyPersist("admin_sistema");
         //apagando uma chave
         clientRedis.KeyDelete("admin_sistema");
         //fechando a conexão com o Redis
         connectionRedis.Close();
     }
 }
コード例 #18
0
        /// <summary>
        /// Example for basic usage of RedisTimeSeries MGET command with a filter and WITHLABELS flag.
        /// The NRedisTimeSeries SimpleMGetExample returns and IReadOnlyList<(string key, IReadOnlyList<TimeSeriesLabel> labels, TimeSeriesTuple value)> collection.
        /// </summary>
        public static async Task MGetWithLabelsAsyncExample()
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            IDatabase             db    = redis.GetDatabase();
            var filter = new List <string> {
                "key=value"
            };
            var results = await db.TimeSeriesMGetAsync(filter, withLabels : true);

            // Values extraction example.
            foreach (var result in results)
            {
                Console.WriteLine(result.key);
                IReadOnlyList <TimeSeriesLabel> labels = result.labels;
                foreach (TimeSeriesLabel label in labels)
                {
                    Console.WriteLine(label);
                }
                TimeSeriesTuple value = result.value;
                Console.WriteLine(value);
            }
            redis.Close();
        }
コード例 #19
0
        // Save or Update
        public int Save(RecordEvent e)
        {
            try
            {
                ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(connectionString);
                IDatabase             db    = redis.GetDatabase(0);

                db.HashSet("device:" + e.Serial, new[] {
                    new HashEntry("serial", e.Serial),
                    new HashEntry("is_moving", e.IsMoving),
                    new HashEntry("speed", e.Speed),
                    new HashEntry("event_code", e.EventCode),
                    new HashEntry("event_time", e.EventTime.ToUniversalTime().ToString()),
                });

                redis.Close();
                return(1);
            }
            catch (Exception err)
            {
                return(-1);
            }
        }
コード例 #20
0
        public IDatabase GetDatabase(string serverName)
        {
            lock (_syncObj)
            {
                ConnectionMultiplexer cm = null;
                _cmList.TryGetValue(serverName, out cm);

                if (cm != null && cm.IsConnected)
                {
                    return(cm.GetDatabase(0));
                }

                if (cm != null)
                {
                    cm.Close(false);
                    cm.Dispose();
                    _cmList.TryRemove(serverName, out cm);
                }

                var masterServers = RedisServer.ConfigDict[serverName].MasterSettings;
                var salveServers  = RedisServer.ConfigDict[serverName].SlaveSettings;
                var options       = new ConfigurationOptions();
                var allServers    = masterServers.Concat(salveServers).Distinct();
                foreach (var server in allServers)
                {
                    options.EndPoints.Add(server.Host, server.Port);
                }
                options.AbortOnConnectFail = false;
                options.AllowAdmin         = true;
                options.SyncTimeout        = 10000; //同步超时 3S

                cm = ConnectionMultiplexer.Connect(options);
                _cmList.TryAdd(serverName, cm);

                return(cm.GetDatabase(0));
            }
        }
コード例 #21
0
ファイル: RedisClient.cs プロジェクト: gaoshoufenmu/NoSqlDemo
        public void ResetConn()
        {
            lock (_lock)
            {
                if (_manager == null || !_manager.IsConnected)
                {
                    _mres.Reset();

                    if (_manager != null)
                    {
                        _manager.Close();
                        _manager.Dispose();
                        _manager = null;
                    }

                    for (int i = 0; i < 10; i++)
                    {
                        try
                        {
                            _manager = ConnectionMultiplexer.Connect(_connStr, _sw);
                            _sw.Flush();
                            _mres.Set();
                            return;
                        }
                        catch (Exception e)
                        {
                            Thread.Sleep(500);
                            if (i == 9)
                            {
                                _mres.Set();
                                throw new Exception("faild 9 times when do redis re-connecting operation", e);
                            }
                        }
                    }
                }
            }
        }
コード例 #22
0
ファイル: RedisConnection.cs プロジェクト: shihyuyu/SignalR
        public void Close(string key, bool allowCommandsToComplete = true)
        {
            lock (_shutdownLock)
            {
                if (_disposed)
                {
                    return;
                }

                _trace.TraceInformation("Closing key: " + key);
                if (_redisSubscriber != null)
                {
                    _redisSubscriber.Unsubscribe(key);
                }

                if (_connection != null)
                {
                    _connection.Close(allowCommandsToComplete);
                }

                _connection.Dispose();
                _disposed = true;
            }
        }
コード例 #23
0
 public void Close()
 {
     redisMultiplexer.Close();
 }
コード例 #24
0
 public static void Init()
 {
     conn.Close();
     dbNum = GameEnvironment.RedisConfig.RedisDB;
     conn  = RedisConnectionHelp.Instance;
 }
コード例 #25
0
        static void Main(string[] args)
        {
            Console.WriteLine("Reading Config...");
            IConfigReader cr = new ConfigReader();

            if (!cr.ConfigReadSuccess)
            {
                Console.ReadKey();
                return;
            }

            GlobalConfig.SetConfig(cr);

            Console.WriteLine("Attempting To Connect to MySQL database...");
            MySql.Data.MySqlClient.MySqlConnection test_connection = new MySql.Data.MySqlClient.MySqlConnection(cr.MySQLDBConnect);
            try
            {
                test_connection.Open();
                Console.WriteLine("Successful Connection to MySQL Database " + test_connection.Database);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed To Connect to MySQL Database - " + ex.Message);
            }
            finally
            {
                if (test_connection != null)
                {
                    if (test_connection.State == System.Data.ConnectionState.Open ||
                        test_connection.State == System.Data.ConnectionState.Connecting)
                    {
                        test_connection.Close();
                    }
                }

                test_connection = null;
            }

            Console.WriteLine("Attempting to Connect to Redis database...");
            ConnectionMultiplexer test_redis_connection = null;

            try
            {
                test_redis_connection = ConnectionMultiplexer.Connect(cr.RedisDBConnect);
                Console.WriteLine("Successful Connection to Redis Database");
                Console.WriteLine("Redis Environment: " + cr.RedisEnvironmentKey);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed To Connect to Redis Database - " + ex.Message);
                Console.ReadKey();
                return;
            }
            finally
            {
                if (test_redis_connection != null)
                {
                    if (test_redis_connection.IsConnected)
                    {
                        test_redis_connection.Close();
                    }
                }
            }

            string PublicIP = "";

            if (cr.UseUPnP)
            {
                Console.WriteLine("Using UPnP to forward ports...");
                PublicIP = SetupPortMappings(cr.PortNumber).GetAwaiter().GetResult();
            }

            if (cr.UseWhiteList)
            {
                Console.WriteLine("Using whitelist...");
            }

            SocketServer server = null;

            try
            {
                server = new SocketServer(cr.MaxConnections, cr.PortNumber, cr.WhiteList);
                server.Open();
                if (!String.IsNullOrWhiteSpace(PublicIP))
                {
                    Console.WriteLine("UPNP: Mapped Public {0} to Private {1} on Port {2}", PublicIP, server.Address(), cr.PortNumber);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error in creating Socket: " + ex.Message);
                if (server != null)
                {
                    server.Close();
                }
                Console.ReadKey();
                return;
            }

            Console.WriteLine("Server is now running on: " + server.Address() + " - use F2 to close server");
            while (true)
            {
                if (Console.ReadKey().Key == ConsoleKey.F2)
                {
                    server.Close();
                    Console.WriteLine("Server Terminated");
                    return;
                }
            }
        }
コード例 #26
0
 public void Dispose()
 {
     _connection?.Close();
 }
コード例 #27
0
 public void Cleanup()
 {
     connectionRedis.Close();
 }
コード例 #28
0
 public void Dispose()
 {
     _redis.Close();
 }
コード例 #29
0
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     redis.Close();
 }
コード例 #30
0
ファイル: RedisCache.cs プロジェクト: AsWinds/Smart
 protected override void Dispose(bool disposing)
 {
     base.Dispose(disposing);
     connectionMultiplexer?.Close();
 }