Пример #1
0
        static void Main(string[] args)
        {
            ServiceStackHelper.Help();

            using (var redisManager = new PooledRedisClientManager())
            using (var redis = redisManager.GetClient())
            {
                var redisTodos = redis.As<Todo>();
                for (int i = 0; i < 20000; i++)
                {
                    var todo = new Todo
                    {
                        Id = redisTodos.GetNextSequence(),
                        Content = "Learn Redis",
                        Order = 1,
                    };
                    redisTodos.Store(todo);
                    Todo savedTodo = redisTodos.GetById(todo.Id);
                    savedTodo.Done = true;
                    redisTodos.Store(savedTodo);
                    //"Updated Todo:".Print();
                    //redisTodos.GetAll().ToList().PrintDump();

                    redisTodos.DeleteById(savedTodo.Id);
                }

                "No more Todos:".Print();
                redisTodos.GetAll().ToList().PrintDump();
            }
            Console.ReadLine();
        }
Пример #2
0
        static RedisClientPoolManager()
        {
            try
            {
                connectTimeout = ConfigUtils.GetSetting("Redis.ConnectTimeout", 1);
                poolTimeOut = ConfigUtils.GetSetting("Redis.PoolTimeOut", 300);
                var readWriteHosts = ConfigUtils.GetSetting("Redis.Host.ReadWrite").Split(',');
                var readOnlyHosts = ConfigUtils.GetSetting("Redis.Host.ReadOnly").Split(',');
                var password = ConfigUtils.GetConnectionString("Redis.RequirePass");
                var dbIndex = ConfigUtils.GetSetting("Redis.Db", 0);
                dbIndex = dbIndex < 0 ? 0 : dbIndex;

                readWriteHosts = ConvertHost(readWriteHosts, password);
                readOnlyHosts = ConvertHost(readOnlyHosts, password);

                var config = new RedisClientManagerConfig()
                {
                    //“写”链接池链接数
                    MaxWritePoolSize = ConfigUtils.GetSetting("Redis.WritePool.MaxSize", 200),
                    //“读”链接池链接数
                    MaxReadPoolSize = ConfigUtils.GetSetting("Redis.Read.MaxSize", 200),
                    AutoStart = true
                };
                prcm = new PooledRedisClientManager(readWriteHosts, readOnlyHosts, config, dbIndex, PoolSizeMultiplier, poolTimeOut);
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Init the redis pool manager error:{0}", ex);
            }
        }
Пример #3
0
 private static void Pump()
 {
     var pool = new PooledRedisClientManager(new string[] {"127.0.0.1"});
     pool.ConnectTimeout = 30000;
     pool.SocketSendTimeout = 30000;
     pool.SocketReceiveTimeout = 30000;
     var today = DateTime.Today;
     for (var d = 0; d < _forwardDays; d++)
     {
         var ds = today.AddDays(d).ToString("yyyy-MM-dd");
         for (var r = 1; r <= _numberOfRids; r++)
         {
             for (var ps = 1; ps <= _partySizeCacheMax; ps++)
             {
                 var key = string.Format("AS1_{0}_{1}_{2}", r, ds, ps);
                 var val = string.Format("{0}_0_abcdefgh0123456789012345678901234567890123456789", r);
                 try
                 {
                     using (IRedisClient client = pool.GetClient())
                     {
                         client.Set(key, val);
                     }
                 }
                 catch (Exception)
                 {
                 }
             }
         }
     }
 }
Пример #4
0
 public long GenerateNewId()
 {
     using (var client = new PooledRedisClientManager(_redisHost).GetClient())
     {
         return client.As<long>().GetNextSequence();
     }
 }
