목차
Introduction
Sample Program
Conclusion
데이터 베이스 MySQL 튜토리얼 Running MongoDB Queries Concurrently With Go

Running MongoDB Queries Concurrently With Go

Jun 07, 2016 pm 04:34 PM
mongodb running

This is a guest post by William Kennedy, managing partner at Ardan Studios in Miami, FL, a mobile and web app development company. Bill is also the author of the blog GoingGo.Net and the organizer for the Go-Miami and Miami MongoDB meetups

This is a guest post by William Kennedy, managing partner at Ardan Studios in Miami, FL, a mobile and web app development company. Bill is also the author of the blog GoingGo.Net and the organizer for the Go-Miami and Miami MongoDB meetups in Miami. Bill looked for a new language in 2013 that would allow him to develop back end systems in Linux and found Go. He has never looked back.

If you are attending GopherCon 2014 or plan to watch the videos once they are released, this article will prepare you for the talk by Gustavo Niemeyer and Steve Francia. It provides a beginners view for using the Go mgo driver against a MongoDB database.

Introduction

MongoDB supports many different programming languages thanks to a great set of drivers. One such driver is the MongoDB Go driver which is called mgo. This driver was developed by Gustavo Niemeyer from Canonical with some assistance from MongoDB Inc. Both Gustavo and Steve Francia, the head of the drivers team, will be talking at GopherCon 2014 in April about “Painless Data Storage With MongoDB and Go”. The talk describes the mgo driver and how MongoDB and Go work well together for building highly scalable and concurrent software.

MongoDB and Go let you build scalable software on many different operating systems and architectures, without the need to install frameworks or runtime environments. Go programs are native binaries and the Go tooling is constantly improving to create binaries that run as fast as equivalent C programs. That wouldn’t mean anything if writing code in Go was complicated and as tedious as writing programs in C. This is where Go really shines because once you get up to speed, writing programs in Go is fast and fun.

In this post I am going to show you how to write a Go program using the mgo driver to connect and run queries concurrently against a MongoDB database. I will break down the sample code and explain a few things that can be a bit confusing to those new to using MongoDB and Go together.

Sample Program

The sample program connects to a public MongoDB database I have hosted with MongoLab. If you have Go and Bazaar installed on your machine, you can run the program against my database. The program is very simple - it launches ten goroutines that individually query all the records from the buoy_stations collection inside the goinggo database. The records are unmarshaled into native Go types and each goroutine logs the number of documents returned:

Now that you have seen the entire program, we can break it down. Let’s start with the type structures that are defined in the beginning:

The structures represent the data that we are going to retrieve and unmarshal from our query. BuoyStation represents the main document and BuoyCondition and BuoyLocation are embedded documents. The mgo driver makes it easy to use native types that represent the documents stored in our collections by using tags. With the tags, we can control how the mgo driver unmarshals the returned documents into our native Go structures.

Now let’s look at how we connect to a MongoDB database using mgo:

We start with creating a mgo.DialInfo object. Connecting to a replica set can be accomplished by providing multiple addresses in the Addrs field or with a single address. If we are using a single host address to connect to a replica set, the mgo driver will learn about any remaining hosts from the replica set member we connect to. In our case we are connecting to a single host.

After providing the host, we specify the database, username and password we need for authentication. One thing to note is that the database we authenticate against may not necessarily be the database our application needs to access. Some applications authenticate against the admin database and then use other databases depending on their configuration. The mgo driver supports these types of configurations very well.

Next we use the mgo.DialWithInfo method to create a mgo.Session object. Each session specifies a Strong or Monotonic mode, and other settings such as write concern and read preference. The mgo.Session object maintains a pool of connections to MongoDB. We can create multiple sessions with different modes and settings to support different aspects of our applications.

The next line of code sets the mode for the session. There are three modes that can be set, Strong, Monotonic and Eventual. Each mode sets a specific consistency for how reads and writes are performed. For more information on the differences between each mode, check out the documentation for the mgo driver.

