Exemplo n.º 1
1
 /// <summary>
 /// Creates a new osm data cache for simple OSM objects kept in memory.
 /// </summary>
 public OsmDataCacheRedis()
 {
     _client = new RedisClient();
     _clientNode = _client.As<RedisNode>();
     _clientWay = _client.As<RedisWay>();
     _clientRelation = _client.As<RedisRelation>();
 }
Exemplo n.º 2
0
 /// <summary>
 /// Creates a new osm data cache for simple OSM objects kept in memory.
 /// </summary>
 /// <param name="redisClient"></param>
 public OsmDataCacheRedis(RedisClient redisClient)
 {
     _client = redisClient;
     _clientNode = _client.As<RedisNode>();
     _clientWay = _client.As<RedisWay>();
     _clientRelation = _client.As<RedisRelation>(); ;
 }
		public virtual void OnBeforeEachTest()
		{
			if (Redis != null) Redis.Dispose();
			Redis = new RedisClient(TestConfig.SingleHost);
			Redis.FlushDb();
			RedisTyped = Redis.As<CacheRecord>();
		}
		public virtual void OnBeforeEachTest()
		{
			if (Redis != null) Redis.Dispose();
			Redis = new RedisClient(TestConfig.SingleHost);
		    Redis.NamespacePrefix = "RedisTypedClientTests:";
			RedisTyped = Redis.As<CacheRecord>();
		}
		public override void OnBeforeEachTest()
		{
			base.OnBeforeEachTest();

			typedClient = Redis.GetTypedClient<Shipper>();			
			model = modelFactory.CreateInstance(1);
		}
Exemplo n.º 6
0
        public RedisRegistryProvider()
        {
            if (SeifApplication.AppEnv.GlobalConfiguration.RegistryConfiguration == null)
                throw new Exception("注册中心配置有误");

            string url = SeifApplication.AppEnv.GlobalConfiguration.RegistryConfiguration.Url;
            string collectionName = "RegistryData";

            var attrs = DictionaryUtils.GetFromConfig(SeifApplication.AppEnv.GlobalConfiguration.RegistryConfiguration.AddtionalFields);
            if (attrs != null && attrs.ContainsKey(AttrKeys.Registry_RedisCollectionName) )
            {
                if (!string.IsNullOrEmpty(attrs[AttrKeys.Registry_RedisCollectionName]))
                {
                    collectionName = attrs[AttrKeys.Registry_RedisCollectionName];
                }
            }

            _redisClient = new RedisClient(url);
            _typedClient = _redisClient.As<RegistryDataInfo>();
            _table = _typedClient.Lists[collectionName];

            _redisSubscription = _redisClient.CreateSubscription();
            _redisSubscription.OnMessage += (channel, msg) =>
            {
                var data = _serializer.Deserialize<ServiceRegistryMetta>(msg);
                if (this.ServiceChanged == null) return;

                this.ServiceChanged(this, new ServiceNotifyEventArgs
                {
                    Data = data
                });
            };
        }
Exemplo n.º 7
0
		/// <summary>
		/// Ctor. Obtains and stores a reference to a typed Redis client.
		/// </summary>
		public RedisQueueClient()
		{
			_client = new RedisClient(Settings.Default.RedisHost, Settings.Default.RedisPort);
			_taskMessageClient = _client.GetTypedClient<TaskMessage>();

			_log.Info("Connected to Redis.");
			_log.DebugFormat("Connection Properties: {0}:{1}",
				Settings.Default.RedisHost, Settings.Default.RedisPort);
		}
        public override void Observe()
        {
            RefreshDb();

            _redisClient = new RedisClient(_host);
            _packageClient = _redisClient.As<Package>();

            _package = new Package {Id = Guid.NewGuid()};

            _writeRepository = Container.Resolve<INEventStoreRepository<Package>>();
        }
Exemplo n.º 9
0
		public RedisQueueService(Uri baseUri, bool resume)
		{
			using (RedisClient redisClient = new RedisClient())
			{
				_redis = redisClient.GetTypedClient<Entry>();
				_queue = _redis.Lists[string.Format("barcodes:{0}:queue", baseUri)];
				if (!resume)
				{
					_queue.Clear();
				}
			}
		}
Exemplo n.º 10
0
		public RedisHistoryService(Uri baseUri, bool resume)
		{
			using (RedisClient redisClient = new RedisClient())
			{
				_redis = redisClient.GetTypedClient<string>();
				_history = _redis.Sets[string.Format("barcodes:{0}:history", baseUri)];
				if (!resume)
				{
					_history.Clear();
				}
			}
		}
        public void SetUp()
        {
            if (client != null)
            {
                client.Dispose();
                client = null;
            }
            client = new RedisClient(TestConfig.SingleHost);
            client.FlushAll();

            redis = client.GetTypedClient<CustomType>();

            List = redis.Lists[ListId];
            List2 = redis.Lists[ListId2];
        }
		public override void OnBeforeEachTest()
		{
			base.OnBeforeEachTest();

			redisQuestions = base.Redis.GetTypedClient<Question>();

			q1Answers = new List<Answer>
          	{
          		Answer.Create(1, question1.Id),
          		Answer.Create(2, question1.Id),
          		Answer.Create(3, question1.Id),
          		Answer.Create(4, question1.Id),
          		Answer.Create(5, question1.Id),
          	};
		}
		public override void OnBeforeEachTest()
		{
			base.OnBeforeEachTest();

			redisQuestions = base.Redis.As<Question>();
		    redisQuestions.Db = 10;
		    redisQuestions.FlushDb();

			q1Answers = new List<Answer>
          	{
          		Answer.Create(1, question1.Id),
          		Answer.Create(2, question1.Id),
          		Answer.Create(3, question1.Id),
          		Answer.Create(4, question1.Id),
          		Answer.Create(5, question1.Id),
          	};
		}
