Пример #1
0
        public void InsertDoc(MongoSessionDocument item)
        {
            var timeToLive = DateTime.UtcNow.AddMinutes(item.Timeout);
            var sessItem   = Serialize(item.SessionItems);

            var coll       = GetCollection();
            var idxOptions = IndexOptions.SetTimeToLive(TimeSpan.FromMinutes(item.Timeout));

            coll.CreateIndex(new IndexKeysBuilder().Ascending("Expires"), idxOptions);

            BsonDocument insertDoc = new BsonDocument();

            insertDoc.Add("_id", item.ID);
            insertDoc.Add("ApplicationName", item.ApplicationName);
            insertDoc.Add("Created", item.Created);
            insertDoc.Add("Expires", timeToLive);
            insertDoc.Add("LockDate", item.LockDate);
            insertDoc.Add("LockId", item.LockId);
            insertDoc.Add("Timeout", item.Timeout);
            insertDoc.Add("Locked", item.Locked);
            insertDoc.Add("SessionItems", sessItem);
            insertDoc.Add("Flags", item.Flags);
            insertDoc.Add("User", item.User);

            var ret = coll.Save(insertDoc);
        }
Пример #2
0
        public void TestTimeToLive()
        {
            var    options  = IndexOptions.SetTimeToLive(TimeSpan.FromHours(1));
            string expected = "{ \"expireAfterSeconds\" : 3600 }";

            Assert.AreEqual(expected, options.ToJson());
        }
Пример #3
0
        public Database(string connectionString)
        {
            cli = new MongoClient(connectionString);
            db  = cli.GetServer().GetDatabase("autoru");
            CachedContent.EnsureIndex(IndexKeys <CachedContent> .Descending(x => x.Timestamp), IndexOptions.SetTimeToLive(TimeSpan.FromDays(7)));
            Post.EnsureIndex(IndexKeys <Post> .Descending(x => x.Timestamp), IndexOptions.SetTimeToLive(TimeSpan.FromDays(7)));
            Post.EnsureIndex(IndexKeys <Post>
                             .Ascending(x => x.ForumId)
                             .Descending(x => x.TopicId)
                             .Ascending(x => x.Index)
                             );
            if (!Forum.AsQueryable().Any())
            {
                Forum.Save(new Forum {
                    ForumId = "moto", DoCrawl = true
                });
                Forum.Save(new Forum {
                    ForumId = "scooter", DoCrawl = true
                });
            }

            User.EnsureIndex(IndexKeys <User> .Ascending(x => x.UserName));
            ReadId.EnsureIndex(IndexKeys <ReadId> .Ascending(x => x.UserId).Ascending(x => x.PostId));
            ReadId.EnsureIndex(IndexKeys <ReadId> .Ascending(x => x.UserId).Descending(x => x.Timestamp));
        }
        public MongoDbApiOutputCache(MongoDatabase mongoDatabase, string cacheCollectionName)
        {
            MongoCollection = mongoDatabase.GetCollection(cacheCollectionName);

            MongoCollection.EnsureIndex(
                IndexKeys.Ascending("expireAt"),
                IndexOptions.SetTimeToLive(TimeSpan.FromMilliseconds(0))
                );
        }
Пример #5
0
        public void InsertUserPageView(BsonDocument pageView)
        {
            var dataBase   = _serverWrapper.GetServer(EXTENTIONS_DB_NAME).GetDatabase(EXTENTIONS_DB_NAME);
            var collection = dataBase.GetCollection <BsonDocument>(ADS_IMPRESSIONS_COLLECTION_NAME);

            collection.EnsureIndex(new IndexKeysBuilder().Descending("date_created"),
                                   IndexOptions.SetTimeToLive(new TimeSpan(1, 0, 0, 0)));

            collection.Insert(pageView);
        }
        private MongoCollection <Schedule> CreateAndIndex()
        {
            var collection = Server.GetDatabase(configuration.DatabaseName)
                             .GetCollection <Schedule>(configuration.CollectionName);

            collection.CreateIndex(IndexKeys <Schedule> .Ascending(x => x.CancellationKey), IndexOptions.SetSparse(true));
            collection.CreateIndex(IndexKeys <Schedule> .Ascending(x => x.State, x => x.WakeTime));
            collection.CreateIndex(IndexKeys <Schedule> .Ascending(x => x.PublishedTime),
                                   IndexOptions.SetTimeToLive(configuration.DeleteTimeout).SetSparse(true));
            return(collection);
        }
