Inheritance: IRedisClient
Ejemplo n.º 1
3
 private void NotifySubscribers(string queueName)
 {
     using (var client = new RedisClient("localhost"))
     {
         client.PublishMessage(queueName, NewItem);
     }
 }
Ejemplo n.º 2
2
        // GET: Tracker
        public ActionResult Index(long userId, int amount = 0)
        {
            using (IRedisClient client = new RedisClient())
            {
                var userClient = client.As<User>();
                var user = userClient.GetById(userId);
                var historyClient = client.As<int>();
                var historyList = historyClient.Lists["urn:history:" + userId];

                if (amount > 0)
                {
                    user.Total += amount;
                    userClient.Store(user);

                    historyList.Prepend(amount);
                    historyList.Trim(0, 4);

                    client.AddItemToSortedSet("urn:leaderboard", user.Name, user.Total);
                }

                ViewBag.HistoryItems = historyList.GetAll();
                ViewBag.UserName = user.Name;
                ViewBag.Total = user.Total;
                ViewBag.Goal = user.Goal;
                ViewBag.UserId = user.Id;
            }

            return View();
        }
        public RedisSubscription(RedisClient redisClient)
        {
            this.redisClient = redisClient;

            this.SubscriptionCount = 0;
            this.activeChannels = new List<string>();
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            using (var redisClient = new RedisClient("localhost"))
            {
                while (true)
                {
                    var stopwatch = System.Diagnostics.Stopwatch.StartNew();
                    //Console.WriteLine("ping: " + ping + ", time: " + time);

                    //redisClient.DeleteAll<Counter>();

                    IRedisTypedClient<Counter> redis = redisClient.As<Counter>();

                    //var key = redis.GetAllKeys();

                    var c = redis.GetAndSetValue("the-counter", new Counter());

                    c.Value += 1;

                    redis.GetAndSetValue("the-counter", c);

                    Console.WriteLine("counter: " + c.Value);

                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }
        }
Ejemplo n.º 5
0
        public static void Main()
        {
            var client = new RedisClient();

            // UsingIRedisClient(client);
            UsingIRedisTypedClient(client);
        }
Ejemplo n.º 6
0
        public Task<bool> SetAsync(string series, int index, long value)
        {
            using (var client = new RedisClient(Host))
            {
                var cache = client.As<Dictionary<int, long>>();

                if (cache.ContainsKey(series))
                {
                    cache[series][index] = value;
                }
                else
                {
                    lock (cache)
                    {
                        cache.SetValue(series,
                            new Dictionary<int, long>()
                        {
                            [index] = value
                        });
                    }
                }

                return Task.FromResult(true);
            }
        }
Ejemplo n.º 7
0
        private static void UsingIRedisTypedClient(RedisClient client)
        {
            var redisTodos = client.As<Todo>();

            // Mark all Todos, that have passed deadline, as DONE

            redisTodos.GetAll()
                      .Where(t => t.Deadline >= DateTime.Now)
                      // Extension method to execute a lambda expression for each element of a IEnumerable<T>
                      .ForEach(t => t.IsDone = true);

            var todo = new Todo()
            {
                Id = redisTodos.GetNextSequence(),
                Text = "Todo created at " + DateTime.Now,
                Deadline = DateTime.Now.AddDays(1),
                IsDone = false,
                AssignedTo = new User()
                {
                    Name = "Nakov"
                }
            };

            redisTodos.Store(todo);
            redisTodos.GetAll()
                      .Print();
        }
Ejemplo n.º 8
0
 public void Clear(string queueName)
 {
     using (var client = new RedisClient("localhost"))
     {
         client.Lists[queueName].Clear();
     }
 }
Ejemplo n.º 9
0
        public void Subscribe(string queueName, Action action)
        {
            Task.Factory.StartNew(() =>
            {
                using (var client1 = new RedisClient("localhost"))
                {
                    using (var subscription1 = client1.CreateSubscription())
                    {
                        subscription1.OnSubscribe =
                            channel => Debug.WriteLine(string.Format("Subscribed to '{0}'", channel));

                        subscription1.OnUnSubscribe =
                            channel => Debug.WriteLine(string.Format("UnSubscribed from '{0}'", channel));

                        subscription1.OnMessage = (channel, msg) =>
                        {
                            Debug.WriteLine(string.Format("Received '{0}' from channel '{1}' Busy: {2}", msg, channel, false));
                            action();
                        };

                        subscription1.SubscribeToChannels(queueName);

                        Debug.WriteLine("Subscribed");
                    }
                }
            }).Start();
        }
Ejemplo n.º 10
0
 public UserBalance GetBalance(string accountName)
 {
     using (RedisClient redis = new RedisClient(redisCloudUrl.Value))
     {
         return redis.Get<UserBalance>(accountName) ?? new UserBalance();
     }
 }
Ejemplo n.º 11
0
 public void CancelToolBroken(bool bIsTrueBroken)
 {
     try
     {
         if (this._info != null)
         {
             String Redisip   = System.Configuration.ConfigurationManager.AppSettings["RedisUri"];
             Int32  Redisport = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["RedisPort_RealTime"]);
             ServiceStack.Redis.RedisClient client = new ServiceStack.Redis.RedisClient(Redisip, Redisport);
             client.Db = this._CloudDB;
             HncMessage <ToolBrokenInfo> toolinfo = new HncMessage <ToolBrokenInfo>();
             toolinfo.Header = "ToolBrokenFeedBack";
             _info.IsBroken  = bIsTrueBroken;
             toolinfo.Body   = _info;
             String msg = Newtonsoft.Json.JsonConvert.SerializeObject(toolinfo);
             client.Set <String>("ToolBrokenFeedBack", msg);
             _info = null;
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("CancelToolBroken:" + ex.Message);
     }
     HncApi.HNC_RegClrBit((int)HncRegType.REG_TYPE_G, 2626, 0, _ClientNo);
     HncApi.HNC_RegClrBit((int)HncRegType.REG_TYPE_G, 3013, 15, _ClientNo);
 }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            Trace.TraceInformation("MEETUP_NOTIFICATION_URL: {0}", _meetupNewsUrl);
            Trace.TraceInformation("SLACK_WEBHOOK_URL: {0}", _slackWebhookUrl);
            Trace.TraceInformation("REDISTOGO_URL: {0}", _redisUrl);

            while(true)
            {
                using(var redis = new RedisClient(_redisUrl))
                {
                    var lastNotificationID = redis.Get<long>(_lastNotificationIDKey);

                    var news = GetMeetupNotifications();

                    var freshNews = news.Where(n => n.id > lastNotificationID);

                    if(freshNews.Any())
                    {
                        var relevantNews = freshNews.Where(n => n.target.group_id == _meetupGroupId)
                                                        .OrderBy(n => n.id);

                        foreach(var item in relevantNews) {
                            PostNotificationToSlack(item);
                        }

                        redis.Set(_lastNotificationIDKey, news.Max(n => n.id));
                    }
                }

                Thread.Sleep(60000);
            }
        }