Exemplo n.º 14
0
        public async Task Send <T>(ConsumeContext <T> context, ISagaPolicy <TSaga, T> policy,
                                   IPipe <SagaConsumeContext <TSaga, T> > next) where T : class
        {
            if (!context.CorrelationId.HasValue)
            {
                throw new SagaException("The CorrelationId was not specified", typeof(TSaga), typeof(T));
            }

            var   sagaId = context.CorrelationId.Value;
            TSaga instance;

            using (var redis = _clientsManager.GetClient())
            {
                IRedisTypedClient <TSaga> sagas = redis.As <TSaga>();

                if (policy.PreInsertInstance(context, out instance))
                {
                    await PreInsertSagaInstance <T>(sagas, instance).ConfigureAwait(false);
                }

                if (instance == null)
                {
                    instance = sagas.GetById(sagaId);
                }
            }

            if (instance == null)
            {
                var missingSagaPipe = new MissingPipe <T>(_clientsManager, next);
                await policy.Missing(context, missingSagaPipe).ConfigureAwait(false);
            }
            else
            {
                await SendToInstance(context, policy, next, instance).ConfigureAwait(false);
            }
        }
Exemplo n.º 15
0
        public ActionResult AboutPhone()
        {
            string message = string.Empty;
            string host    = "localhost";

            using (RedisClient redisClient = new RedisClient(host))
            {
                IRedisTypedClient <Phone> phones = redisClient.As <Phone>();
                Phone phoneFive = phones.GetValue(5.ToString());
                if (phoneFive == null)
                {
                    // make a small delay
                    Thread.Sleep(5000);
                    phoneFive = new Phone
                    {
                        Id           = 5,
                        Manufacturer = "Motorolla",
                        Model        = "xxxxx",
                        Owner        = new Person
                        {
                            Id         = 1,
                            Age        = 90,
                            Name       = "OldOne",
                            Profession = "sportsmen",
                            Surname    = "OldManSurname"
                        }
                    };
                    phones.SetEntry(phoneFive.Id.ToString(), phoneFive);
                }
                message  = "Phone model is " + phoneFive.Manufacturer;
                message += "Phone Owner Name is: " + phoneFive.Owner.Name;
                message += "Phone Id is: " + phoneFive.Id.ToString();
            }
            ViewBag.Message = message;
            return(View("Index"));
        }
Exemplo n.º 16
0
        public bool DeleteAllData <T>()
        {
            try
            {
                using (var redis = redisManager.GetClient())
                {
                    IRedisTypedClient <T> redis1 = redis as IRedisTypedClient <T>;

                    var datas = redis1.GetAll();
                    foreach (var item in datas)
                    {
                        redis1.Delete(item);
                    }

                    return(true);
                }
            }
            catch
            {
                //print ke log
                //throw;
                return(false);
            }
        }
Exemplo n.º 17
0
 public RedisRepository()
 {
     redisDB          = RedisManager.GetClient();
     redisTypedClient = redisDB.As <TEntity>();
     table            = redisTypedClient.Lists[typeof(TEntity).Name];
 }
Exemplo n.º 18
0
 public TaskRepositoryImplementation(IRedisClient redisClient)
 {
     this.redisClient = redisClient.As <Models.Task>();
 }
 public RedisPostRepository(Uri serverUri)
 {
     _bareClient = new RedisClient(serverUri);
     _client = _bareClient.As<Post>();
 }
 public RedisPostRepository()
 {
     _bareClient = new RedisClient();
     _client = _bareClient.As<Post>();
 }
Exemplo n.º 21
0
        public void persistStoredCache()
        {
            using (RedisClient redisClient = new RedisClient(host))
            {
                IRedisTypedClient <CpuUsage> processes = redisClient.As <CpuUsage>();
                Dictionary <string, Process> process   = new Dictionary <string, Process>();
                int previousCount = redisCount - 60;
                //Get objects for the previous minute
                for (int i = 0; i < 60; i++)
                {
                    CpuUsage         processTable = processes.GetValue(previousCount.ToString());
                    ProcessArrayList response     = processTable.process;
                    //check if object for id exist
                    if (processTable != null)
                    {
                        foreach (DictionaryEntry item in response.process)
                        {
                            string    json    = item.Value.ToString();
                            ArrayList rowItem = JsonConvert.DeserializeObject <ArrayList>(json);
                            //Exclude idle and Total processes both with PID 0
                            if (!rowItem[1].ToString().Equals("0"))
                            {
                                //check if process is already in the Dictionary
                                if (process.ContainsKey(rowItem[0].ToString()))
                                {
                                    Process listProcess;
                                    process.TryGetValue(rowItem[0].ToString(), out listProcess);
                                    //check if the new CPU usage is greater than the previous one
                                    //if so replace the new CPU usage with the old one
                                    if (Int32.Parse(listProcess.usage) < Int32.Parse(rowItem[2].ToString()))
                                    {
                                        listProcess.usage = rowItem[2].ToString();
                                        process[rowItem[0].ToString()] = listProcess;
                                    }
                                }
                                else
                                {
                                    //Add new entry to the Dictionary
                                    Process newProcess = new Process
                                    {
                                        name  = rowItem[0].ToString(),
                                        usage = rowItem[2].ToString()
                                    };

                                    process.Add(rowItem[0].ToString(), newProcess);
                                }
                            }
                        }
                    }
                    previousCount++;
                }
                //Persist the final result to database
                DatabaseFactory.connectToDatabase();
                foreach (var processKey in process.Keys)
                {
                    string sql    = "INSERT INTO process_longterm_usage(name,usage) VALUES('" + process[processKey].name + "','" + process[processKey].usage + "')";
                    int    result = DatabaseFactory.executeNonQuery(sql);
                    if (result < 0)
                    {
                        continue;
                    }
                }
                DatabaseFactory.closeConnection();
            }
        }
 public RedisContainerCacheStrategy()
 {
     //_config = RedisConfigInfo.GetConfig();
     _client = RedisManager.GetClient();
     _cache = _client.As<IContainerItemCollection>();
 }