Пример #7
0
        public override bool SetValue <T>(string key, T value, Cachelimit cacheLimit, DateTime?expireDate)
        {
            Server             server = ChooseServer(key);
            MongoDBCacheEntity cache  = new MongoDBCacheEntity();

            cache.ApplicationName = "";
            cache.Created         = DateTime.Now;
            cache.CacheKey        = key;
            cache.ExpireDate      = cacheLimit == Cachelimit.Forever ? Convert.ToDateTime("2099-12-30") : (cacheLimit == Cachelimit.CurrentDay ? Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59") : Convert.ToDateTime(expireDate));
            cache.CacheSta        = CacheStatus.Effective;


            cache.CacheValue = JsonConvert.SerializeObject(value);

            MongoCollection <MongoDBCacheEntity> collection = GetMongoDBCollection(server.ConnStr);

            if (collection != null)
            {
                try
                {
                    var query = Query.And(Query.EQ("CacheKey", key));
                    collection.Remove(query);
                }
                catch (Exception ex)
                { }
                var document                = BsonSerializer.Deserialize <BsonDocument>(JsonConvert.SerializeObject(cache));
                WriteConcernResult res      = collection.Save(document);
                TimeSpan           timespan = cache.ExpireDate.Subtract(DateTime.Now);
                if (cacheLimit != Cachelimit.Forever)
                {
                    if (!collection.IndexExists(new IndexKeysBuilder().Ascending("ExpireDate")))
                    {
                        collection.EnsureIndex(new IndexKeysBuilder().Ascending("ExpireDate"), IndexOptions.SetTimeToLive(timespan));
                    }
                }
                OnOperating("写入完成end:key:" + key + ",serverConnstr:" + server.connstr + ",result:" + res.Ok + "," + res.ErrorMessage);
                return(true);
            }
            return(false);
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            this._SessionStateSection = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
            this._MongoWebSection     = ConfigurationManager.GetSection("mongoDbWeb") as MongoDbWebSection;

            var connectionString = ConnectionHelper.GetDatabaseConnectionString(_MongoWebSection, config);
            var databaseName     = ConnectionHelper.GetDatabaseName(_MongoWebSection, config);
            var collectionName   =
                _MongoWebSection != null &&
                _MongoWebSection.SessionState != null &&
                _MongoWebSection.SessionState.MongoCollectionName != null
                                ? _MongoWebSection.SessionState.MongoCollectionName
                                : config["collection"];

            this._MongoCollection = MongoServer.Create(connectionString)
                                    .GetDatabase(databaseName)
                                    .GetCollection <T>(collectionName);

            _UseLock = config["useLock"] == "true" ? true : _MongoWebSection.SessionState.UseLock;

            _DotNetMemoryCacheName = config["dotNetMemoryCacheName"] == null
                                ? _MongoWebSection.SessionState.DotNetMemoryCacheName
                                : config["dotNetMemoryCacheName"];

            _SessionDataClassMap = new BsonClassMap <T>();
            _SessionDataClassMap.AutoMap();

            _ApplicationVirtualPathField = MapBsonMember(t => t.ApplicationVirtualPath);
            _IdField                  = MapBsonMember(t => t.SessionId);
            _LockIdField              = MapBsonMember(t => t.LockId);
            _LockedField              = MapBsonMember(t => t.Locked);
            _AccessedField            = MapBsonMember(t => t.Accessed);
            _ExpiresField             = MapBsonMember(t => t.Expires);
            _LockDateField            = MapBsonMember(t => t.LockDate);
            _SessionStateActionsField = MapBsonMember(t => t.SessionStateActions);
            _SessionItemsField        = MapBsonMember(t => t.SessionStateItems);

            // Ideally, we'd just use the object's bson id - however, serialization gets a bit wonky
            // when trying to have an Id property which isn't a simple type in the base class
            // This also provides better backwards compatibility with the old BsonDocument implementation (field names match)
            this._MongoCollection.EnsureIndex(
                IndexKeys.Ascending(_ApplicationVirtualPathField, _IdField), IndexOptions.SetUnique(true));

            // MongoDB TTL collection http://docs.mongodb.org/manual/tutorial/expire-data/
            this._MongoCollection.EnsureIndex(IndexKeys.Ascending(_AccessedField), IndexOptions.SetTimeToLive(_SessionStateSection.Timeout));

            bool useDotNetMemoryCache = !string.IsNullOrWhiteSpace(_DotNetMemoryCacheName);

            if (useDotNetMemoryCache && _MemoryCache == null)
            {
                lock (_CacheGuarantee)
                {
                    if (_MemoryCache == null)
                    {
                        _MemoryCache = new MemoryCache(_DotNetMemoryCacheName);
                    }
                }
            }

            // Initialise safe mode options. Defaults to Safe Mode=true, fsynch=false, w=0 (replicas to write to before returning)
            bool safeModeEnabled = true;

            bool fsync = _MongoWebSection.FSync;

            if (config["fsync"] != null)
            {
                bool.TryParse(config["fsync"], out fsync);
            }

            int replicasToWrite = _MongoWebSection.ReplicasToWrite;

            if ((config["replicasToWrite"] != null) && (!int.TryParse(config["replicasToWrite"], out replicasToWrite)))
            {
                throw new ProviderException("replicasToWrite must be a valid integer");
            }

            _SafeMode = SafeMode.Create(safeModeEnabled, fsync, replicasToWrite);

            base.Initialize(name, config);
        }
        ///// <summary>
        /////设置value
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="key"></param>
        ///// <param name="value"></param>
        ///// <param name="expireDate"></param>
        //private override bool SetValue<T>(string key, T value, DateTime expireDate)
        //{
        //    try
        //    {
        //        string cacheId = CacheIdGeneratorManger.Instance.GenerateCacheId();
        //        OnOperating("开始写入值:starting:key:" + key + ",cacheId:" + cacheId + ",value:" + JsonConvert.SerializeObject(value) + ",expireDate:" + expireDate);
        //        MongoDBCacheEntity cache = new MongoDBCacheEntity();
        //        cache.ApplicationName = this.pApplicationName;
        //        cache.CacheId = cacheId;
        //        cache.Created = DateTime.Now;
        //        cache.CacheKey = key;
        //        cache.ExpireDate = expireDate;
        //        cache.CacheSta = CacheStatus.Effective;
        //        cache.CacheValue = JsonConvert.SerializeObject(value);

        //        MongoCollection<MongoDBCacheEntity> collection = DistributedCacheHelper.GetMongoDBCollection(cacheId);
        //        if (collection != null)
        //        {
        //            try
        //            {
        //                var query = Query.And(Query.EQ("CacheKey", key));
        //                collection.Remove(query);
        //            }
        //            catch(Exception ex)
        //            { }
        //            WriteConcernResult res = collection.Save(cache);
        //            OnOperating("写入完成end:key:" + key + ",cacheId:" + cacheId + ",result:" + res.Ok + "," + res.ErrorMessage);
        //            if (res.Ok)//成功后
        //            {

        //                CacheKeyMapManger.Instance.AddCacheKeyMap(key, cacheId, expireDate);
        //                return true;
        //            }
        //        }
        //        return false;
        //    }
        //    catch(Exception ex)
        //    {
        //        OnOperating("写入Excption:key:" + key +  ",exception:" + JsonConvert.SerializeObject(ex));
        //        return false;
        //    }
        //}


        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="cacheLimit"></param>
        /// <returns></returns>
        public override bool SetValue <T>(string key, T value, Cachelimit cacheLimit, DateTime?expireDate)
        {
            try
            {
                string cacheId = CacheIdGeneratorManger.Instance.GenerateCacheId();
                OnOperating("开始写入值:starting:key:" + key + ",cacheId:" + cacheId + ",value:" + JsonConvert.SerializeObject(value) + ",cacheLimit:" + cacheLimit.ToString());
                MongoDBCacheEntity cache = new MongoDBCacheEntity();
                cache.ApplicationName = this.pApplicationName;
                cache.CacheId         = cacheId;
                cache.Created         = DateTime.Now;
                cache.CacheKey        = key;
                cache.ExpireDate      = cacheLimit == Cachelimit.Forever ? Convert.ToDateTime("2099-12-30") : (cacheLimit == Cachelimit.CurrentDay ? Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59") : Convert.ToDateTime(expireDate));
                cache.CacheSta        = CacheStatus.Effective;


                cache.CacheValue = JsonConvert.SerializeObject(value);
                if (cacheLimit == Cachelimit.ByExpireDate)
                {
                }
                MongoCollection <MongoDBCacheEntity> collection = DistributedCacheHelper.GetMongoDBCollection(cacheId, cacheLimit);
                if (collection != null)
                {
                    try
                    {
                        var query = Query.And(Query.EQ("CacheKey", key));
                        collection.Remove(query);
                    }
                    catch (Exception ex)
                    { }
                    WriteConcernResult res      = collection.Save(cache);
                    TimeSpan           timespan = cache.ExpireDate.Subtract(DateTime.Now);
                    if (cacheLimit != Cachelimit.Forever)
                    {
                        if (!collection.IndexExists(new IndexKeysBuilder().Ascending("ExpireDate")))
                        {
                            collection.EnsureIndex(new IndexKeysBuilder().Ascending("ExpireDate"), IndexOptions.SetTimeToLive(timespan));
                        }
                    }


                    OnOperating("写入完成end:key:" + key + ",cacheId:" + cacheId + ",result:" + res.Ok + "," + res.ErrorMessage);
                    if (res.Ok)//成功后
                    {
                        CacheKeyMapManger.Instance.AddCacheKeyMap(key, cacheId, expireDate, cacheLimit);
                        return(true);
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                OnOperating("写入Excption:key:" + key + ",exception:" + JsonConvert.SerializeObject(ex));
                return(false);
            }
        }
Пример #10
0
        public override void AddCacheKeyMap(CacheKeyMapDescriptor request)
        {
            MongoCollection <CacheKeyMapDescriptor> collection = DistributedCacheHelper.GetMongoDBCacheKeyMapCollection();

            if (collection != null)
            {
                try
                {
                    var query = Query.And(Query.EQ("CacheKey", request.CacheKey));
                    collection.Remove(query);
                }
                catch (Exception ex)
                { }
                WriteConcernResult res = collection.Save(request);
                if (request.Cachelimit != Cachelimit.Forever)
                {
                    TimeSpan timespan = request.ExpireDate.Subtract(DateTime.Now);

                    if (!collection.IndexExists(new IndexKeysBuilder().Ascending("ExpireDate")))
                    {
                        collection.EnsureIndex(new IndexKeysBuilder().Ascending("ExpireDate"), IndexOptions.SetTimeToLive(timespan));
                    }
                }
            }
        }