Ejemplo n.º 13
0
 public ViewResult Teacher()
 {
     using (var redis = new RedisClient(new Uri(connectionString))) {
         var teacher = redis.As<Teacher>().GetAll().FirstOrDefault();
         return View(teacher);
     }
 }
Ejemplo n.º 14
0
        public static void DrawMenu(RedisClient redisDictionaryClient)
        {
            Console.WriteLine("To list all items type - list");
            Console.WriteLine("To add new word in dictionary type - add");
            Console.WriteLine("To search type - search");
            Console.WriteLine("To exit type - exit");

            string clientChoice = Console.ReadLine();

            switch (clientChoice)
            {
                case "list":
                    ListItems(redisDictionaryClient);
                    DrawMenu(redisDictionaryClient);
                    break;
                case "add":
                    AddItem(redisDictionaryClient);
                    DrawMenu(redisDictionaryClient);
                    break;
                case "search":
                    SearchItem(redisDictionaryClient);
                    DrawMenu(redisDictionaryClient);
                    break;
                case "exit":
                    Console.WriteLine("Bye bye!");
                    break;
                default:
                    Console.WriteLine("Wrong command!");
                    DrawMenu(redisDictionaryClient);
                    break;
            }
        }
Ejemplo n.º 15
0
        public ActionResult Save(string userName, int goal, long? userId)
        {
            using (IRedisClient client = new RedisClient())
            {
                var userClient = client.As<User>();

                User user;
                if (userId != null)
                {
                    user = userClient.GetById(userId);
                    client.RemoveItemFromSortedSet("urn:leaderboard", user.Name);
                }
                else
                {
                    user = new User()
                    {
                        Id = userClient.GetNextSequence()
                    };
                }

                user.Name = userName;
                user.Goal = goal;
                userClient.Store(user);
                userId = user.Id;

                client.AddItemToSortedSet("urn:leaderboard", userName, user.Total);
            }

            return RedirectToAction("Index", "Tracker", new { userId});
        }
Ejemplo n.º 16
0
 private static void ChangeTranslation(RedisClient client)
 {
     Console.WriteLine("Enter word.");
     string word = Console.ReadLine();
     byte[] wordInBytes = Extensions.ToAsciiCharArray(word);
     Console.WriteLine("Enter translation.");
     string translation = Console.ReadLine();
     byte[] translationInBytes = Extensions.ToAsciiCharArray(translation);
     if (!string.IsNullOrWhiteSpace(word) && !string.IsNullOrWhiteSpace(translation))
     {
         if (client.HExists(dictionary, wordInBytes) == 1)
         {
             client.HSet(dictionary, wordInBytes, translationInBytes);
             Console.WriteLine("Translation of the word {0} is changed.", word);
         }
         else
         {
             Console.WriteLine("There is no word {0}.", word);
         }
     }
     else
     {
         Console.WriteLine("You enter null or empty string for word or translation. Please try again.");
     }
 }