Exemplo n.º 23
0
 public RedisTypeInfoClient()
 {
     this.client = new RedisClient("127.0.0.1", 6379);
     this.Store = this.client.As<TypeInfo>();
 }
 /// <summary>
 /// Initializes this data processor.
 /// </summary>
 public override void Initialize()
 {
     _nodeTypeClient     = _redisClient.As <RedisNode>();
     _wayTypeClient      = _redisClient.As <RedisWay>();
     _relationTypeClient = _redisClient.As <RedisRelation>();
 }
Exemplo n.º 25
0
 public Cache(IRedisClientsManager redisClientsManager)
 {
     this.redisClient      = redisClientsManager.GetClient();
     this.oAuthTypedClient = redisClient.As <T>();
 }
Exemplo n.º 26
0
 public override void SetUp()
 {
     base.SetUp();
     this._typedClient = this.Redis.As <Shipper>();
     this._model       = this._modelFactory.CreateInstance(1);
 }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            // ilk önce Sunucu ile aramızda bir kanal açalım
            using (RedisClient client = new RedisClient("127.0.0.1", 6379))
            {
                // T ile belirtilen tip ile çalışabileceğimiz bir Redis arayüzünü tedarik etmemizi sağlar
                IRedisTypedClient <Person> personStore = client.As <Person>();

                #region Örnek bir veri kümesinin eklenmesi

                // Temiz bir başlangıç için istenirse var olan Person kümesi silinebilir de
                if (personStore.GetAll().Count > 0)
                {
                    personStore.DeleteAll();
                }

                // Bir kaç örnek departman ve personel verisi oluşturuyoruz
                Department itDepartment = new Department
                {
                    DepartmentId = 1000,
                    Name         = "IT",
                    Description  = "Information Technologies"
                };
                Department financeDepartment = new Department
                {
                    DepartmentId = 1000,
                    Name         = "Finance",
                    Description  = "Finance Unit"
                };

                List <Person> persons = new List <Person>
                {
                    new Person
                    {
                        PersonId     = personStore.GetNextSequence()
                        , Name       = "Burak"
                        , Level      = 100
                        , Department = itDepartment
                    },
                    new Person
                    {
                        PersonId     = personStore.GetNextSequence()
                        , Name       = "Bill"
                        , Level      = 200
                        , Department = itDepartment
                    },
                    new Person
                    {
                        PersonId     = personStore.GetNextSequence()
                        , Name       = "Adriana"
                        , Level      = 250
                        , Department = itDepartment
                    },
                    new Person
                    {
                        PersonId     = personStore.GetNextSequence()
                        , Name       = "Sakira"
                        , Level      = 300
                        , Department = financeDepartment
                    },
                    new Person
                    {
                        PersonId     = personStore.GetNextSequence()
                        , Name       = "Bob"
                        , Level      = 550
                        , Department = financeDepartment
                    }
                };

                // Elemanları StoreAll metodu yardımıyla Redis' e alıyoruz.
                personStore.StoreAll(persons);

                #endregion Örnek bir veri kümesinin eklenmesi

                #region Verileri elde etmek, sorgulamak

                Console.WriteLine("Tüm Personel");
                // Kaydettiğimiz elemanların tamamını GetAll metodu yardımıyla çekebiliriz.
                foreach (var person in personStore.GetAll())
                {
                    Console.WriteLine(person.ToString());
                }

                // Dilersek içeride tutulan Key/Value çiftlerinden Key değerlerine ulaşabiliriz
                List <string> personKeys = personStore.GetAllKeys();

                Console.WriteLine("\nKey Bilgileri");
                foreach (var personKey in personKeys)
                {
                    Console.WriteLine(personKey);
                }

                // İstersek bir LINQ sorgusunu GetAll metodu üstünden dönen liste üzerinden çalıştırabiliriz
                IOrderedEnumerable <Person> itPersons = personStore
                                                        .GetAll()
                                                        .Where <Person>(p => p.Department.Name == "IT")
                                                        .OrderByDescending(p => p.Level);

                Console.WriteLine("\nSadece IT personeli");
                foreach (var itPerson in itPersons)
                {
                    Console.WriteLine(itPerson.ToString());
                }

                // Random bir Key değeri alabilir ve bunun karşılığı olan value' yu çekebiliriz
                string randomKey = personStore.GetRandomKey();
                Console.WriteLine("\nBulunan Key {0}", randomKey);
                // seq:Person ve ids:Person key değerleri için hata oluşacağından try...catch' den kaçıp başka bir kontrol yapmaya çalışıyoruz.
                if (randomKey != personStore.SequenceKey &&
                    randomKey != "ids:Person")
                {
                    var personByKey = personStore[randomKey];
                    Console.WriteLine("{0}", personByKey.ToString());
                }

                personStore.SaveAsync(); // Kalıcı olarak veriyi persist edebiliriz. Asenkron olarak yapılabilen bir işlemdir.

                #endregion Verileri elde etmek, sorgulamak

                Console.WriteLine("\nÇıkmak için bir tuşa basınız");
                Console.ReadLine();
            }
        }