Пример #5
0
        public static bool SaveMeals(IList<Meal> meals)
        {
            using (var redisManager = new PooledRedisClientManager("[email protected]:9038"))
            {
                using (var client = redisManager.GetCacheClient())
                {
                    IList<bool> result = new List<bool>();
                    //save meals by date...add to workout dates
                    foreach (Meal meal in meals)
                    {
                        Meal tempMeal = client.Get<Meal>(String.Format(saveMeals, meal.MealDate));
                        if (tempMeal != null && tempMeal.Foods != null)
                        {
                            foreach (var food in meal.Foods)
                                tempMeal.Foods.Add(food);
                            result.Add(client.Set<Meal>(String.Format(saveMeals, meal.MealDate), tempMeal));
                        }
                        else
                        {
                            result.Add(client.Add<Meal>(String.Format(saveMeals, meal.MealDate), meal));
                            WorkoutClient.AddWorkoutDate(meal.MealDate.Date);
                        }
                    }

                    return !result.Contains(false);
                }
            }
        }
Пример #6
0
 public Task<bool> DeleteDataBulk(IEnumerable<dynamic> Ids, string CollectionName)
 {
     try
     {
         using (var redisManager = new PooledRedisClientManager())
         using (var redis = redisManager.GetClient())
         {
             foreach (var Fid in Ids)
             {
                 var datas = redis.ScanAllKeys($"{DBName}:{CollectionName}:{Fid}");
                 foreach (var item in datas)
                 {
                     redis.Remove(item);
                 }
             }
             return Task.FromResult(true);
         }
     }
     catch
     {
         //print ke log
         //throw;
         return Task.FromResult(false); ;
     }
 }
        public override void Configure(Funq.Container container)
        {
            PathProvider.BinaryPath = "~".MapAbsolutePath();

            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

			RequestBinders.Add(typeof(CommitAttempt), request => new CommitAttempt()
			{
				UserAgent = request.Headers["User-Agent"],
				RawBody = request.GetRawBody()
			});
			

            Routes
                .Add<CommitAttempt>("/commit")
                .Add<CommitMessages>("/commits")
                .Add<MessageErrors>("/errors")

            //    //.Add<CommitMessage>("/commitMessage")
              ;

            var redisFactory = new PooledRedisClientManager("localhost:6379");
            container.Register<IRedisClientsManager>(redisFactory);
            //var mqHost = new RedisMqHost(redisFactory);
            var mqHost = new RedisMqServer(redisFactory);

            container.Register<IMessageService>(mqHost);
            container.Register(mqHost.MessageFactory);

            mqHost.RegisterHandler<CommitAttempt>(ServiceController.ExecuteMessage);
            //mqHost.RegisterHandler<CommitMessage>(ServiceController.ExecuteMessage);

            mqHost.Start();
        }
Пример #8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var pooledClientManager = new PooledRedisClientManager("localhost");
        var client = pooledClientManager.GetClient();
        var blogRedis = new BlogRedis(client);
        var memberRedis = new MemberRedis(client);

        var Id = Request["ID"];
        var idNull = string.IsNullOrEmpty(Id);
        Item = new Member();
        using (var con = DAL.con())
        {
            if (!idNull)
            {
                var blog = blogRedis.GetById(Convert.ToInt64(Id));

                Item = memberRedis.GetByUsername(blog.NguoiTao);
                //blog.Anhs = AnhDal.SelectByPId(con, blog.RowId.ToString(), 20);
                //blog.Profile = Item;
                ViewForProfile.Xes = Item.GetXe(client);
                ViewForProfile.Nhoms = Item.GetNhom(client);
                ViewForProfile.Pager = BinhLuanDal.PagerByPRowId(con, "", true, blog.RowId.ToString(), 20);
                ViewForProfile.Blog = blog;
                ViewForProfile.Item = Item;
            }
        }
    }