Ejemplo n.º 17
0
    static void Main()
    {
        RedisClient client = new RedisClient("127.0.0.1:6379");
        using (client)
        {
            Console.WriteLine("Enter command - Add, Change, Find or Exit");
            string command = Console.ReadLine();
            while (command != exit)
            {
                if (command == add)
                {
                    AddToDictionary(client);
                }
                else if (command == change)
                {
                    ChangeTranslation(client);
                }
                else if (command == find)
                {
                    ShowTranslation(client);
                }
                else if (command != exit)
                {
                    Console.WriteLine("Enter invalid command. Please try again.");
                }

                Console.WriteLine("Enter command - Add, Change, Find or Exit");
                command = Console.ReadLine();
            }
        }
    }
Ejemplo n.º 18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                redisHost = ConfigurationManager.AppSettings["redisHost"];
                redisPort = int.Parse(ConfigurationManager.AppSettings["redisPort"]);
                redisPassword = ConfigurationManager.AppSettings["redisPassword"];

                if (!IsPostBack)
                {
                    RedisClient redisClient = new RedisClient(redisHost, redisPort) { Password = redisPassword };
                    using (var redisGuids = redisClient.GetTypedClient<Guids>())
                    {
                        redisGuids.Store(new Guids { Date = DateTime.Now, Value = Guid.NewGuid() });
                        var allValues = redisGuids.GetAll();
                        GridView1.DataSource = allValues;
                        GridView1.DataBind();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new WebException(ex.ToString(), WebExceptionStatus.ConnectFailure);
            }
        }
        static void Main(string[] args)
        {
            var dictionaryData = new string[,]
            {
                { ".NET", "platform for applications from Microsoft" },
                { "CLR", "managed execution environment for .NET" },
                { "namespace", "hierarchical organization of classes" },
                { "database", "structured sets of persistent updateable and queriable data" },
                { "blob", "binary large object" },
                { "RDBMS", "relational database management system" },
                { "json", "JavaScript Object Notation" },
                { "xml", "Extensible Markup Language" },
            };

            using (var redisClient = new RedisClient("127.0.0.1:6379"))
            {
                for (int i = 0; i < dictionaryData.GetLength(0); i++)
                {
                    if (redisClient.HExists("dictionary", ToByteArray(dictionaryData[i, 0])) == 0)
                    {
                        redisClient.HSetNX("dictionary", ToByteArray(dictionaryData[i, 0]), ToByteArray(dictionaryData[i, 1]));
                    }
                }

                PrintAllWords(redisClient);
                Console.WriteLine("\nSearch for word \"blob\":");
                FindWord(redisClient, "blob");
            }
        }
 public static void ExecuteRedis()
 {
     RedisClient dataContext = new RedisClient("localhost");
     //dataContext.RemoveAll(new List<string>() { "./test.txt", "./temp.txt" });
     dataContext.Add<string>("harageth./file.txt", "This is a test file to make sure that things are working correctly.");
     dataContext.Add<string>("harageth./temp.txt", "And now we will store a second file to just see if we can get a couple of files at once.");
 }
 private IRedisClient CreateClient()
 {
     var hosts = _host.Split(':');
     var client = new RedisClient(hosts[0], Int32.Parse(hosts[1]));
     client.Password = _password;
     return client;
 }
Ejemplo n.º 22
0
        public void CanLoadData()
        {
            string cs = ConfigurationManager.AppSettings["RedisServer"];
            if (String.IsNullOrEmpty(cs))
                return;

            // Check we don't crash when session is missing
            using (var client = new RedisClient(new Uri(cs)))
            {
                var store = new RedisSessionStore(client);
                var data = store.Load<IDictionary<string, object>>("foo");
                Assert.Null(data);
            }
            // Check we can save and reload some data
            using (var client = new RedisClient(new Uri(cs)))
            {
                var store = new RedisSessionStore(client);
                store.Save<IDictionary<string, object>>("Test", new Dictionary<string, object> { { "Key", "Value" }, { "Key2", "Value2" } });
                var data = store.Load<IDictionary<string, object>>("Test");
                Assert.Equal(2, data.Count);
                Assert.Equal("Value", data["Key"]);
                Assert.Equal("Value2", data["Key2"]);
            }

            // Test we can load an object from another connection/store isntance
            using (var client = new RedisClient(new Uri(cs)))
            {
                var store = new RedisSessionStore(client);
                var data = store.Load<IDictionary<string, object>>("Test");
                Assert.Equal(2, data.Count);
                Assert.Equal("Value", data["Key"]);
                Assert.Equal("Value2", data["Key2"]);
            }
        }