Exemplo n.º 28
0
 public PersonRepositroyRedis()
 {
     client = redisClient.As <Person>();
 }
        /// <summary>
        /// 获取链表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <returns></returns>
        public IList <T> GetList <T>(string listId)
        {
            IRedisTypedClient <T> iredisClient = client.As <T>();

            return(iredisClient.Lists[listId]);
        }
        private void RedisSeedDatabase()
        {
            redis.FlushAll();

            redisStudents = redis.As<Student>();

            var persistedStudent = new Student
            {
                Id = redisStudents.GetNextSequence(),
                Name = "Hugo Estevam Longo",
                Age = 30,
                Birthday = new DateTime(1985, 10, 31),
                Actived = true
            };

            redisStudents.Store(persistedStudent);
        }
Exemplo n.º 31
0
 public void Connect()
 {
     _redisClient = new RedisClient(ConfigurationManager.AppSettings["DbIpAddress"]);
     _typedClient = _redisClient.As <TA>();
     FlushDb();
 }
 public StudentRedisRepository()
 {
     redis = new RedisClient("localhost", 6379);
     redisStudents = redis.As<Student>();
 }
Exemplo n.º 33
0
 /// <summary>
 /// Initializes this data processor.
 /// </summary>
 public override void Initialize()
 {
     _nodeTypeClient = _redisClient.As<RedisNode>();
     _wayTypeClient = _redisClient.As<RedisWay>();
     _relationTypeClient = _redisClient.As<RedisRelation>();
 }
Exemplo n.º 34
0
 public RedisQueue(RedisClient _client)
 {
     redisClient = _client;
     jobStore = redisClient.As<Job>();
 }
Exemplo n.º 35
0
 public Service1()
 {
     this.Manager     = new RedisManagerPool();
     this.redisClient = Manager.GetClient().As <Alumno>();
 }
Exemplo n.º 36
0
 public RedisRepository(RedisDataContext context)
 {
     _client      = context.Client();
     _typedClient = _client.As <TEntity>();
     _type        = typeof(TEntity).ToString();
 }
Exemplo n.º 37
0
        public void persistStoredCache(int startCount)
        {
            //IDatabase db = redis.GetDatabase();
            using (RedisClient redisClient = new RedisClient(host))
            {
                IRedisTypedClient <CpuUsage> processes = redisClient.As <CpuUsage>();
                Dictionary <string, Process> process   = new Dictionary <string, Process>();
                //Get objects for the previous minute
                for (int i = 0; i < 60; i++)
                {
                    //CpuUsage processTable = JsonConvert.DeserializeObject<CpuUsage>(db.StringGet(startCount.ToString()));
                    CpuUsage         processTable = processes.GetValue(startCount.ToString());
                    ProcessArrayList response     = processTable.process;
                    //check if object for id exist
                    if (processTable != null)
                    {
                        foreach (DictionaryEntry item in response.process)
                        {
                            string    json    = item.Value.ToString();
                            ArrayList rowItem = JsonConvert.DeserializeObject <ArrayList>(json);
                            //Exclude idle and Total processes both with PID 0
                            if (!rowItem[6].ToString().Equals("0"))
                            {
                                //check if process is already in the Dictionary
                                if (process.ContainsKey(rowItem[2].ToString()))
                                {
                                    Process listProcess;
                                    process.TryGetValue(rowItem[2].ToString(), out listProcess);
                                    //check if the new CPU usage is greater than the previous one
                                    //if so replace the new CPU usage with the old one
                                    if (Int32.Parse(listProcess.PercentProcessorTime) < Int32.Parse(rowItem[7].ToString()))
                                    {
                                        listProcess.UsageDateKey         = rowItem[0].ToString();
                                        listProcess.UsageTimeKey         = rowItem[1].ToString();
                                        listProcess.CreatingProcessID    = rowItem[3].ToString();
                                        listProcess.ElapsedTime          = rowItem[4].ToString();
                                        listProcess.HandleCount          = rowItem[5].ToString();
                                        listProcess.IDProcess            = rowItem[6].ToString();
                                        listProcess.PercentProcessorTime = rowItem[7].ToString();
                                        listProcess.PercentUserTime      = rowItem[8].ToString();
                                        listProcess.ThreadCount          = rowItem[9].ToString();

                                        process[rowItem[0].ToString()] = listProcess;
                                    }
                                }
                                else
                                {
                                    //Add new entry to the Dictionary
                                    Process newProcess = new Process
                                    {
                                        UsageDateKey         = rowItem[0].ToString(),
                                        UsageTimeKey         = rowItem[1].ToString(),
                                        Name                 = rowItem[2].ToString(),
                                        CreatingProcessID    = rowItem[3].ToString(),
                                        ElapsedTime          = rowItem[4].ToString(),
                                        HandleCount          = rowItem[5].ToString(),
                                        IDProcess            = rowItem[6].ToString(),
                                        PercentProcessorTime = rowItem[7].ToString(),
                                        PercentUserTime      = rowItem[8].ToString(),
                                        ThreadCount          = rowItem[9].ToString()
                                    };
                                    process.Add(rowItem[2].ToString(), newProcess);
                                }
                                //check if process is in the database
                                //if process is not there store the new process name
                                if (!sqldb.checkIfProcessExist(rowItem[2].ToString()))
                                {
                                    sqldb.persistProcessName(rowItem[2].ToString());
                                }
                            }
                        }
                    }
                    startCount++;
                }
                //Persist the final result to database
                foreach (var processKey in process.Keys)
                {
                    string processId = sqldb.getProcessKey(process[processKey].Name);
                    sqldb.persistData(process[processKey].UsageDateKey, process[processKey].UsageTimeKey, processId, process[processKey].CreatingProcessID, process[processKey].ElapsedTime, process[processKey].HandleCount, process[processKey].IDProcess, process[processKey].PercentProcessorTime, process[processKey].PercentUserTime, process[processKey].ThreadCount);
                }
            }
        }
 public UserRepository(string redisUrl)
 {
     _client = new RedisClient(new Uri(redisUrl));
     _typedUserClient = _client.GetTypedClient<User>();
     _typedUserNameLookupClient = _client.GetTypedClient<UserNameLookup>();
 }
Exemplo n.º 39
0
        ///// <summary>
        ///// The redist node clients.
        ///// </summary>
        //private IRedisTypedClient<SimpleRelation> _relation_type_client;
        /// <summary>
        /// Initializes this data processor.
        /// </summary>
        public override void Initialize()
        {
            _node_type_client = _redis_client.GetTypedClient<OsmNode>();
            _way_type_client = _redis_client.GetTypedClient<OsmWay>();
            //_relation_type_client = _redis_client.GetTypedClient<SimpleRelation>();

             //redis = redisClient.GetTypedClient<OsmNode>()
            _cached_nodes = new Dictionary<long, SimpleNode>();
            _nodes_in_ways = new Dictionary<long, OsmNode>();
        }
Exemplo n.º 40
0
        public void Shippers_UseCase()
        {
            using (var redisClient = new RedisClient(TestConfig.SingleHost))
            {
                //Create a 'strongly-typed' API that makes all Redis Value operations to apply against Shippers
                IRedisTypedClient <Shipper> redis = redisClient.As <Shipper>();

                //Redis lists implement IList<T> while Redis sets implement ICollection<T>
                var currentShippers     = redis.Lists["urn:shippers:current"];
                var prospectiveShippers = redis.Lists["urn:shippers:prospective"];

                currentShippers.Add(
                    new Shipper {
                    Id          = redis.GetNextSequence(),
                    CompanyName = "Trains R Us",
                    DateCreated = DateTime.UtcNow,
                    ShipperType = ShipperType.Trains,
                    UniqueRef   = Guid.NewGuid()
                });

                currentShippers.Add(
                    new Shipper {
                    Id          = redis.GetNextSequence(),
                    CompanyName = "Planes R Us",
                    DateCreated = DateTime.UtcNow,
                    ShipperType = ShipperType.Planes,
                    UniqueRef   = Guid.NewGuid()
                });

                var lameShipper = new Shipper {
                    Id          = redis.GetNextSequence(),
                    CompanyName = "We do everything!",
                    DateCreated = DateTime.UtcNow,
                    ShipperType = ShipperType.All,
                    UniqueRef   = Guid.NewGuid()
                };

                currentShippers.Add(lameShipper);

                Dump("ADDED 3 SHIPPERS:", currentShippers);

                currentShippers.Remove(lameShipper);

                Dump("REMOVED 1:", currentShippers);

                prospectiveShippers.Add(
                    new Shipper {
                    Id          = redis.GetNextSequence(),
                    CompanyName = "Trucks R Us",
                    DateCreated = DateTime.UtcNow,
                    ShipperType = ShipperType.Automobiles,
                    UniqueRef   = Guid.NewGuid()
                });

                Dump("ADDED A PROSPECTIVE SHIPPER:", prospectiveShippers);

                redis.PopAndPushItemBetweenLists(prospectiveShippers, currentShippers);

                Dump("CURRENT SHIPPERS AFTER POP n' PUSH:", currentShippers);
                Dump("PROSPECTIVE SHIPPERS AFTER POP n' PUSH:", prospectiveShippers);

                var poppedShipper = redis.PopItemFromList(currentShippers);
                Dump("POPPED a SHIPPER:", poppedShipper);
                Dump("CURRENT SHIPPERS AFTER POP:", currentShippers);

                //reset sequence and delete all lists
                redis.SetSequence(0);
                redis.RemoveEntry(currentShippers, prospectiveShippers);
                Dump("DELETING CURRENT AND PROSPECTIVE SHIPPERS:", currentShippers);
            }
        }
 public RedisContainerCacheStrategy()
 {
     //_config = RedisConfigInfo.GetConfig();
     _client = RedisManager.GetClient();
     _cache  = _client.As <IContainerItemCollection>();
 }
 public RedisPostRepository(string host, int port, string password = null)
 {
     _bareClient = new RedisClient(host, port, password);
     _client = _bareClient.As<Post>();
 }
Exemplo n.º 43
0
 public CacheManager()
 {
     _redis  = _redisManager.GetClient();
     _entity = _redis.As <T>();
 }
 public override void SetUp()
 {
     base.SetUp();
     this.Redis.NamespacePrefix = "RedisTypedClientTests:";
     this._redisTyped           = this.Redis.As <CacheRecord>();
 }
Exemplo n.º 45
0
        private void GenerateSubMaps(ProgressionCounter progression)
        {
            double total = MapsManager.Instance.MapsCount;

            progression.UpdateValue(0, "Loading all maps ...");
            m_mapsPosition = MapsPositionManager.Instance.EnumerateAllMaps().ToDictionary(x => x.MapId);
            int counter = 0;

            Parallel.ForEach(MapsManager.Instance.EnumerateMaps(), map =>
            {
                var builder = new SubMapBuilder();
                AdjacentSubMap[] submaps = builder.GenerateBinders(map);

                m_submaps.TryAdd(map.Id, submaps);

                // update the counter (in percent)
                Interlocked.Increment(ref counter);
                if (counter % 30 == 0)
                {
                    lock (progression)
                    {
                        if (counter % 30 == 0)
                        {
                            progression.UpdateValue(total == 0 ? 100d : (counter / total) * 100d);
                        }
                    }
                }
            });

            progression.UpdateValue(0, "Binding submaps together ...");
            counter = 0;
            Parallel.ForEach(m_submaps, cacheEntry =>
            {
                var neighbours = new[]
                {
                    TryGetMapNeighbour(cacheEntry.Key, MapNeighbour.Right),
                    TryGetMapNeighbour(cacheEntry.Key, MapNeighbour.Top),
                    TryGetMapNeighbour(cacheEntry.Key, MapNeighbour.Left),
                    TryGetMapNeighbour(cacheEntry.Key, MapNeighbour.Bottom),
                };

                foreach (AdjacentSubMap submap in cacheEntry.Value)
                {
                    for (MapNeighbour neighbour = MapNeighbour.Right; neighbour <= MapNeighbour.Bottom; neighbour++)
                    {
                        int i = (int)neighbour - 1;

                        if (neighbours[i] == null)
                        {
                            continue;
                        }

                        MapNeighbour opposite = GetOppositeDirection(neighbour);
                        AdjacentSubMap[] submaps;
                        int mapChangeData         = Map.MapChangeDatas[neighbour];
                        int oppositeMapChangeData = Map.MapChangeDatas[neighbour];
                        int cellChangement        = Map.MapCellChangement[neighbour];

                        if (neighbours[i] != null && m_submaps.TryGetValue(neighbours[i].Value, out submaps))
                        {
                            lock (submaps)
                                foreach (AdjacentSubMap neighbourSubmap in submaps)
                                {
                                    // neighbor already set
                                    lock (submap.SubMap.Neighbours)
                                        if (submap.SubMap.Neighbours.Any(x => x.GlobalId == neighbourSubmap.SubMap.GlobalId))
                                        {
                                            continue;
                                        }

                                    // if any cell of the submaps is a transition to another submap
                                    AdjacentSubMap submap1 = neighbourSubmap;
                                    short[] links          = submap.ChangeCells.Where(x => (x.MapChangeData & mapChangeData) != 0 &&
                                                                                      submap1.ChangeCells.Any(y => y.Id == x.Id + cellChangement)).Select(x => x.Id).ToArray();
                                    if (links.Length > 0)
                                    {
                                        // set in the two ways
                                        lock (submap.SubMap.Neighbours)
                                            lock (neighbourSubmap.SubMap.Neighbours)
                                            {
                                                submap.SubMap.Neighbours.Add(new SubMapNeighbour(neighbourSubmap.SubMap.GlobalId, new MovementTransition(neighbour, links)));
                                                neighbourSubmap.SubMap.Neighbours.Add(new SubMapNeighbour(submap.SubMap.GlobalId,
                                                                                                          new MovementTransition(opposite, links.Select(x => (short)(x + cellChangement)).ToArray())));
                                            }
                                    }
                                }
                        }
                    }
                }

                // update the counter (in percent)
                Interlocked.Increment(ref counter);
                if (counter % 30 == 0)
                {
                    lock (progression)
                    {
                        if (counter % 30 == 0)
                        {
                            progression.UpdateValue(counter / (double)m_submaps.Count * 100d);
                        }
                    }
                }
            });


            using (IRedisClient client = m_clientManager.GetClient())
            {
                progression.UpdateValue(0, "Storing informations on Redis server...");

                IRedisTypedClient <SubMapBinder> typedClient1 = client.As <SubMapBinder>();
                typedClient1.SetRangeInHash(typedClient1.GetHash <long>(REDIS_KEY), m_submaps.Values.SelectMany(x => x).ToDictionary(x => x.SubMap.GlobalId, x => x.SubMap));
                progression.UpdateValue(50);

                IRedisTypedClient <long[]> typedClient2 = client.As <long[]>();
                typedClient2.SetRangeInHash(typedClient2.GetHash <int>(REDIS_MAPS), m_submaps.ToDictionary(x => x.Key, x => x.Value.Select(y => y.SubMap.GlobalId).ToArray()));
                progression.UpdateValue(100);

                client.Set(REDIS_VERSION, VERSION);
            }

            m_submaps.Clear();
            m_mapsPosition.Clear();

            progression.NotifyEnded();
        }
