search

读书笔记 C# Driver 之前看了Bson类库,现在学习C# Driver Thread safety(多线程问题) 只有少部分的C# Driver类是多线程安全的。比如MongoClient,MongoServer,MongoDatabase, MongoCollection 以及MongoGridFS。一般常用的类存在多线程问题,包括MongoCurs

读书笔记

C# Driver

之前看了Bson类库,现在学习C# Driver

Thread safety(多线程问题)

只有少部分的C# Driver类是多线程安全的。比如MongoClient,MongoServer,MongoDatabase, MongoCollection 以及MongoGridFS。一般常用的类存在多线程问题,包括MongoCursor以及Bson类库中的所有类(除了其中的BsonSymbolTable是线程安全的)。

所有的类的静态属性值和函数方法都不会引起多线程问题。

MongoClient类

这个类提供使用MongoDB server的基本对象。与MongoDB server服务进行链接的时候,client自动进行连接。(使用了连接池来进行更有效的连接)

在连接一个副本集的时候,有且只用一个MongoClient实例。

When you are connecting to a replica set you will still use only one instance of MongoClient, which represents the replica set as a whole. The driver automatically finds all the members of the replica set and identifies the current primary.

这个类的实例不会引起多线程问题。

除非其他设置,在默认设置情况下,所有操作需要一个WriteConcern,一个写入确定语句。另外,默认情况下,所有的写操作会锁定,直到server知道要进行写操作。

Connection strings

最简单的数据库连接是使用Connection string。标准的Connection string如下:

mongodb://[username:password@]hostname[:port][/[database][?options]]

在使用认证的mongodb服务器上,username和password必须填写。

port号码是可选的。默认的是27017.

如果要连接多个服务器,可以直接填写多个服务器名(以及需要的端口号),并且以‘,’分割。如下:

mongodb://server1,server2:27017,server2:27018

上面这段connection string 连接了三个数据库服务,由于多数据库服务是模糊不清的,不能分辨服务是否复本集,或者是多数据库服务。drive驱动会跳过connection string的语法检查,直接连接进数据库服务器,让server自己检查他们的类别。还有一些办法在连接的时候就指定数据服务器的类别,就是在connection string里面直接描述。如下:

mongodb://server1,server2:27017,server2:27018/?connect=replicaset

可用的连接模式包括:automatic (默认), direct, replica set, 以及shardrouter。连接的规则如下:

1、如果指定了某种连接模式,则直接使用否则使用默认的automatic。

2、如果在connection string中有replica set name,则使用replica set模式

3、如果connection string中仅有一个服务器,则使用direct模式

4、另外,连接服务之后,服务决定连接的模式

注意:如果有多服务器列表连接,其中有一个是复本集的一个,而其他不是,则连接模式将成为non-deterministic(未决定)。确定connection string中没有混合服务类型。

当连接模式指定成为replica set,美国服务器,但是driver接口还是会找到primary服务器,即使该服务器不在connection连接列表中。直到connection列表中的一个服务器的回应(这个回应包括replica set以及现有的primary服务)。另外,即使在初始化语句完成之后,其他次级服务器也会被发现,并且自动加入到混合集群。这样,香港服务器,如果你有添加以及删除,移动replica set,driver接口会自己处理这些改变。

顺便提到,假设你想要直接连接入一个replica set并且无论它是否是现在的primary(也许只是想监控下它的运行状态或者进行只读语句),可以使用下面连接语句:

mongodb://server2/?connect=direct;readpreference=nearest

可以在下面的链接获取比较齐全的connection string文档

更加深入地额:

SSL Support

这些不感兴趣,大概是driver连接的一个设置

通过在connection string里面加入“ssl=true”选项来设置

mongodb://server2/?ssl=true

在默认的情况下,server是通过本地的受信任的证书机构获取许可。在一些测试环境下面,测试server没有签署证书,为了缓解这个情况,香港虚拟主机,可以使用在connection string里面添加“sslverifycertificate=false”来屏蔽所有certificate errors(认证错误)。

Authentication

MongoDB支持两种认证方式。一种是在程序执行时,调用特定的方法。在执行特定的方法时,认证将会被使用。另外一种健壮的方法是在MongoCredentialsStore存储认证信息。

下面是一个例子,使用credential store来确定admin和“foo”数据库的认证信息。除了使用“admin”以及“foo”连接入数据库,还可以使用默认的认证“test”。

var url = new MongoUrl("mongodb://test:user@localhost:27017"); var settings = MongoClientSettings.FromUrl(url); var adminCredentials = new MongoCredentials("admin", "user", true); settings.CredentialsStore.Add("admin", adminCredentials); var fooCredentials = new MongoCredentials("foo", "user", false); settings.CredentialsStore.Add("foo", fooCredentials); var client = new MongoClient(settings); 我感觉类似SQL语句: foo.* ; GetServer method 在MongoClient实例中调用GetServer方法获取MongoServer的实例。   MongoServer class  

使用MongoServer类可以进行更多的控制操作。它使用了先进的技术通过一个单个的socket获取数据库以及进行一系列的数据库操作,并且保持数据库的一致性。

GetDatabase method

通过这个方法访问数据库

例子代码:

MongoClient client = new MongoClient(); // connect to localhost MongoServer server = client.GetServer(); MongoDatabase test = server.GetDatabase("test"); MongoCredentials credentials = new MongoCredentials("username", "password"); MongoDatabase salaries = server.GetDatabase("salaries", credentials);
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools