検索

c#链接mongDB集群实战开发3

Jun 07, 2016 pm 03:56 PM
実戦開発するリンク集まる

c# 链接mongDB集群 一 了解mongdb 二 部署集群 三 C#链接mongdb 完成测试 C#链接mongdb 完成测试 此章节继续我们上一章节将的我们开始用程序去链接mondbdb,大家都知道我们链接sqlserver其实用的是微软自己写的驱动。它已经封装了一些对象,要我们去链接。但

c# 链接mongDB集群

一 了解mongdb

二 部署集群

三 C#链接mongdb 完成测试 

C#链接mongdb 完成测试

此章节继续我们上一章节将的我们开始用程序去链接mondbdb,大家都知道我们链接sqlserver其实用的是微软自己写的驱动。它已经封装了一些对象,要我们去链接。但是我们链接mondbdb 同样需要一些对象,这个mongdb官网有说明,可以自己去看看或者直接下载我的这里下载 或者在第一章节有些伙伴们已经下载好了

开发驱动文件夹 在 mongo-csharp-driver-master\mongo-csharp-driver-master\src SRC下面看到驱动项目这里注意,我下载是vs2012的项目,同学们可以根据自己的需要替换net framework 版本

打开项目之后看到 如图所示

\

编译项目得到

MongoDB.Bson.dll

MongoDB.Driver.dll

创建项目,项目配置文件如下

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="LogLevel" value="trace" />
    <add key="LogPath" value="E:\Tools\mongdb\FrmMongDB\FrmMongDB\logs" />
    
    <!--MongDb配置begin-->
    <add key="MongReplicaSetName" value="zuomm"/><!--设置副本集名称-->
    <add key="MongoServerAddress" value="127.0.0.1:1111|127.0.0.1:2222|127.0.0.1:3333"/><!--mongdb集群列表-->
    <add key="TimeOut" value="60"/><!--mongdb集群链接超时时间-->
    <!--MongDb配置end-->
  </appSettings>

</configuration>

LogLevel 为自定义 日记级别 ,这个后面看我的代码

LogPath 为日志路径

MongReplicaSetName 为副本集名称,其实就是建立集群的时候取的名字。

MongoServerAddress 为集群机器ip列表,我这里是自己的机器开了不同的端口来区别,你可以改成局域网ip

TimeOut 超时时间,默认貌似是3秒,我这里设置60秒方便调试

链接集群主要代码

 /// <summary>
        /// 取得数据库连接字符串
        /// </summary>
        /// <param name="connName">App.Config文件中AppSettings节中 AppSettings 对应的name</param>
        /// <returns>数据库连接字符串</returns>
        private static MongoServer GetConnStr()
        {
            List<MongoServerAddress> servers = new List<MongoServerAddress>();
            string reg = @"^(?&#39;server&#39;\d{1,}.\d{1,}.\d{1,}.\d{1,}):(?&#39;port&#39;\d{1,})$";
            string[] ServerList = ConfigurationManager.AppSettings["MongoServerAddress"].Trim().Split(&#39;|&#39;);
            foreach (string server in ServerList)
            {
                MatchCollection mc = Regex.Matches(server, reg);
                if (mc != null && mc.Count > 0)
                    servers.Add(new MongoServerAddress(mc[0].Groups["server"].ToString(), Convert.ToInt32(mc[0].Groups["port"].ToString())));
            }

            if (servers == null || servers.Count < 1)
                return null;

            MongoClientSettings set = new MongoClientSettings();

            set.Servers = servers;

            set.ReplicaSetName = ConfigurationManager.AppSettings["MongReplicaSetName"].Trim();//设置副本集名称

            int TimeOut =ConvertUtil.ParseInt(ConfigurationManager.AppSettings["TimeOut"].Trim());//设置副本集名称

            set.ConnectTimeout = new TimeSpan(0, 0, 0, TimeOut, 0);//设置超时时间为5秒

            set.ReadPreference = new ReadPreference(ReadPreferenceMode.SecondaryPreferred);

            MongoClient client = new MongoClient(set);

            return client.GetServer();
        }
set.ReadPreference = new ReadPreference(ReadPreferenceMode.SecondaryPreferred); 这句代码可以根据自己需要修改。

其他没有什么注意的地方

数据插入mongdb代码

    /// <summary>
        /// MongDB 批量insert语句
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="_databaseName">数据库名称</param>
        /// <param name="_collectionName">表名称</param>
        /// <param name="entitys">对象</param>
        /// <param name="errorMsg">返回错误</param>
        /// <returns></returns>
        public static IEnumerable<SafeModeResult> Execute<T>(string _databaseName, string _collectionName, IEnumerable<T> entitys, out string errorMsg)
        {
            errorMsg = string.Empty;
            //取得数据库连接
            IEnumerable<SafeModeResult> result = null;

            try
            {
                if (null == entitys)
                    return null;
                //获取连接的服务器集群
                _server = GetConnStr();

                //获取数据库或者创建数据库(不存在的话)。
                MongoDatabase database = _server.GetDatabase(_databaseName);

                using (_server.RequestStart(database))//开始连接数据库。
                {
                    MongoCollection<T> myCollection = database.GetCollection<T>(_collectionName);
                    result = myCollection.InsertBatch<T>(entitys);
                }
            }
            catch (Exception ex)
            {
                errorMsg = ex.ToString();
            }
            finally
            {
            }

            //记录日志
            if (!string.IsNullOrEmpty(errorMsg))
            {
                LogUtil.Error("CommonLib.DbAccess.MongDBAccess", "Execute", errorMsg + "\n\r\t");
            }

            return result;
        }

读取mongdb数据代码

/// <summary>
        /// 如果不清楚具体的数量,一般不要用这个函数。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        public static List<T> GetAll<T>(string _databaseName, string collectionName,out string errorMsg)
        {
            errorMsg = string.Empty;
            List<T> result = new List<T>();
            try
            {
                //获取连接的服务器集群
                _server = GetConnStr();

                //获取数据库或者创建数据库(不存在的话)。
                MongoDatabase database = _server.GetDatabase(_databaseName);
               
                using (_server.RequestStart(database))//开始连接数据库。
                {
                    MongoCollection<T> myCollection = database.GetCollection<T>(collectionName);
                    result.AddRange(myCollection.FindAll());
                }
            }
            catch (Exception ex )
            {
                errorMsg = ex.ToString();
            }
            //记录日志
            if (!string.IsNullOrEmpty(errorMsg))
            {
                LogUtil.Error("CommonLib.DbAccess.MongDBAccess", "GetAll", errorMsg + "\n\r\t");
            }
            return result;
        } 

以上是插入和读取代码。

后面运行效果如下

\

我这里插入了10w条数据 人然后读取10w条数据。效率比sqlserver是快很多。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
MySQLでビューを使用することの限界は何ですか?MySQLでビューを使用することの限界は何ですか?May 14, 2025 am 12:10 AM

mysqlviewshavelimitations:1)supportallsqloperations、制限、dataManipulationswithjoinsorubqueries.2)それらは、特にパフォーマンス、特にパルフェクソルラージャターセット