Exemplo n.º 46
0
        /// <summary>
        ///     获取链表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="listId"></param>
        /// <returns></returns>
        public IEnumerable <T> GetList <T>(string listId)
        {
            IRedisTypedClient <T> iredisClient = Redis.As <T>();

            return(iredisClient.Lists[listId]);
        }
 public RedisITypedRedisClientFacade(IRedisTypedClient <T> redisTypedClient)
 {
     this.redisTypedClient = redisTypedClient;
 }
Exemplo n.º 48
0
 public RedisCacheRepository(RedisDataContext context)
 {
     _client      = context.Client();
     _typedClient = _client.As <RedisCacheEntity <TEntity> >();
     setDomain();
 }
Exemplo n.º 49
0
 public EventStorageService(IOptions <BotConfiguration> config, IRedisClientsManager redisClientsManager)
 {
     this.redisClient = redisClientsManager.GetClient().As <IncomingEvent>();
 }
Exemplo n.º 50
0
 public CachingPipe(IRedisClient redisClient)
 {
     _redisClient = redisClient.As <TResponse>();
 }
Exemplo n.º 51
0
        public ActionResult Index()
        {
            string message = string.Empty;
            string host    = "localhost";

            using (var redisClient = new RedisClient(host))
            {
                //Create a 'strongly-typed' API that makes all Redis Value operations to apply against Phones
                IRedisTypedClient <Phone> redis = redisClient.As <Phone>();

                //Redis lists implement IList<T> while Redis sets implement ICollection<T>
                IRedisList <Phone> mostSelling   = redis.Lists["urn:phones:mostselling"];
                IRedisList <Phone> oldCollection = redis.Lists["urn:phones:oldcollection"];

                Person phonesOwner = new Person
                {
                    Id         = 7,
                    Age        = 90,
                    Name       = "OldOne",
                    Profession = "sportsmen",
                    Surname    = "OldManSurname"
                };

                // adding new items to the list
                mostSelling.Add(new Phone
                {
                    Id           = 5,
                    Manufacturer = "Sony",
                    Model        = "768564564566",
                    Owner        = phonesOwner
                });

                mostSelling.Add(new Phone
                {
                    Id           = 8,
                    Manufacturer = "Motorolla",
                    Model        = "324557546754",
                    Owner        = phonesOwner
                });

                var upgradedPhone = new Phone
                {
                    Id           = 3,
                    Manufacturer = "LG",
                    Model        = "634563456",
                    Owner        = phonesOwner
                };

                mostSelling.Add(upgradedPhone);

                // remove item from the list
                oldCollection.Remove(upgradedPhone);

                // find objects in the cache
                IEnumerable <Phone> LGPhones = mostSelling.Where(ph => ph.Manufacturer == "LG");

                // find specific
                Phone singleElement = mostSelling.FirstOrDefault(ph => ph.Id == 8);

                //reset sequence and delete all lists
                redis.SetSequence(0);
                redisClient.Remove("urn:phones:mostselling");
                redisClient.Remove("urn:phones:oldcollection");
            }
            ViewBag.Message = message;
            return(View());
        }
Exemplo n.º 52
0
        private static void UpdateRedisTick(IRedisTypedClient <Tick> redisTickClient, int secId, DateTime dtAyondoNow, IList <Quote> quotes, TickSize tickSize)
        {
            //redis tick list
            var list = redisTickClient.Lists[Ticks.GetTickListNamePrefix(tickSize) + secId];

            if (quotes.Count == 0) //fill in non-changing ticks
            {
                if (list.Count > 0)
                {
                    var last = list[list.Count - 1];

                    //redis last tick is newer
                    if (last.T >= dtAyondoNow)
                    {
                        return;//impossible
                    }

                    //update last tick in redis
                    if (Ticks.IsTickEqual(last.T, dtAyondoNow, tickSize))
                    {
                        //do nothing
                    }
                    else //append new tick with the same price as redis last
                    {
                        list.Add(new Tick()
                        {
                            P = last.P, T = dtAyondoNow
                        });
                    }
                }
            }
            else
            {
                var lastQuote = quotes.OrderByDescending(o => o.Time).First();
                var newTick   = new Tick {
                    P = Quotes.GetLastPrice(lastQuote), T = dtAyondoNow
                };

                if (list.Count == 0) //new products coming
                {
                    list.Add(newTick);
                    return;
                }

                var last = list[list.Count - 1];

                //redis last tick is newer
                if (last.T >= dtAyondoNow)
                {
                    return;//impossible
                }

                //update last tick in redis
                if (Ticks.IsTickEqual(last.T, dtAyondoNow, tickSize))
                {
                    ////last price dominate
                    //list[list.Count - 1] = newTick;

                    //first price dominate
                    //do nothing
                }
                else //append new last tick
                {
                    list.Add(newTick);
                }
            }

            //clear history/prevent data increasing for good
            var clearWhenSize = Ticks.GetClearWhenSize(tickSize);
            var clearToSize   = Ticks.GetClearToSize(tickSize);

            if (list.Count > clearWhenSize) //data count at most possible size (in x days )
            {
                YJYGlobal.LogLine("Tick " + tickSize + " " + secId + " Clearing data from " + list.Count + " to " + clearToSize);
                var ticks    = list.GetAll();
                var newTicks = ticks.Skip(ticks.Count - clearToSize);
                list.RemoveAll();
                list.AddRange(newTicks);
            }
        }
 public UserRepository(string redisUrl)
 {
     _client                    = new RedisClient(new Uri(redisUrl));
     _typedUserClient           = _client.GetTypedClient <User>();
     _typedUserNameLookupClient = _client.GetTypedClient <UserNameLookup>();
 }