We are using Monotonic mode which provides reads that may not entirely be up to date, but the reads will always see the history of changes moving forward. In this mode reads occur against secondary members of our replica sets until a write happens. Once a write happens, the primary member is used. The benefit is some distribution of the reading load can take place against the secondaries when possible.

With the session set and ready to go, next we execute multiple queries concurrently:

This code is classic Go concurrency in action. First we create a sync.WaitGroup object so we can keep track of all the goroutines we are going to launch as they complete their work. Then we immediately set the count of the sync.WaitGroup object to ten and use a for loop to launch ten goroutines using the RunQuery function. The keyword go is used to launch a function or method to run concurrently. The final line of code calls the Wait method on the sync.WaitGroup object which locks the main goroutine until everything is done processing.

To learn more about Go concurrency and better understand how this particular piece of code works, check out these posts on concurrency and channels.

Now let’s look at the RunQuery function and see how to properly use the mgo.Session object to acquire a connection and execute a query:

The very first thing we do inside of the RunQuery function is to defer the execution of the Done method on the sync.WaitGroup object. The defer keyword will postpone the execution of the Done method, to take place once the RunQuery function returns. This will guarantee that the sync.WaitGroup objects count will decrement even if an unhandled exception occurs.

Next we make a copy of the session we created in the main goroutine. Each goroutine needs to create a copy of the session so they each obtain their own socket without serializing their calls with the other goroutines. Again, we use the defer keyword to postpone and guarantee the execution of the Close method on the session once the RunQuery function returns. Closing the session returns the socket back to the main pool, so this is very important.

To execute a query we need a mgo.Collection object. We can get a mgo.Collection object through the mgo.Session object by specifying the name of the database and then the collection. Using the mgo.Collection object, we can perform a Find and retrieve all the documents from the collection. The All function will unmarshal the response into our slice of BuoyStation objects. A slice is a dynamic array in Go. Be aware that the All method will load all the data in memory at once. For large collections it is better to use the Iter method instead. Finally, we just log the number of BuoyStation objects that are returned.

Conclusion

The example shows how to use Go concurrency to launch multiple goroutines that can execute queries against a MongoDB database independently. Once a session is established, the mgo driver exposes all of the MongoDB functionality and handles the unmarshaling of BSON documents into Go native types.

MongoDB can handle a large number of concurrent requests when you architect your MongoDB databases and collections with concurrency in mind. Go and the mgo driver are perfectly aligned to push MongoDB to its limits and build software that can take advantage of all the computing power that is available.

The mgo driver provides a safe way to leverage Go’s concurrency support and you have the flexibility to execute queries concurrently and in parallel. It is best to take the time to learn a bit about MongoDB replica sets and load balancer configuration. Then make sure the load balancer is behaving as expected under the different types of load your application can produce.

Now is a great time to see what MongoDB and Go can do for your software applications, web services and service platforms. Both technologies are being battle tested everyday by all types of companies, solving all types of business and computing problems.

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 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 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

navicat이 만료되면 어떻게 해야 할까요? navicat이 만료되면 어떻게 해야 할까요? Apr 23, 2024 pm 12:12 PM

Navicat 만료 문제를 해결하는 방법은 다음과 같습니다: 라이센스 갱신, 자동 업데이트 비활성화, Navicat 고객 지원에 문의하세요.

프론트엔드에서 nodejs를 배우기가 어렵나요? 프론트엔드에서 nodejs를 배우기가 어렵나요? Apr 21, 2024 am 04:57 AM

프런트엔드 개발자의 경우 Node.js 학습의 어려움은 JavaScript 기초, 서버 측 프로그래밍 경험, 명령줄 익숙함, 학습 스타일에 따라 다릅니다. 학습 곡선에는 기본 개념, 서버 측 아키텍처, 데이터베이스 통합 및 비동기 프로그래밍에 중점을 둔 초급 수준 및 고급 수준 모듈이 포함됩니다. 전반적으로, JavaScript에 탄탄한 기초가 있고 시간과 노력을 투자할 의향이 있는 개발자에게는 Node.js를 배우는 것이 어렵지 않지만 관련 경험이 부족한 개발자에게는 극복해야 할 특정 과제가 있을 수 있습니다.

Navicat을 mongodb에 연결하는 방법 Navicat을 mongodb에 연결하는 방법 Apr 24, 2024 am 11:27 AM

Navicat을 사용하여 MongoDB에 연결하려면 다음을 수행해야 합니다: Navicat 설치 MongoDB 연결 생성: a. 연결 이름, 호스트 주소 및 포트를 입력합니다. b. 인증 정보를 입력합니다(필요한 경우). SSL 인증서를 추가합니다(필요한 경우). 연결 저장

nodejs에서 일반적으로 사용되는 모듈은 무엇입니까? nodejs에서 일반적으로 사용되는 모듈은 무엇입니까? Apr 21, 2024 am 04:34 AM

Node.js에서 가장 일반적으로 사용되는 모듈은 다음과 같습니다. 파일 작업을 위한 파일 시스템 모듈 네트워크 통신을 위한 네트워크 모듈 데이터 스트림 처리를 위한 스트림 모듈 데이터베이스와 상호 작용하기 위한 데이터베이스 모듈 암호화, 쿼리 문자열과 같은 기타 유틸리티 모듈 문자열 구문 분석 및 HTTP 프레임워크

net4.0의 용도는 무엇입니까 net4.0의 용도는 무엇입니까 May 10, 2024 am 01:09 AM

.NET 4.0은 다양한 애플리케이션을 만드는 데 사용되며 객체 지향 프로그래밍, 유연성, 강력한 아키텍처, 클라우드 컴퓨팅 통합, 성능 최적화, 광범위한 라이브러리, 보안, 확장성, 데이터 액세스 및 모바일을 포함한 풍부한 기능을 애플리케이션 개발자에게 제공합니다. 개발 지원.

nodejs에는 어떤 데이터베이스가 좋은가요? nodejs에는 어떤 데이터베이스가 좋은가요? Apr 21, 2024 am 05:06 AM

Node.js 애플리케이션의 경우 데이터베이스 선택은 애플리케이션 요구 사항에 따라 다릅니다. NoSQL 데이터베이스 MongoDB는 유연성을 제공하고, Redis는 높은 동시성을 제공하며, Cassandra는 시계열 데이터를 처리하고, Elasticsearch는 검색 전용입니다. SQL 데이터베이스 MySQL은 뛰어난 성능을 갖고 있고, PostgreSQL은 기능이 풍부하며, SQLite는 가볍고, Oracle 데이터베이스는 포괄적입니다. 선택할 때 데이터 유형, 쿼리, 성능, 트랜잭션성, 가용성, 라이센스 및 비용을 고려하십시오.

nodejs를 데이터베이스에 연결하는 방법 nodejs를 데이터베이스에 연결하는 방법 Apr 21, 2024 am 05:07 AM

Node.js에서 데이터베이스에 연결하는 단계: MySQL, MongoDB 또는 PostgreSQL 패키지를 설치합니다. 데이터베이스 연결 개체를 만듭니다. 데이터베이스 연결을 열고 연결 오류를 처리합니다.

nodejs가 데이터베이스를 구현하는 방법 nodejs가 데이터베이스를 구현하는 방법 Apr 21, 2024 am 05:42 AM

Node.js에서 데이터베이스에 연결하려면 데이터베이스 시스템(관계형 또는 비관계형)을 선택한 다음 해당 유형에 특정한 모듈을 사용하여 연결을 설정해야 합니다. 일반적인 모듈에는 mysql(MySQL), pg(PostgreSQL), mongodb(MongoDB) 및 redis(Redis)가 포함됩니다. 연결이 설정된 후 쿼리 문을 사용하여 데이터를 검색하고 문을 업데이트하여 데이터를 수정할 수 있습니다. 마지막으로 리소스를 해제하려면 모든 작업이 완료되면 연결을 닫아야 합니다. 연결 풀링, 매개변수화된 쿼리 사용, 오류 처리 등 모범 사례를 따르면 성능과 보안이 향상됩니다.

See all articles