Ejemplo n.º 23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        using (var redisClient = new RedisClient("localhost"))
        {
            //DanhMucDal.ClearCache(CacheManager.Loai.Redis);
            //LoaiDanhMucDal.ClearCache(CacheManager.Loai.Redis);

            //var list = DanhMucDal.List;

            var dm = redisClient.As<DanhMuc>();
            var key = string.Format("urn:danhmuc:list");
            var obj = dm.Lists[key];
            Response.Write(obj.Count + "<br/>");
            foreach (var item in obj.ToList())
            {
                Response.Write(string.Format("{0}:{1}", item.Ten,item.LoaiDanhMuc.Ten));
                Response.Write(item.Ten + "<br/>");
            }
            Response.Write("<hr/>");
            foreach (var _key in dm.GetAllKeys())
            {
                Response.Write(string.Format("{0}<br/>", _key));
            }
        }
    }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            string host = "localhost";
            string elementKey = "testKeyRedis";

            using (RedisClient redisClient = new RedisClient(host))
            {
                if (redisClient.Get<string>(elementKey) == null)
                {
                    // adding delay to see the difference
                    Thread.Sleep(2000);
                    // save value in cache
                    redisClient.Set(elementKey, "default value");
                }

                //change the value
                redisClient.Set(elementKey, "f**k you value");

                // get value from the cache by key
                string message = "Item value is: " + redisClient.Get<string>(elementKey);

                Console.WriteLine(message);
                Console.ReadLine();
            }
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Create a shared client for redis
 /// </summary>
 /// <returns></returns>
 public static RedisClient CreateRedisClient()
 {
     var redisUri = new Uri(ConfigurationManager.AppSettings.Get("REDISTOGO_URL"));
     var redisClient = new RedisClient(redisUri.Host, redisUri.Port);
     redisClient.Password = "******";
     return redisClient;
 }
Ejemplo n.º 26
0
        private static void TestList()
        {
            using (var client = new RedisClient("127.0.0.1", 6379))
            {
                #region "List类型"

                client.AddItemToList("HQF.Tutorial.Redis:userInfoId1", "123");
                client.AddItemToList("HQF.Tutorial.Redis:userInfoId1", "1234");

                Console.WriteLine("List数据项条数:" + client.GetListCount("HQF.Tutorial.Redis:userInfoId1"));
                Console.WriteLine("List数据项第一条数据:" + client.GetItemFromList("HQF.Tutorial.Redis:userInfoId1", 0));
                Console.WriteLine("List所有数据");
                client.GetAllItemsFromList("HQF.Tutorial.Redis:userInfoId1").ForEach(e => Console.WriteLine(e));
                #endregion

                #region "List类型做为队列和栈使用"
                Console.WriteLine(client.GetListCount("HQF.Tutorial.Redis:userInfoId1"));
                //队列先进先出
                //Console.WriteLine(client.DequeueItemFromList("userInfoId1"));
                //Console.WriteLine(client.DequeueItemFromList("userInfoId1"));

                //栈后进先出
                Console.WriteLine("出栈" + client.PopItemFromList("HQF.Tutorial.Redis:userInfoId1"));
                Console.WriteLine("出栈" + client.PopItemFromList("HQF.Tutorial.Redis:userInfoId1"));
                #endregion
            }
        }
Ejemplo n.º 27
0
 public int Dequeue(string queueName)
 {
     using (var client = new RedisClient("localhost"))
     {
         return Convert.ToInt32(client.Lists[queueName].Pop());
     }
 }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            var host = args.Length > 0 ? args[0] : "localhost";
            var port = args.Length > 1 ? int.Parse(args[1]) : 6379;

            var redisClient = new RedisClient(host, port);

            var before = DateTime.Now;
            for (var i = 0; i < Iterations; i++)
            {
                var key = KeyMaster + i;
                redisClient.Set(key, ValueMaster);

                //if (i % LogEveryTimes == 0)
                //    Console.WriteLine("Time taken at {0}: {1}ms", i, (DateTime.Now - before).TotalMilliseconds);
            }

            for (int i = 0; i < Iterations; i++)
            {
                var key = KeyMaster + i;
                redisClient.Get<string>(key);

                //if (i % LogEveryTimes == 0)
                //    Console.WriteLine("Time taken at {0}: {1}ms", i, (DateTime.Now - before).TotalMilliseconds);
            }

            Console.WriteLine("Total Time Taken: {0}ms", (DateTime.Now - before).TotalMilliseconds);
        }
Ejemplo n.º 29
0
 //Verification是前端传进来的验证码
 public int checkverification(string mobile, string smsType, string verification)
 {
     try
     {
         var Client = new RedisClient("127.0.0.1", 6379);
         var verify = Client.Get<string>(mobile + smsType);
         if (verify != null)
         {
             if (verify == verification)
             {
                 return 1;//验证码正确
             }
             else
             {
                 return 2;//验证码错误
             }
         }
         else
         {
             return 0;//没有验证码或验证码已过期
         }
     }
     catch (Exception ex)
     {
         HygeiaComUtility.WriteClientLog(HygeiaEnum.LogType.ErrorLog, "匹配验证码功能错误", "WebService调用异常! error information : " + ex.Message + Environment.NewLine + ex.StackTrace);
         return 3;
         throw (ex);
     }
 }
Ejemplo n.º 30
0
        public void Dispose()
        {
            if (Redis != null)
                Redis.Dispose();

            Redis = null;
        }
Ejemplo n.º 31
0
 // 释放资源
 public void Dispose()
 {
     if (Redis != null)
     {
         Redis.Dispose();
         Redis = null;
     }
     GC.Collect();
 }
Ejemplo n.º 32
0
        public Subscriber(RedisMessageClient client)
        {
            _client  = client;
            _redis   = new RedisClient(client.Host, client.Port, client.Password);
            _context = Thread.CurrentContext;

            // registry client
            _redis.SAdd(Consts.CONST_CLIENTS_SET_NAME, Encoding.UTF8.GetBytes(client.ClientId));
        }
Ejemplo n.º 33
0
 public void ClearAllKeys()
 {
     foreach (HostSettings host in _hosts.Values)
     {
         using (IRedisClient client = new ServiceStack.Redis.RedisClient(host.URL, host.Port))
         {
             client.FlushAll();
         }
     }
 }
Ejemplo n.º 34
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="OpenPooledRedis">是否开启缓冲池</param>
        public RedisService(bool OpenPooledRedis = false)
        {
            if (OpenPooledRedis)
            {
                //prcm = CreateManager(new[] { "[email protected]:6379" }, new[] { "[email protected]:6379" });
                prcm = CreateManager(new[] { "172.19.20.72:6379" }, new[] { "172.19.20.73:6379" });

                Redis = prcm.GetClient() as ServiceStack.Redis.RedisClient;
            }
        }
Ejemplo n.º 35
0
        public void Simple()
        {
            ServiceStack.Redis.RedisClient cli = new ServiceStack.Redis.RedisClient();
            var c1   = cli.As <UserLight>();
            var set1 = c1.Sets["set1"];

            //set1.Add(new UserLight() { Id = DateTime.Now.Ticks, UserName = "******", LastSeen = DateTime.Now });

            var s = "activity-" + DateTime.Now.ToString("dd-hh-mm-ss");

            var users = ActivityTracker.GetActiveUsers();
        }
Ejemplo n.º 36
0
 private void UploadToCloud()
 {
     while (CloudDB > -1 && _LocalDB > -1)
     {
         try
         {
             using (ServiceStack.Redis.RedisClient client = getClient())
             {
                 if (!client.Ping())
                 {
                     continue;
                 }
                 client.Db = CloudDB;
                 if (client.Exists("Machine") == 0)
                 {
                     RegisterConfigure(client);
                 }
                 ServiceStack.Redis.RedisClient localclient = new ServiceStack.Redis.RedisClient("127.0.0.1", 6379);
                 localclient.Db = LocalDB;
                 if (localclient.Exists("Machine") == 0)
                 {
                     RegisterConfigure(localclient);
                 }
                 if (localclient.LLen("SampleData") > 99)
                 {
                     List <String> listData = localclient.GetRangeFromList("SampleData", 0, 99);
                     using (var trans = client.CreatePipeline())              //Calls 'MULTI'
                     {
                         for (int i = 0; i < listData.Count; i++)
                         {
                             trans.QueueCommand(r => r.AddItemToList("SampleData", listData[i]));
                         }
                         trans.Flush();
                     }
                     localclient.LTrim("SampleData", listData.Count, -1);
                 }
                 UploudGCodeToCloud(client, localclient);
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine("Upload to cloud:" + ex.Message);
         }
         System.Threading.Thread.Sleep(10);
     }
 }
Ejemplo n.º 37
0
        /// <summary>
        /// 订阅
        /// </summary>
        public static void Subscription()
        {
            using (ServiceStack.Redis.RedisClient consumer = new RedisClient("192.168.1.117", 6379))
            {
                //创建订阅
                ServiceStack.Redis.IRedisSubscription subscription = consumer.CreateSubscription();

                //接收消息处理Action
                subscription.OnMessage = (channel, msg) =>
                {
                    Console.WriteLine("频道【" + channel + "】订阅客户端接收消息:" + ":" + msg + "         [" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "]");
                    Console.WriteLine("订阅数:" + subscription.SubscriptionCount);
                    Console.WriteLine("___________________________________________________________________");
                };

                //订阅事件处理
                subscription.OnSubscribe = (channel) =>
                {
                    Console.WriteLine("订阅客户端:开始订阅" + channel);
                };

                //取消订阅事件处理
                subscription.OnUnSubscribe = (a) => { Console.WriteLine("订阅客户端:取消订阅"); };

                //模拟:发送100条消息给服务
                Task.Run(() =>
                {
                    using (ServiceStack.Redis.IRedisClient publisher = new ServiceStack.Redis.RedisClient("192.168.1.117", 6379))
                    {
                        for (int i = 1; i <= 100; i++)
                        {
                            publisher.PublishMessage("channel-1", string.Format("这是我发送的第{0}消息!", i));
                            System.Threading.Thread.Sleep(200);
                        }
                    }
                });

                //订阅频道
                subscription.SubscribeToChannels("channel-1");
                Console.ReadLine();
            }
        }
Ejemplo n.º 38
0
        private void UploudGCodeToCloud(ServiceStack.Redis.RedisClient client, ServiceStack.Redis.RedisClient localclient)
        {
            List <String> GCodeFiles = localclient.SearchKeys("GCODE:*");

            if (GCodeFiles != null)
            {
                for (int i = 0; i < GCodeFiles.Count; i++)
                {
                    List <String> listData = localclient.GetRangeFromList(GCodeFiles[i], 0, -1);
                    localclient.Remove(GCodeFiles[i]);
                    client.Remove(GCodeFiles[i]);
                    using (var trans = client.CreatePipeline())              //Calls 'MULTI'
                    {
                        for (int j = 0; j < listData.Count; j++)
                        {
                            trans.QueueCommand(r => r.AddItemToList(GCodeFiles[i], listData[j]));
                        }
                        trans.Flush();
                    }
                }
            }
        }
 protected void ClosePipeline()
 {
     RedisClient.ResetSendBuffer();
     RedisClient.Pipeline = null;
 }
 public RedisClientLists(RedisClient client)
 {
     this.client = client;
 }
 public RedisTransaction(RedisClient redisClient)
     : base(redisClient)
 {
 }
 /// <summary>
 /// Issue exec command (not queued)
 /// </summary>
 private void Exec()
 {
     RedisClient.Exec();
     RedisClient.FlushSendBuffer();
 }
Ejemplo n.º 43
0
 public RedisCommandQueue(RedisClient redisClient)
 {
     this.RedisClient = redisClient;
 }
Ejemplo n.º 44
0
 public RedisClientHashes(RedisClient client)
 {
     this.client = client;
 }
Ejemplo n.º 45
0
 protected void ClosePipeline()
 {
     RedisClient.EndPipeline();
 }
Ejemplo n.º 46
0
 public RedisClientHash(RedisClient client, string hashId)
 {
     this.client = client;
     this.hashId = hashId;
 }
Ejemplo n.º 47
0
 private Int32 FindLocalDB()
 {
     lock (_DBLocker)
     {
         try
         {
             String Redisip   = "127.0.0.1";
             Int32  Redisport = 6379;
             bool   found     = false;
             ServiceStack.Redis.RedisClient client = new ServiceStack.Redis.RedisClient(Redisip, Redisport);
             for (int i = 0; i < 22; i++)
             {
                 client.Db = i;
                 if (client.Exists("Machine") == 1)
                 {
                     String SN = client.Get <String>("Machine");
                     if (SN == this.MachineSN)
                     {
                         String ConfigureStr = Newtonsoft.Json.JsonConvert.SerializeObject(_conf);
                         client.Set("SampleConfigure", ConfigureStr);
                         client.Set("IP", this._MachineIp);
                         found = true;
                         return(i);
                     }
                 }
             }
             if (!found)
             {
                 for (int i = 0; i < 22; i++)
                 {
                     client.Db = i;
                     if (client.DbSize == 0)
                     {
                         client.Set("Machine", this.MachineSN);
                         client.Set("IP", this._MachineIp);
                         String ConfigureStr = Newtonsoft.Json.JsonConvert.SerializeObject(_conf);
                         client.Set("SampleConfigure", ConfigureStr);
                         found = true;
                         return(i);
                     }
                 }
             }
             if (!found)
             {
                 for (int i = 0; i < 22; i++)
                 {
                     client.Db = i;
                     if (client.Exists("Machine") == 0)
                     {
                         client.FlushDb();
                         client.Set("Machine", this.MachineSN);
                         client.Set("IP", this._MachineIp);
                         String ConfigureStr = Newtonsoft.Json.JsonConvert.SerializeObject(_conf);
                         client.Set("SampleConfigure", ConfigureStr);
                         found = true;
                         return(i);
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine("FindLocalDB" + ex.Message);
         }
         return(-1);
     }
 }
Ejemplo n.º 48
0
 private void RegistMachineToClound()
 {
     lock (_DBLocker)
     {
         try
         {
             String Redisip   = System.Configuration.ConfigurationManager.AppSettings["RedisUri"];
             Int32  Redisport = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["RedisPort"]);
             bool   found     = false;
             using (ServiceStack.Redis.RedisClient client = new ServiceStack.Redis.RedisClient(Redisip, Redisport))
             {
                 for (int i = 0; i < 180; i++)
                 {
                     client.Db = i;
                     if (client.Exists("Machine") == 1)
                     {
                         String SN = client.Get <String>("Machine");
                         if (SN == this.MachineSN)
                         {
                             found = true;
                             RegisterConfigure(client);
                             CloudDB = i;
                             break;
                         }
                     }
                 }
                 if (!found)
                 {
                     for (int i = 0; i < 180; i++)
                     {
                         client.Db = i;
                         if (client.DbSize == 0)
                         {
                             CloudDB = i;
                             RegisterConfigure(client);
                             found = true;
                             break;
                         }
                     }
                 }
                 if (!found)
                 {
                     for (int i = 0; i < 180; i++)
                     {
                         client.Db = i;
                         if (client.Exists("Machine") == 0)
                         {
                             CloudDB = i;
                             client.FlushDb();
                             RegisterConfigure(client);
                             found = true;
                             break;
                         }
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine("RegistMachineToClound" + ex.Message);
         }
     }
 }
 /// <summary>
 /// General purpose pipeline
 /// </summary>
 /// <param name="redisClient"></param>
 public RedisAllPurposePipeline(RedisClient redisClient)
     : base(redisClient)
 {
     Init();
 }
 private void InitClient(RedisClient client)
 {
 }
Ejemplo n.º 51
0
        public virtual RedisClient CreateRedisClient(RedisEndpoint config, bool master)
        {
            var client = ClientFactory(config);

            if (master)
            {
                var role = RedisServerRole.Unknown;
                try
                {
                    role = client.GetServerRole();
                    if (role == RedisServerRole.Master)
                    {
                        lastValidMasterFromSentinelAt = DateTime.UtcNow;
                        return(client);
                    }
                }
                catch (Exception ex)
                {
                    Interlocked.Increment(ref RedisState.TotalInvalidMasters);

                    if (client.GetHostString() == lastInvalidMasterHost)
                    {
                        lock (oLock)
                        {
                            if (DateTime.UtcNow - lastValidMasterFromSentinelAt > sentinel.WaitBeforeForcingMasterFailover)
                            {
                                lastInvalidMasterHost         = null;
                                lastValidMasterFromSentinelAt = DateTime.UtcNow;

                                log.Error("Valid master was not found at '{0}' within '{1}'. Sending SENTINEL failover...".Fmt(
                                              client.GetHostString(), sentinel.WaitBeforeForcingMasterFailover), ex);

                                Interlocked.Increment(ref RedisState.TotalForcedMasterFailovers);

                                sentinel.ForceMasterFailover();
                                TaskUtils.Sleep(sentinel.WaitBetweenFailedHosts);
                                role = client.GetServerRole();
                            }
                        }
                    }
                    else
                    {
                        lastInvalidMasterHost = client.GetHostString();
                    }
                }

                if (role != RedisServerRole.Master && RedisConfig.VerifyMasterConnections)
                {
                    try
                    {
                        var stopwatch = Stopwatch.StartNew();
                        while (true)
                        {
                            try
                            {
                                var masterConfig = sentinel.GetMaster();
                                var masterClient = ClientFactory(masterConfig);
                                masterClient.ConnectTimeout = sentinel.SentinelWorkerConnectTimeoutMs;

                                var masterRole = masterClient.GetServerRole();
                                if (masterRole == RedisServerRole.Master)
                                {
                                    lastValidMasterFromSentinelAt = DateTime.UtcNow;
                                    return(masterClient);
                                }
                                else
                                {
                                    Interlocked.Increment(ref RedisState.TotalInvalidMasters);
                                }
                            }
                            catch { /* Ignore errors until MaxWait */ }

                            if (stopwatch.Elapsed > sentinel.MaxWaitBetweenFailedHosts)
                            {
                                throw new TimeoutException("Max Wait Between Sentinel Lookups Elapsed: {0}"
                                                           .Fmt(sentinel.MaxWaitBetweenFailedHosts.ToString()));
                            }

                            TaskUtils.Sleep(sentinel.WaitBetweenFailedHosts);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("Redis Master Host '{0}' is {1}. Resetting allHosts...".Fmt(config.GetHostString(), role), ex);

                        var         newMasters   = new List <RedisEndpoint>();
                        var         newSlaves    = new List <RedisEndpoint>();
                        RedisClient masterClient = null;
                        foreach (var hostConfig in allHosts)
                        {
                            try
                            {
                                var testClient = ClientFactory(hostConfig);
                                testClient.ConnectTimeout = RedisConfig.HostLookupTimeoutMs;
                                var testRole = testClient.GetServerRole();
                                switch (testRole)
                                {
                                case RedisServerRole.Master:
                                    newMasters.Add(hostConfig);
                                    if (masterClient == null)
                                    {
                                        masterClient = testClient;
                                    }
                                    break;

                                case RedisServerRole.Slave:
                                    newSlaves.Add(hostConfig);
                                    break;
                                }
                            }
                            catch { /* skip past invalid master connections */ }
                        }

                        if (masterClient == null)
                        {
                            Interlocked.Increment(ref RedisState.TotalNoMastersFound);
                            var errorMsg = "No master found in: " + string.Join(", ", allHosts.Map(x => x.GetHostString()));
                            log.Error(errorMsg);
                            throw new Exception(errorMsg);
                        }

                        ResetMasters(newMasters);
                        ResetSlaves(newSlaves);
                        return(masterClient);
                    }
                }
            }

            return(client);
        }
 public RedisClientSets(RedisClient client)
 {
     this.client = client;
 }
Ejemplo n.º 53
0
 public RedisClientList(RedisClient client, string listId)
 {
     this.listId = listId;
     this.client = client;
 }
Ejemplo n.º 54
0
 public RedisClientSet(RedisClient client, string setId)
 {
     this.client = client;
     this.setId  = setId;
 }
Ejemplo n.º 55
0
 public RedisClient(string ip, int port, string password = null, int db = 0)
 {
     client     = new ServiceStack.Redis.RedisClient(ip, port, password, db);
     client_pub = new ServiceStack.Redis.RedisClient(ip, port, password, db);
     Console.WriteLine($"redis启动成功!");
 }
 public void Connect(RedisConnectionStringBuilder connectionString)
 {
     _client = new ServiceStack.Redis.RedisClient(((IPEndPoint)connectionString.EndPoint).Address.ToString(),
                                                  ((IPEndPoint)connectionString.EndPoint).Port);
 }
Ejemplo n.º 57
0
        public static IRedisClient GetConnect(string connstring)
        {
            #region 连接字符串处理
            if (string.IsNullOrWhiteSpace(connstring))
            {
                throw new ArgumentException("无效redis地址!");
            }
            string host   = string.Empty;
            int    port   = 6379;
            string passwd = null;
            int    dbid   = 0;
            var    sps    = connstring.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray();
            if (sps.Length == 1)
            {
                if (sps[0].Contains("@"))
                {
                    passwd = sps[0].Substring(0, sps[0].IndexOf('@'));
                    sps[0] = sps[0].Substring(sps[0].IndexOf('@') + 1);
                }
                if (sps[0].Contains(":"))
                {
                    host = sps[0].Substring(0, sps[0].IndexOf(':'));
                    port = Convert.ToInt32(sps[0].Substring(sps[0].IndexOf(':') + 1));
                }
                else
                {
                    host = sps[0];
                }
            }
            else
            {
                foreach (var a in sps)
                {
                    var kvp = a.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                    if (kvp.Length != 2)
                    {
                        continue;
                    }
                    kvp[0] = kvp[0].ToLower();

                    //server
                    if (kvp[0] == "server")
                    {
                        if (kvp[1].Contains(":"))
                        {
                            host = kvp[1].Substring(0, sps[0].IndexOf(':'));
                            int t_port = 0;
                            if (int.TryParse(kvp[1].Substring(sps[0].IndexOf(':') + 1), out t_port))
                            {
                                port = t_port;
                            }
                        }
                        else
                        {
                            host = kvp[1];
                        }
                    }
                    //port
                    if (kvp[0] == "port")
                    {
                        int t_port = 0;
                        if (int.TryParse(kvp[1], out t_port))
                        {
                            port = t_port;
                        }
                    }

                    //password
                    if (kvp[0] == "password" || kvp[0] == "pwd")
                    {
                        passwd = kvp[1];
                    }
                    //database
                    if (kvp[0] == "database" || kvp[0] == "db")
                    {
                        var t_dbid = 0;
                        if (int.TryParse(kvp[1], out dbid))
                        {
                            dbid = t_dbid;
                        }
                    }
                }
            }
            #endregion

            ServiceStack.Redis.RedisClient client = new ServiceStack.Redis.RedisClient(host, port, passwd, dbid);
            return(client);
        }
Ejemplo n.º 58
0
        private void Subscribe()
        {
            try
            {
                var channelName = MachineSN;
                _Client = new RedisClient(_ip, _port);

                using (var subscription = _Client.CreateSubscription())
                {
                    subscription.OnSubscribe = channel =>
                    {
                    };
                    subscription.OnUnSubscribe = channel =>
                    {
                    };
                    subscription.OnMessage = (channel, msg) =>
                    {
                        try
                        {
                            int      index1    = msg.IndexOf(',');
                            String   Header    = msg.Substring(1, index1 - 1);
                            String[] HeaderArr = Header.Split(':');
                            if (HeaderArr.Length != 2)
                            {
                                return;
                            }
                            String ValueStr = HeaderArr[1].Trim('\"');

                            switch (ValueStr)
                            {
                            case "ToolBroken":
                            {
                                HncMessage <HNCAPI.Data.ToolBrokenInfo> tmes = Newtonsoft.Json.JsonConvert.DeserializeObject <HncMessage <HNCAPI.Data.ToolBrokenInfo> >(msg);
                                if (OnToolBroken != null)
                                {
                                    OnToolBroken(tmes.Body);
                                }
                            }
                            break;

                            case "Sample":
                            {
                                HncMessage <SampleMessge> SampleMsg = Newtonsoft.Json.JsonConvert.DeserializeObject <HncMessage <SampleMessge> >(msg);
                                if (OnSubScribeSampleData != null)
                                {
                                    OnSubScribeSampleData(SampleMsg.Body);
                                }
                            }
                            break;

                            case "HealthData":
                            {
                                HncMessage <HealthData> SampleMsg = Newtonsoft.Json.JsonConvert.DeserializeObject <HncMessage <HealthData> >(msg);
                                if (OnHealthData != null)
                                {
                                    OnHealthData(SampleMsg.Body);
                                }


                                break;
                            }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Subscribe" + ex.Message);
                        }
                    };
                    subscription.SubscribeToChannels(channelName); //blocking
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Subscribe" + ex.Message);

                this.Start();
            }
        }
Ejemplo n.º 59
0
 public RedisTransaction(RedisClient redisClient)
     : this(redisClient, false)
 {
 }
Ejemplo n.º 60
-1
 public ViewResult Student()
 {
     using (var redis = new RedisClient(new Uri(connectionString))) {
         var student = redis.As<Student>().GetAll().FirstOrDefault();
         return View(student);
     }
 }