Пример #9
0
        public override void Configure(Container container)
        {
            string sc = ConfigurationManager.AppSettings.Get("DbConnection");

            string rchost= ConfigurationManager.AppSettings.Get("SessionRedisHost");
            rchost= (string.IsNullOrEmpty(rchost))? "localhost:6379": rchost;

            string rcpassword= ConfigurationManager.AppSettings.Get("SessionRedisPassword");

            string rcdbs=  ConfigurationManager.AppSettings.Get("SessionRedisDb");
            int rcdb;
            if(! int.TryParse(rcdbs, out rcdb) ) rcdb= 10;

            string sstout = ConfigurationManager.AppSettings.Get("SessionTimeout");
            int sessionTimeout;
            if(! int.TryParse(sstout, out sessionTimeout) ) sessionTimeout= 60*8;

            var cacheClient= new  BasicRedisClientManager( new string[]{rchost}, new string[]{rchost}, rcdb);
            cacheClient.GetClient().Password= rcpassword;

            container.Register<IAuthProvider>( new BdAuthProvider()
            {
                DbFactory=new ConnectionFactory(sc,  FirebirdDialectProvider.Instance),
                AuthUserSession= new UserSession()
                {
                    CacheClient= cacheClient,
                    TimeOut=sessionTimeout,
                }
            });

            string phost= ConfigurationManager.AppSettings.Get("CacheHost");
            phost = (string.IsNullOrEmpty(phost))?"localhost:6379":phost;

            string pdbs= ConfigurationManager.AppSettings.Get("CacheDb");
            int pdb ;
            if(! int.TryParse(pdbs, out pdb) ) pdb= 9;

            string ppassword= ConfigurationManager.AppSettings.Get("CachePassword");

            var p = new PooledRedisClientManager(new string[]{phost}, new string[]{phost}, pdb);
            p.GetClient().Password= ppassword;
            container.Register<ICacheClient>( p);
            container.Register<IDbConnectionFactory>(
                new ConnectionFactory(sc,  FirebirdDialectProvider.Instance)
            );

            //Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method
            base.SetConfig(new EndpointHostConfig
            {
                GlobalResponseHeaders =
                    {
                        { "Access-Control-Allow-Origin", "*" },
                        { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
                        { "Access-Control-Allow-Headers","X-Requested-With"}
                    },
            });

            log.InfoFormat("AppHost Configured: " + DateTime.Now);
        }
Пример #10
0
 //Método requerido para establecer una conexión con el servicio de Redis
 private static void RedisConnection()
 {
     if (redisClient == null)
     {
         var clientsManager = new PooledRedisClientManager(RedisUri);
         redisClient = clientsManager.GetClient();
     }
 }
Пример #11
0
 public static List<Article> ListArticles()
 {
     using (var pooledRedisClient = new PooledRedisClientManager())
     using (var redis = pooledRedisClient.GetClient())
     {
         return redis.Sets["Articles"].Select(x => redis.GetById<Article>(int.Parse(x))).ToList<Article>();
     }
 }
Пример #12
0
 public Article ReadArticle(int id)
 {
     using (var pooledRedisClient = new PooledRedisClientManager())
     using (var redis = pooledRedisClient.GetClient())
     {
         return redis.GetById<Article>(id);
     }
 }
Пример #13
0
 public User ReadUser(int userId)
 {
     using (var pooledRedisClient = new PooledRedisClientManager())
     using (var redis = pooledRedisClient.GetClient())
     {
         return redis.GetById<User>(userId);
     }
 }
Пример #14
0
 /// <summary>
 /// 建立连接池
 /// </summary>
 public void BuildRedisPoolClient()
 {
     RedisClientManagerConfig RedisConfig = new RedisClientManagerConfig();
     RedisConfig.AutoStart = true;
     RedisConfig.MaxReadPoolSize = RedisServicePoolSize;
     RedisConfig.MaxWritePoolSize = RedisServicePoolSize;
     PooledRedisClient = new PooledRedisClientManager(RedisServiceAddress, RedisServiceAddress, RedisConfig);
 }
Пример #15
0
 public void DeleteUser(int userId)
 {
     using (var pooledRedisClient = new PooledRedisClientManager())
     using (var redis = pooledRedisClient.GetClient())
     {
         var redisUser = redis.As<User>();
         redisUser.DeleteById(userId); // Delete old user using ID
     }
 }
Пример #16
0
 public void DeleteArticle(int id)
 {
     using (var pooledRedisClient = new PooledRedisClientManager())
     using (var redis = pooledRedisClient.GetClient())
     {
         var redisArticle = redis.As<Article>();
         redisArticle.DeleteById(id);
     }
 }
 public Comment ReadComment(int commentId)
 {
     using (var pooledRedisClient = new PooledRedisClientManager())
     using (var redis = pooledRedisClient.GetClient())
     {
         Comment target = redis.GetById<Comment>(commentId);
         return target;
     }
 }
 public void DeleteComment(int commentId)
 {
     using (var pooledRedisClient = new PooledRedisClientManager())
     using (var redis = pooledRedisClient.GetClient())
     {
         var redisComment = redis.As<Comment>();
         redisComment.DeleteById(commentId); // Delete old user using ID
     }
 }
Пример #19
0
 /// <summary>
 /// 关闭
 /// </summary>
 public void Close()
 {
     if (_prcm != null)
     {
         //_client.Shutdown();
         _prcm.Dispose();
         _prcm = null;
     }
 }
 private static IRedisClientsManager InitRedisClientsManager()
 {
     List<string> rwServers = new List<string>();
     List<string> roServers = new List<string>();
     rwServers.Add(ConfigurationManager.AppSettings["RedisMasterServerUrl"]);
     roServers.Add(ConfigurationManager.AppSettings["RedisSlave1ServerUrl"]);
     var redisClientManager = new PooledRedisClientManager(rwServers, roServers);
     return redisClientManager;
 }
Пример #21
0
 // New methods using usernames instead of IDs
 public static User ReadUsername(string username)
 {
     using (var pooledRedisClient = new PooledRedisClientManager())
     using (var redis = pooledRedisClient.GetClient())
     {
         User target = redis.GetById<User>(redis.Get<int>(username + ":id"));
         return target;
     }
 }
Пример #22
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var pooledClientManager = new PooledRedisClientManager("localhost");
        var client = pooledClientManager.GetClient();
        var alias = Request["Alias"];
        using (var con = DAL.con())
        {
            var objRedis = new ObjRedis(client);

            var obj = objRedis.GetByAlias(alias);
            if(obj != null && !string.IsNullOrEmpty(obj.Url))
            {
                Response.Redirect(obj.Url, true);
            }

            var memberRedis = new MemberRedis(client);
            var promotedUsers = memberRedis.GetXacNhanItems(0, 7);
            //UserHomeList.List = MemberDal.SelectPromoted(con, 8, 61);
            UserHomeList.List = promotedUsers;

            var blogRedis = new BlogRedis(client);
            //var userBlogs = BlogDal.SelectTopBlogProfile(con, 10, Security.Username, null);
            var userBlogs = blogRedis.GetNhatKyItems(0, 9);
            blogTop.List = userBlogs;
            //var carBlogs = BlogDal.SelectTopBlogXe(con, 10, Security.Username, null);
            var carBlogs = blogRedis.GetHanhTrinhItems(0, 10);
            nhatKyXeTop.List = carBlogs;

            var xeRedis = new XeRedis(client);
            //var topCars = XeDal.HomeTop;
            var topCars = xeRedis.GetAllItems(0, 9);
            //var newstpCars = XeDal.HomeNewest;
            var newstpCars = xeRedis.GetTopItems(0, 9);

            topCarsList.List = topCars;
            newestCarsList.List = newstpCars;

            promotedHome.Visible = false;
            promotedHome.HomeBig = XeDal.PromotedHomeBig.FirstOrDefault();
            promotedHome.HomeMedium = XeDal.PromotedHomeMedium.Take(2).ToList();
            promotedHome.HomeSMall = XeDal.PromotedHomeSmall.Take(4).ToList();

            var loaiDanhMucRedis = new LoaiDanhMucRedis(client);
            var hangXe = loaiDanhMucRedis.GetByAlias("HANGXE");

            //var hangXeList = DanhMucDal.SelectByLDMMa(con, "HANGXE");
            if(hangXe!=null)
            {
                var hangXeList = hangXe.GetDanhMuc(client);
                var hangList = (from p in hangXeList
                                where p.PID == Guid.Empty
                                select p).OrderBy(m => m.ThuTu).ToList();
                LeftMenu.List = hangList;
            }
        }
    }