MySQLデータベースのセキュリティ:ユーザーの追加と特権の付与MySQLデータベースのセキュリティ:ユーザーの追加と特権の付与May 14, 2025 am 12:09 AM

reperusermanmanagementInmysqliscialforenhancingsecurationsinginuring databaseaperation.1)usecreateusertoaddusers、指定connectionsourcewith@'localhost'or@'% '。

MySQLで使用できるトリガーの数にどのような要因がありますか?MySQLで使用できるトリガーの数にどのような要因がありますか?May 14, 2025 am 12:08 AM

mysqldoes notimposeahardlimitontriggers、しかしpracticalfactorsdeTerminetheireffectiveuse:1)serverconufigurationStriggermanagement; 2)complentiggersincreaseSystemload;

mysql:Blobを保管しても安全ですか?mysql:Blobを保管しても安全ですか?May 14, 2025 am 12:07 AM

はい、それはssafetostoreblobdatainmysql、butonsiderheSeCactors:1)Storagespace:blobscanconsumesificantspace.2)パフォーマンス:パフォーマンス:大規模なドゥエットブロブスメイズ階下3)backupandrecized recized recized recize

MySQL:PHP Webインターフェイスを介してユーザーを追加しますMySQL:PHP Webインターフェイスを介してユーザーを追加しますMay 14, 2025 am 12:04 AM

PHP Webインターフェイスを介してMySQLユーザーを追加すると、MySQLI拡張機能を使用できます。手順は次のとおりです。1。MySQLデータベースに接続し、MySQLI拡張機能を使用します。 2。ユーザーを作成し、CreateUserステートメントを使用し、パスワード()関数を使用してパスワードを暗号化します。 3. SQLインジェクションを防ぎ、MySQLI_REAL_ESCAPE_STRING()関数を使用してユーザー入力を処理します。 4.新しいユーザーに権限を割り当て、助成金ステートメントを使用します。

MySQL:BLOBおよびその他のNO-SQLストレージ、違いは何ですか?MySQL:BLOBおよびその他のNO-SQLストレージ、違いは何ですか?May 13, 2025 am 12:14 AM

mysql'sblobissuitable forstoringbinarydatawithinarationaldatabase、whileenosqloptionslikemongodb、redis、andcassandraofferferulesions forunstructureddata.blobissimplerbutcanslowdowdowd withwithdata

MySQLユーザーの追加:構文、オプション、セキュリティのベストプラクティスMySQLユーザーの追加:構文、オプション、セキュリティのベストプラクティスMay 13, 2025 am 12:12 AM

toaddauserinmysql、使用:createuser'username '@' host'identifidedby'password '; here'showtodoitsely:1)chosehostcarefilytoconを選択しますTrolaccess.2)setResourcelimitslikemax_queries_per_hour.3)usestrong、uniquasswords.4)endforcessl/tlsconnectionswith

MySQL:文字列データ型の一般的な間違いを回避する方法MySQL:文字列データ型の一般的な間違いを回避する方法May 13, 2025 am 12:09 AM

toavoidcommonMonmistakeswithStringDatatypesinmysql、undultingStringTypenuste、choosetherightType、andManageEncodingandCollat​​ionsEttingtingive.1)U​​secharforfixed-LengthStrings、Varcharforaible Length、AndText/Blobforlardata.2)setCurrectCherts

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、