您现在的位置是:网站首页> 编程资料编程资料
windows7下使用MongoDB实现仓储设计_MongoDB_
2023-05-27
750人已围观
简介 windows7下使用MongoDB实现仓储设计_MongoDB_
简单的介绍一下,我使用MongoDB的场景。
我们现在的物联网环境下,有部分数据,采样频率为2000条记录/分钟,这样下来一天24*60*2000=2880000约等于300万条数据,以后必然还会增加。之前数据库使用的是mssql,对于数据库的压力很大,同时又需要保证历史查询的响应速度,这种情况下,在单表中数据量大,同时存在读写操作。不得已采用MongoDB来存储数据。如果使用MongoDB,则至少需要三台机器,两台实现读写分离,一台作为仲裁(当然条件不允许也可以不用),每台机器的内存暂时配置在16G,公司小,没办法,据说,使用这个MongoDB需要机器内存最少92G,我没有验证过,但是吃内存是公认的,所以内存绝对要保证,就算保证了,也不一定完全就没有意外发生。我们上面的这些特殊的数据是允许少量的丢失的,这些只是做分析使用的,几个月了,暂时还没出现数据丢失的情况,可能最新版本早就修复了吧,新手使用建议多看下官网上的说明。下面直接奔入主题:
一、安装部署和配置环境
1.安装部署mongo-server(V3.4)
参考 点击这里进入
这个时候不要启动,接着配置config文件
2.配置Config文件
dbpath=C:/Program Files/MongoDB/Server/3.4/bin/data/db logpath=C:/Program Files/MongoDB/Server/3.4/bin/data/log/master.log pidfilepath=C:/Program Files/MongoDB/Server/3.4/bin/master.pid directoryperdb=true logappend=true replSet=testrs bind_ip=10.1.5.25 port=27016 oplogSize=10000 noauth = true storageEngine = wiredTiger wiredTigerCacheSizeGB = 2 syncdelay = 30 wiredTigerCollectionBlockCompressor = snappy
以上是详细的配置参数,其中路径部分根据需要更改, 这里设置的oplogsize大小为10G,根据业务场景进行调整,另外auth权限为null,因为设置权限会增加服务开销,影响效率,最下面几行是内存引擎,可以控制副本集同步及内存限制,防止内存泄露。
3.启动mongo-server
4.添加副本集配置
conf= { "_id" : "testrs", "members" : [ { "_id" : 0, "host" : "10.1.5.25:27016" }, { "_id" : 1, "host" : "10.1.5.26:27016" }, { "_id" : 2, "host" : "10.1.5.27:27016" } ] } rs.initiate(conf) 此时副本集集群配置已经完成,然后在命令行中输入:rs.status(),查看副本集状态,需要查看同步情况,可以输入命令:db.serverStatus().
5.设置副本集可读写
Rs.slaveOk()
6..NET操作mongo
连接设置,请参考个人封装Unitoon.Mongo代码所示。
7.性能对比
读写速度:Redis>Mongo>Mssqlserver
可容纳数据量:Mssqlserver~Mongo>Redis
存储数据类型:Mongo>Mssqlserver>Redis
Note:内存持续上升,内部没有内存回收机制,若限制内存 ,则可能出现查询速度变慢,数据丢失等问题,建议优化查询效率,建立索引
Db.test.ensureIndex({"username":1, "age":-1})
强制释放内存命令:db.runCommand({closeAllDatabases:1})
二、仓储设计
1.基类BaseEntity
namespace UnitoonIot.Mongo { /// /// 实体基类,方便生成ObjId /// [Serializable] [ProtoContract(ImplicitFields = ImplicitFields.AllPublic)] //[ProtoInclude(10, typeof(NormalHistory))] public class BaseEntity { //[BsonRepresentation(BsonType.ObjectId)] public ObjectId Id { get; set; } /// /// 数据库名称 /// public string DbName { get; set; } /// /// 给对象初值 /// public BaseEntity() { // this.ObjId = ObjectId.GenerateNewId().ToString(); //this.Id = ObjectId.NewObjectId().ToString(); } } }
这里需要注意时间格式,MongoDB默认时间格式为国际时间,所以在写入数据时和读取数据时,时间格式要一致,此例中没有对时间进行特殊处理,由传入的时间格式确定。
2.Repository继承接口IMongoRepository
namespace UnitoonIot.Mongo { public interface IMongoRepository where TEntity : class { } }
3.MongoRepository
using MongoDB.Driver; using MongoDB.Bson; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver.Linq; using System.Configuration; using System.IO; using UnitoonIot.AppSetting; namespace UnitoonIot.Mongo { public class MongoDb { private static string ConnectionStringHost ; private static string UserName ; private static string Password; private static IMongoDatabase _db = null; private static readonly object LockHelper = new object(); /// /// mongodb初始化 /// public static void Init() { ConnectionStringHost = "10.1.5.24:27016,10.1.5.24:27016,10.1.5.26:27017"; //AppSettings.GetConfigValue("MongoHost");//"10.1.5.24:27016"; UserName = AppSettings.GetConfigValue("MongoUserName"); Password = AppSettings.GetConfigValue("MongoPwd"); } static MongoDb() { } public static IMongoDatabase GetDb(string dbName,string options=null) { if (_db != null) return _db; lock (LockHelper) { if (_db != null) return _db; var database = dbName; var userName = UserName; var password = Password; var authentication = string.Empty; var host = string.Empty; if (!string.IsNullOrWhiteSpace(userName)) { authentication = string.Concat(userName, ':', password, '@'); } if (!string.IsNullOrEmpty(options) && !options.StartsWith("?")) { options = string.Concat('?', options); } host = string.IsNullOrEmpty(ConnectionStringHost) ? "localhost" : ConnectionStringHost; database = database ?? "testdb"; //mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]] var conString = options!=null? $"mongodb://{authentication}{host}/{database}{options}" : $"mongodb://{authentication}{host}/{database}"; var url = new MongoUrl(conString); var mcs = MongoClientSettings.FromUrl(url); mcs.MaxConnectionLifeTime = TimeSpan.FromMilliseconds(1000); var client = new MongoClient(mcs); _db = client.GetDatabase(url.DatabaseName); } return _db; } } /// /// MongoDb 数据库操作类 /// public class MongoRepository: IMongoRepository where T : BaseEntity { #region readonly field /// /// 表名 /// private readonly IMongoCollection _collection = null; /// /// 数据库对象 /// private readonly IMongoDatabase _database; #endregion /// /// 构造函数 /// public MongoRepository() { this._database = MongoDb.GetDb(Activator.CreateInstance().DbName, "readPreference =secondaryPreferred ");//primaryPreferred/secondaryPreferred/nearest _collection = _database.GetCollection(typeof(T).Name); } #region 增加 /// /// 插入对象 /// /// 插入的对象 public virtual T Insert(T t) { // var flag = ObjectId.GenerateNewId(); // t.GetType().GetProperty("Id").SetValue(t, flag); //t.Time = DateTime.Now; _collection.InsertOne(t); return t; } /// /// 批量插入 /// /// 要插入的对象集合 public virtual IEnumerable InsertBatch(IEnumerable ts) { _collection.InsertMany(ts); return ts; } /// /// 插入对象 /// /// 插入的对象 public virtual void InsertAsync(T t) { //var flag = ObjectId.GenerateNewId(); // t.GetType().GetProperty("Id").SetValue(t, flag); // t.Time = DateTime.Now; _collection.InsertOneAsync(t); } /// /// 批量插入 /// /// 要插入的对象集合 public virtual void InsertBatchAsync(IEnumerable ts) { _collection.InsertManyAsync(ts); } #endregion #region 删除 /// /// 删除 /// /// public virtual long Delete(T t) { var filter = Builders.Filter.Eq("Id", t.Id); var result = _collection.DeleteOne(filter); return result.DeletedCount; } /// /// 删除 /// /// public virtual void DeleteAsync(T t) { var filter = Builders.Filter.Eq("Id", t.Id); _collection.DeleteOneAsync(filter); } /// /// 按条件表达式删除 /// /// 条件表达式 /// public virtual long Delete(Expression> predicate) { var result = _collection.DeleteOne(predicate); return result.DeletedCount; } /// /// 按条件表达式删除 /// /// 条件表达式 /// public virtual void DeleteAsync(Expression> predicate) { _collection.DeleteOneAsync(predicate); } /// /// 按条件表达式批量删除 /// /// 条件表达式 /// public virtual long DeleteBatch(Expression> predicate) { var result = _collection.DeleteMany(predicate); return result.DeletedCount; } /// /// 按条件表达式批量删除 /// /// 条件表达式 /// public virtual void DeleteBatchAsync(Expression> predicate) { _collection.DeleteManyAsync(predicate); } /// /// 按检索条件删除 /// 建议用Builders构建复杂的查询条件 /// /// 条件 /// public virtual long Delete(FilterDefinition filter) { var result = _collection.DeleteOne(filter); return result.DeletedCount; } /// /// 按检索条件删除 /// 建议用Builders构建复杂的查询条件 /// /// 条件 /// public virtual void DeleteAsync(FilterDefinition filter) { _collection.DeleteOneAsync(filter); } #endregion #region 修改 /// /// 修改(Id不变) /// /// public virtual long Update(T t) { var filterBuilder = Builders.Filter; var filter = filterBuilder.Eq("Id",t.Id); var update = _collection.ReplaceOne(filter, t, new UpdateOptions() { IsUpsert = true }); return update.ModifiedCount; } /// /// 修改(Id不变) /// /// public virtual void UpdateAsync(T t) { var filterBuilder = Builders.Filter; var filter = filterBuilder.Eq("Id", t.Id); _collection.ReplaceOneAsync(filter, t, new UpdateOptions() { IsUpsert = true }); } /// /// 用新对象替换新文档 /// /// 查询条件 /// 对象 /// 修改影响文档数 public virtual long Update(Expression> filter, T t) { var update = _collection.ReplaceOne(filter, t, new UpdateOptions() { IsUpsert = true }); return update.ModifiedCount; } /// /// 用新对象替换新文档 /// /// 查询条件 /// 对象 /// 修改影响文档数 public virtual long Update(FilterDefinition filter, T t) { var update = _collection.ReplaceOne(filter, t, new UpdateOptions() { IsUpsert = true }); return update.ModifiedCount; } /// /// 用新对象替换新文档 /// /// 查询条件 /// 对象 /// 修改影响文档数 public virtual void UpdateAsync(Expression> filter, T t) { _collection.ReplaceOneAsync(filter, t, new UpdateOptions() { IsUpsert = true }); } /// /// 用新对象替换新文档 /// /// 查询条件
相关内容
- java操作mongoDB查询的实例详解_MongoDB_
- MongoDB 查询操作的实例详解_MongoDB_
- MongoDB开源数据库开发工具dbKoda_MongoDB_
- MongoDB如何查询耗时记录的方法详解_MongoDB_
- MongoDB 3.4 安装以 Windows 服务方式运行的详细步骤_MongoDB_
- 详解MongoDB数据库基础操作及实例_MongoDB_
- MongoDB 3.4配置文件避免入坑的注意事项_MongoDB_
- Mongodb常用的身份验证方式_MongoDB_
- mongodb操作的模块手动封装_MongoDB_
- mongodb增删改查详解_动力节点Java学院整理_MongoDB_
点击排行
本栏推荐