Exemplo n.º 54
0
 public DriverRepository()
 {
     var uri = new Uri(ConfigurationManager.AppSettings["REDISTOGO_URL"]);
     redisTypedClient = new RedisClient(uri).As<Driver>();
 }
Exemplo n.º 55
0
        private static void UpdateKLine(List <Quote> quotes, IRedisTypedClient <KLine> redisKLineClient, ProdDef prodDef,
                                        DateTime dtAyondoNow, KLineSize kLineSize)
        {
            var list = redisKLineClient.Lists[KLines.GetKLineListNamePrefix(kLineSize) + prodDef.Id];

            if (quotes.Count == 0)              //no quotes received, then should just fill the non-changing candle
            {
                if (kLineSize != KLineSize.Day) //no need to fill the non-changing candle for day kline
                {
                    if (list.Count != 0)
                    {
                        var last = list[list.Count - 1];

                        var klineTime = KLines.GetKLineTime(dtAyondoNow, kLineSize, prodDef);

                        if (prodDef.QuoteType == enmQuoteType.Closed)
                        {
                            klineTime = KLines.GetKLineTime(prodDef.LastClose.Value, kLineSize);
                        }

                        if (klineTime > last.T) //a new candle?
                        {
                            //fill the non-changing candle
                            list.Add(new KLine()
                            {
                                T = klineTime,
                                O = last.C,
                                C = last.C,
                                H = last.C,
                                L = last.C,
                            });
                        }
                    }
                }
            }
            else
            {
                var orderedQuotes = quotes.OrderBy(o => o.Time).ToList();

                var firstQuote = orderedQuotes.First();
                var lastQuote  = orderedQuotes.Last();

                var klineTime1 = KLines.GetKLineTime(firstQuote.Time, kLineSize, prodDef);
                var klineTime2 = KLines.GetKLineTime(lastQuote.Time, kLineSize, prodDef);

                //var list = redisKLineClient.Lists[KLines.GetKLineListNamePrefix(kLineSize) + prodDef.Id];

                if (klineTime1 != klineTime2 && kLineSize != KLineSize.Day) //quotes range more than 1 candle
                {
                    var list1 = orderedQuotes.Where(o => o.Time < klineTime2).ToList();
                    var list2 = orderedQuotes.Where(o => o.Time >= klineTime2).ToList();

                    var k1 = new KLine()
                    {
                        T = klineTime1,
                        O = Quotes.GetLastPrice(list1.First()),
                        C = Quotes.GetLastPrice(list1.Last()),
                        H = list1.Max(o => Quotes.GetLastPrice(o)),
                        L = list1.Min(o => Quotes.GetLastPrice(o)),
                    };
                    var k2 = new KLine()
                    {
                        T = klineTime2,
                        O = Quotes.GetLastPrice(list2.First()),
                        C = Quotes.GetLastPrice(list2.Last()),
                        H = list2.Max(o => Quotes.GetLastPrice(o)),
                        L = list2.Min(o => Quotes.GetLastPrice(o)),
                    };

                    if (list.Count == 0)
                    {
                        list.Add(k1);
                        list.Add(k2);
                    }
                    else
                    {
                        var last = list[list.Count - 1];

                        if (last.T < klineTime1) //2 new candles to append
                        {
                            list.Add(k1);
                            list.Add(k2);
                        }
                        else if (last.T == klineTime1) //update last 1, append 1 new
                        {
                            list[list.Count - 1] = new KLine()
                            {
                                T = last.T,
                                O = last.O,
                                C = k1.C,
                                H = Math.Max(last.H, k1.H),
                                L = Math.Min(last.L, k1.L),
                            };

                            list.Add(k2);
                        }
                        else
                        {
                            //should not be here
                        }
                    }
                }
                else //quotes range within 1 candle
                {
                    var k = new KLine()
                    {
                        T = klineTime1,
                        O = Quotes.GetLastPrice(firstQuote),
                        C = Quotes.GetLastPrice(lastQuote),
                        H = orderedQuotes.Max(o => Quotes.GetLastPrice(o)),
                        L = orderedQuotes.Min(o => Quotes.GetLastPrice(o)),
                    };

                    if (list.Count == 0)
                    {
                        list.Add(k);
                    }
                    else
                    {
                        var last = list[list.Count - 1];

                        if (last.T < k.T) //append 1 new
                        {
                            list.Add(k);
                        }
                        else if (last.T == k.T) //update last 1
                        {
                            list[list.Count - 1] = new KLine()
                            {
                                T = last.T,
                                O = last.O,
                                C = k.C,
                                H = Math.Max(last.H, k.H),
                                L = Math.Min(last.L, k.L),
                            };
                        }
                        else
                        {
                            //should not be here
                        }
                    }
                }
            }

            //clear history/prevent data increasing for good
            var clearWhenSize = KLines.GetClearWhenSize(kLineSize);
            var clearToSize   = KLines.GetClearToSize(kLineSize);

            if (list.Count > clearWhenSize) //data count at most possible size (in x days )
            {
                YJYGlobal.LogLine("KLine " + kLineSize + " " + prodDef.Id + " Clearing data from " + list.Count + " to " +
                                  clearToSize);
                var klines    = list.GetAll();
                var newKLines = klines.Skip(klines.Count - clearToSize);
                list.RemoveAll();
                list.AddRange(newKLines);
            }
        }