Пример #23
0
        private void btnConnection_Click(object sender, EventArgs e)
        {
            PooledRedisClientManager pool = new ServiceStack.Redis.PooledRedisClientManager();

            //string d = RedisOperation.Client.GetValue("12");
            string[] str  = new string[] { "1", "2" };
            string   json = JsonSerializer(str);
            //bool result= RedisOperation.Client.Set<string>(txtData.Text,
            //  json );
        }
Пример #24
0
 public static bool SaveExercises(IList<Event> exercises)
 {
     using (var redisManager = new PooledRedisClientManager("[email protected]:9038"))
     {
         using (var client = redisManager.GetCacheClient())
         {
             return client.Add<IList<Event>>(selectExercises, exercises);
         }
     }
 }
Пример #25
0
        /// <summary>
        /// 连接池进行创建连接
        /// </summary>
        /// <returns></returns>
        public IRedisClient GetClient(List<string> readwritehosts,List<string> readhosts)
        {
            RedisClientManagerConfig redisconfig = new RedisClientManagerConfig();
            redisconfig.MaxReadPoolSize = 5;
            redisconfig.MaxWritePoolSize = 5;
            redisconfig.AutoStart = true;

            PooledRedisClientManager poolredis = new PooledRedisClientManager(readwritehosts, readhosts, redisconfig);
            return poolredis.GetClient();
        }
Пример #26
0
 public static bool SaveGoals(IList<ContestEventGoal> goals)
 {
     using (var redisManager = new PooledRedisClientManager("[email protected]:9038"))
     {
         using (var client = redisManager.GetCacheClient())
         {
             return client.Add<IList<ContestEventGoal>>(getGoals, goals);
         }
     }
 }
Пример #27
0
 public static IList<FoodEntry> GetFoodEntries(DateTime entryDate)
 {
     using (var redisManager = new PooledRedisClientManager("[email protected]:9038"))
     {
         using (var client = redisManager.GetCacheClient())
         {
             return client.Get<IList<FoodEntry>>(String.Format(getFoodEntries, entryDate));
         }
     }
 }
Пример #28
0
 public static IList<Entities.CurrentStatistic> RetrieveProfile()
 {
     using (var redisManager = new PooledRedisClientManager("[email protected]:9038"))
     {
         using (var client = redisManager.GetCacheClient())
         {
             return client.Get<IList<CurrentStatistic>>(getProfile);
         }
     }
 }
Пример #29
0
 public static IList<Entities.ContestEventGoal> RetrieveGoals()
 {
     using (var redisManager = new PooledRedisClientManager("[email protected]:9038"))
     {
         using (var client = redisManager.GetCacheClient())
         {
             return client.Get<IList<ContestEventGoal>>(getGoals);
         }
     }
 }
Пример #30
0
 public static bool SaveFoods(IList<Food> foods)
 {
     using (var redisManager = new PooledRedisClientManager("[email protected]:9038"))
     {
         using (var client = redisManager.GetCacheClient())
         {
             return client.Add<IList<Food>>(selectFoods, foods);
         }
     }
 }
Пример #31
0
 public static bool SaveProfile(IList<CurrentStatistic> profile)
 {
     using (var redisManager = new PooledRedisClientManager("[email protected]:9038"))
     {
         using (var client = redisManager.GetCacheClient())
         {
             return client.Add<IList<CurrentStatistic>>(getProfile, profile);
         }
     }
 }
        public RedisSentinelWorker(string host, string sentinelName, PooledRedisClientManager clientsManager = null)
        {
            this.sentinelName                   = sentinelName;
            this.sentinelClient                 = new RedisClient(host);
            this.sentinelPubSubClient           = new RedisClient(host);
            this.sentinelSubscription           = this.sentinelPubSubClient.CreateSubscription();
            this.sentinelSubscription.OnMessage = SentinelMessageReceived;
            this.clientsManager                 = clientsManager;

            Log.Info("Set up Redis Sentinel on {0}".Fmt(host));
        }
Пример #33
0
        private string GetKeyValue(string key)
        {
            var settingsProvider = GetSettingsProvider();
            var settings         = settingsProvider.GetSettings().Result as RedisLockSettings;

            using (var client = new ST.PooledRedisClientManager(settings.Hosts.ToArray()))
            {
                var client1 = client.GetClient();
                var value   = client1.GetValue(key);
                return(value);
            }
        }
Пример #34
0
        private RedisClient getClient(Int32 port)
        {
            try {
                if (_Manager == null)
                {
                    _Manager = new PooledRedisClientManager(2, 3000, new String[] { _ip + ":" + _RedisLocalPort.ToString() });
                    //_Manager.Start();
                }
                RedisClient client = (RedisClient)_Manager.GetClient();

                if (client.Ping())
                {
                    return(client);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("getClientLocal" + e.Message);
            }
            return(null);
        }
Пример #35
0
        private void GetValidSentinel()
        {
            while (this.clientManager == null && ShouldRetry())
            {
                try
                {
                    this.worker        = GetNextSentinel();
                    this.clientManager = worker.GetClientManager();
                    this.worker.BeginListeningForConfigurationChanges();
                }
                catch (RedisException)
                {
                    if (this.worker != null)
                    {
                        this.worker.SentinelError -= Worker_SentinelError;
                        this.worker.Dispose();
                    }

                    this.failures++;
                }
            }
        }
Пример #36
0
        private void GetValidSentinel()
        {
            while (this.clientManager == null && failures < RedisSentinel.MaxFailures)
            {
                try
                {
                    worker        = GetNextSentinel();
                    clientManager = worker.GetClientManager();
                    worker.BeginListeningForConfigurationChanges();
                }
                catch (RedisException)
                {
                    if (worker != null)
                    {
                        worker.SentinelError -= Worker_SentinelError;
                        worker.Dispose();
                    }

                    failures++;
                }
            }
        }
Пример #37
0
        /// <summary>
        /// 发布
        /// </summary>
        public void Pub()
        {
            ServiceStack.Redis.IRedisClientsManager RedisClientManager = new ServiceStack.Redis.PooledRedisClientManager("127.0.0.1.65:6379");
            //发布、订阅服务 IRedisPubSubServer
            ServiceStack.Redis.RedisPubSubServer pubSubServer = new ServiceStack.Redis.RedisPubSubServer(RedisClientManager, "channel-1");

            pubSubServer.OnMessage = (channel, msg) =>
            {
                Console.WriteLine(string.Format("服务端:频道{0}接收消息:{1}    时间:{2}", channel, msg, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                Console.WriteLine("___________________________________________________________________");
            };
            pubSubServer.OnStart = () =>
            {
                Console.WriteLine("发布服务已启动");
                Console.WriteLine("___________________________________________________________________");
            };
            pubSubServer.OnStop        = () => { Console.WriteLine("服务停止"); };
            pubSubServer.OnUnSubscribe = (channel) => { Console.WriteLine(channel); };
            pubSubServer.OnError       = (e) => { Console.WriteLine(e.Message); };
            pubSubServer.OnFailover    = (s) => { Console.WriteLine(s); };
            pubSubServer.Start();
        }