使用 Azure Cosmos 模擬器進行本機開發和測試Use the Azure Cosmos Emulator for local development and testing

Azure Cosmos 模擬器提供一個模擬 Azure Cosmos DB 服務的本機環境做為開發之用。The Azure Cosmos Emulator provides a local environment that emulates the Azure Cosmos DB service for development purposes. 您可以使用 Azure Cosmos 模擬器在本機開發及測試應用程式,不需建立 Azure 訂用帳戶,也不會產生任何費用。Using the Azure Cosmos Emulator, you can develop and test your application locally, without creating an Azure subscription or incurring any costs. 如果您滿意應用程式在 Azure Cosmos 模擬器中的運作方式,就可以切換成使用雲端的 Azure Cosmos 帳戶。When you're satisfied with how your application is working in the Azure Cosmos Emulator, you can switch to using an Azure Cosmos account in the cloud.

您可以搭配 SQLCassandraMongoDBGremlin資料表 API 帳戶使用 Azure Cosmos 模擬器進行開發。You can develop using Azure Cosmos Emulator with SQL, Cassandra, MongoDB, Gremlin, and Table API accounts. 不過,模擬器中的 [資料總管] 檢視目前僅完全支援 SQL API 的用戶端。However at this time the Data Explorer view in the emulator fully supports clients for SQL API only.

模擬器的運作方式How the emulator works

Azure Cosmos 模擬器提供 Azure Cosmos DB 服務的高逼真度模擬。The Azure Cosmos Emulator provides a high-fidelity emulation of the Azure Cosmos DB service. 它支援與 Azure Cosmos DB 完全相同的功能,包括支援建立和查詢資料、佈建和調整容器,以及執行預存程序和觸發程序。It supports identical functionality as Azure Cosmos DB, including support for creating and querying data, provisioning and scaling containers, and executing stored procedures and triggers. 您可以使用 Azure Cosmos 模擬器來開發及測試應用程式,並且只需對 Azure Cosmos DB 的連接端點進行單一設定變更,就能將應用程式部署到範圍遍及全球的 Azure。You can develop and test applications using the Azure Cosmos Emulator, and deploy them to Azure at global scale by just making a single configuration change to the connection endpoint for Azure Cosmos DB.

雖然 Azure Cosmos DB 服務的模擬很可靠,但模擬器的實作會與服務有所不同。While emulation of the Azure Cosmos DB service is faithful, the emulator's implementation is different than the service. 例如,模擬器會使用標準的作業系統元件,比如使用本機檔案系統以獲得持續性,以及使用 HTTPS 通訊協定堆疊進行連線。For example, the emulator uses standard OS components such as the local file system for persistence, and the HTTPS protocol stack for connectivity. 依賴 Azure 基礎結構的功能 (例如全域複寫、讀取/寫入的個位數毫秒延遲,以及可調整的一致性層級) 均不適用。Functionality that relies on Azure infrastructure like global replication, single-digit millisecond latency for reads/writes, and tunable consistency levels are not applicable.

您可以使用 Azure Cosmos DB 資料移轉工具 (英文),在 Azure Cosmos 模擬器與 Azure Cosmos DB 服務之間移轉資料。You can migrate data between the Azure Cosmos Emulator and the Azure Cosmos DB service by using the Azure Cosmos DB Data Migration Tool.

您可以在 Windows Docker 容器上執行 Azure Cosmos 模擬器,請參閱 Docker Hub (英文) 以了解 docker pull 命令,以及 GitHub (英文) 以了解模擬器來源程式碼。You can run Azure Cosmos Emulator on the Windows Docker container, see the Docker Hub for the docker pull command and GitHub for the emulator source code.

模擬器和服務之間的差異Differences between the emulator and the service

因為 Azure Cosmos 模擬器提供一個在本機開發人員工作站上執行的模擬環境,所以在模擬器和雲端 Azure Cosmos 帳戶之間有一些功能上的差異:Because the Azure Cosmos Emulator provides an emulated environment running on the local developer workstation, there are some differences in functionality between the emulator and an Azure Cosmos account in the cloud:

  • 模擬器中的 [資料總管] 目前支援 SQL API 的用戶端。Currently Data Explorer in the emulator supports clients for SQL API. [資料總管] 檢視和適用於 Azure Cosmos DB API (例如 MongoDB、資料表、圖表及 Cassandra API) 的作業並未受到完全支援。The Data Explorer view and operations for Azure Cosmos DB APIs such as MongoDB, Table, Graph, and Cassandra APIs are not fully supported.
  • Azure Cosmos 模擬器僅支援單一固定帳戶及一個已知的主要金鑰。The Azure Cosmos Emulator supports only a single fixed account and a well-known master key. Azure Cosmos 模擬器中無法重新產生金鑰,但您可以使用命令列選項來變更預設金鑰。Key regeneration is not possible in the Azure Cosmos Emulator, however the default key can be changed using the command-line option.
  • Azure Cosmos 模擬器是一項無法擴充的服務,也不支援大量容器。The Azure Cosmos Emulator is not a scalable service and will not support a large number of containers.
  • Azure Cosmos 模擬器未提供不同的 Azure Cosmos DB 一致性層級The Azure Cosmos Emulator does not offer different Azure Cosmos DB consistency levels.
  • Azure Cosmos 模擬器未提供多重區域複寫The Azure Cosmos Emulator does not offer multi-region replication.
  • 因為 Azure Cosmos DB 服務最新的變更,您的 Azure Cosmos 模擬器複本可能不會一直是最新狀態,您應該參閱 Azure Cosmos DB 容量規劃工具 (英文),準確地評估應用程式的生產輸送量 (RU) 需求。As your copy of the Azure Cosmos Emulator might not always be up-to-date with the most recent changes in the Azure Cosmos DB service, you should refer to the Azure Cosmos DB capacity planner to accurately estimate the production throughput (RUs) needs of your application.
  • 使用 Azure Cosmos 模擬器時,根據預設,您最多可以建立 25 個固定大小的容器 (僅支援使用 Azure Cosmos DB SDK),或者,使用 Azure Cosmos 模擬器來建立 5 個無限制的容器。When using the Azure Cosmos Emulator, by default, you can create up to 25 fixed size containers (only supported using Azure Cosmos DB SDKs), or 5 unlimited containers using the Azure Cosmos Emulator. 如需變更此值的詳細資訊,請參閱設定 PartitionCount 值For more information about changing this value, see Setting the PartitionCount value.

系統需求System requirements

Azure Cosmos 模擬器的硬體和軟體需求如下:The Azure Cosmos Emulator has the following hardware and software requirements:

  • 軟體需求Software requirements
    • Windows Server 2012 R2、Windows Server 2016 或 Windows 10Windows Server 2012 R2, Windows Server 2016, or Windows 10
    • 64 位元作業系統64-bit operating system
  • 最低硬體需求Minimum Hardware requirements
    • 2-GB RAM2-GB RAM
    • 10-GB 可用硬碟空間10-GB available hard disk space

安裝Installation

您可以從 Microsoft 下載中心下載並安裝 Azure Cosmos 模擬器,或在適用於 Windows 的 Docker 上執行模擬器。You can download and install the Azure Cosmos Emulator from the Microsoft Download Center or you can run the emulator on Docker for Windows. 如需在適用於 Window 的 Docker 使用模擬器的指示,請參閱在 Docker 上執行For instructions on using the emulator on Docker for Windows, see Running on Docker.

注意

若要安裝、設定和執行 Azure Cosmos 模擬器,您必須具備電腦的系統管理權限。To install, configure, and run the Azure Cosmos Emulator, you must have administrative privileges on the computer. 模擬器將建立/新增憑證,也會設定防火牆規則以便執行其服務;因此,模擬器必須能夠執行這類作業。The emulator will create/add a certificate and also set the firewall rules in order to run its services; therefore it's necessary for the emulator to be able to execute such operations.

在 Windows 上執行Running on Windows

若要啟動 Azure Cosmos 模擬器,請選取 [開始] 按鈕或按下 Windows 鍵。To start the Azure Cosmos Emulator, select the Start button or press the Windows key. 開始輸入 Azure Cosmos 模擬器,然後從應用程式清單中選取模擬器。Begin typing Azure Cosmos Emulator, and select the emulator from the list of applications.

選取 [開始] 按鈕或按下 Windows 鍵,開始輸入 Azure Cosmos 模擬器,然後從應用程式清單中選取模擬器

如果模擬器正在執行,您就會在 Windows 工作列通知區域看到圖示。When the emulator is running, you'll see an icon in the Windows taskbar notification area. Azure Cosmos DB 本機模擬器的工作列通知

Azure Cosmos 模擬器預設會在連接埠 8081 上接聽的本機電腦 ("localhost") 上執行。The Azure Cosmos Emulator by default runs on the local machine ("localhost") listening on port 8081.

Azure Cosmos 模擬器預設會安裝到 C:\Program Files\Azure Cosmos DB EmulatorThe Azure Cosmos Emulator is installed to C:\Program Files\Azure Cosmos DB Emulator by default. 您也可以從命令列啟動和停止模擬器。You can also start and stop the emulator from the command-line. 如需詳細資訊,請參閱命令列工具參考For more information, see the command-line tool reference.

啟動資料總管Start Data Explorer

當 Azure Cosmos 模擬器啟動時,會自動在瀏覽器中開啟 Azure Cosmos 資料總管。When the Azure Cosmos Emulator launches, it automatically opens the Azure Cosmos Data Explorer in your browser. 位址會顯示為 https://localhost:8081/_explorer/index.htmlThe address appears as https://localhost:8081/_explorer/index.html. 如果您關閉資料總管且想要稍後重新開啟,可以在瀏覽器中開啟 URL,或從 Windows 系統匣圖示中的 Azure Cosmos 模擬器啟動它,如下所示。If you close the explorer and would like to reopen it later, you can either open the URL in your browser or launch it from the Azure Cosmos Emulator in the Windows Tray Icon as shown below.

Azure Cosmos 本機模擬器的資料總管啟動程式

檢查更新Checking for updates

資料總管會表示是否有新的更新可供下載。Data Explorer indicates if there is a new update available for download.

注意

在某個 Azure Cosmos 模擬器版本 (請參閱 %LOCALAPPDATA%\CosmosDBEmulator 或資料路徑選擇性設定) 中建立的資料,不保證可使用不同的版本加以存取。Data created in one version of the Azure Cosmos Emulator (see %LOCALAPPDATA%\CosmosDBEmulator or data path optional settings) is not guaranteed to be accessible when using a different version. 如果您需要長期保存資料,建議您將資料儲存於 Azure Cosmos 帳戶,而不是 Azure Cosmos 模擬器。If you need to persist your data for the long term, it is recommended that you store that data in an Azure Cosmos account, rather than in the Azure Cosmos Emulator.

驗證要求Authenticating requests

就像雲端的 Azure Cosmos DB 一樣,您對 Azure Cosmos 模擬器所做的每個要求都必須經過驗證。As with Azure Cosmos DB in the cloud, every request that you make against the Azure Cosmos Emulator must be authenticated. Azure Cosmos 模擬器支援使用單一固定帳戶及一個已知的驗證金鑰來進行主要金鑰驗證。The Azure Cosmos Emulator supports a single fixed account and a well-known authentication key for master key authentication. 此帳戶和金鑰都是唯一允許搭配 Azure Cosmos 模擬器使用的認證,This account and key are the only credentials permitted for use with the Azure Cosmos Emulator. 如下:They are:

Account name: localhost:<port>
Account key: C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==

注意

Azure Cosmos 模擬器所支援的主要金鑰僅能與模擬器搭配使用。The master key supported by the Azure Cosmos Emulator is intended for use only with the emulator. 您無法將生產用的 Azure Cosmos DB 帳戶和金鑰與 Azure Cosmos 模擬器搭配使用。You cannot use your production Azure Cosmos DB account and key with the Azure Cosmos Emulator.

注意

如果您使用 /Key 選項來啟動模擬器,則使用產生的金鑰,而非 C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==If you have started the emulator with the /Key option, then use the generated key instead of C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==. 如需 /Key 選項的詳細資訊,請參閱命令列工具參考For more information about /Key option, see Command-line tool reference.

就像 Azure Cosmos DB 一樣,Azure Cosmos 模擬器僅支援透過 SSL 的安全通訊。As with the Azure Cosmos DB, the Azure Cosmos Emulator supports only secure communication via SSL.

在區域網路上執行Running on a local network

您可以在本機網路上執行模擬器。You can run the emulator on a local network. 若要啟用網路存取,請在命令列上指定 /AllowNetworkAccess 選項,這也需要您指定 /Key=key_string/KeyFile=file_nameTo enable network access, specify the /AllowNetworkAccess option at the command-line, which also requires that you specify /Key=key_string or /KeyFile=file_name. 您可以使用 /GenKeyFile=file_name,預先產生具有隨機金鑰的檔案。You can use /GenKeyFile=file_name to generate a file with a random key upfront. 然後可將該檔案傳遞至 /KeyFile=file_name/Key=contents_of_fileThen you can pass that to /KeyFile=file_name or /Key=contents_of_file.

若是第一次啟用網路存取,使用者應該關閉模擬器,並刪除模擬器的資料目錄 (%LOCALAPPDATA%\CosmosDBEmulator)。To enable network access for the first time the user should shut down the emulator and delete the emulator’s data directory (%LOCALAPPDATA%\CosmosDBEmulator).

使用模擬器進行開發Developing with the emulator

SQL APISQL API

在桌面上執行 Azure Cosmos 模擬器之後,就可以使用任何支援的 Azure Cosmos DB SDKAzure Cosmos DB REST API 來與模擬器互動。Once you have the Azure Cosmos Emulator running on your desktop, you can use any supported Azure Cosmos DB SDK or the Azure Cosmos DB REST API to interact with the emulator. Azure Cosmos 模擬器也包含內建的資料總管,可讓您建立 SQL API 或適用於 Mongo DB API 的 Cosmos DB 的容器,並檢視及編輯項目,而不需撰寫任何程式碼。The Azure Cosmos Emulator also includes a built-in Data Explorer that lets you create containers for SQL API or Cosmos DB for Mongo DB API, and view and edit items without writing any code.

// Connect to the Azure Cosmos Emulator running locally
DocumentClient client = new DocumentClient(
   new Uri("https://localhost:8081"), "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");

適用於 MongoDB 的 Azure Cosmos DB APIAzure Cosmos DB's API for MongoDB

在桌面上執行 Azure Cosmos 模擬器之後,就可以使用適用於 MongoDB 的 Azure Cosmos DB API 來與模擬器互動。Once you have the Azure Cosmos Emulator running on your desktop, you can use the Azure Cosmos DB's API for MongoDB to interact with the emulator. 從命令提示字元中,以系統管理員身分使用 "/EnableMongoDbEndpoint" 來啟動模擬器。Start emulator from command prompt as an administrator with "/EnableMongoDbEndpoint". 然後使用下列連接字串來連線至 MongoDB API 帳戶:Then use the following connection string to connect to the MongoDB API account:

mongodb://localhost:C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==@localhost:10255/admin?ssl=true

資料表 APITable API

在桌面上執行 Azure Cosmos 模擬器之後,就可以使用 Azure Cosmos DB 資料表 API SDK 來與模擬器互動。Once you have the Azure Cosmos Emulator running on your desktop, you can use the Azure Cosmos DB Table API SDK to interact with the emulator. 從命令提示字元中,以系統管理員身分使用 "/EnableTableEndpoint" 來啟動模擬器。Start emulator from command prompt as an administrator with “/EnableTableEndpoint”. 接著,執行下列程式碼以連線到資料表 API 帳戶:Next run the following code to connect to the table API account:

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using CloudTable = Microsoft.WindowsAzure.Storage.Table.CloudTable;
using CloudTableClient = Microsoft.WindowsAzure.Storage.Table.CloudTableClient;

string connectionString = "DefaultEndpointsProtocol=http;AccountName=localhost;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==;TableEndpoint=http://localhost:8902/;";

CloudStorageAccount account = CloudStorageAccount.Parse(connectionString);
CloudTableClient tableClient = account.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("testtable");
table.CreateIfNotExists();
table.Execute(TableOperation.Insert(new DynamicTableEntity("partitionKey", "rowKey")));

Cassandra APICassandra API

從系統管理員的命令提示字元中,使用 "/EnableCassandraEndpoint" 來啟動模擬器。Start emulator from an administrator command prompt with “/EnableCassandraEndpoint”. 或者,您也可以設定環境變數 AZURE_COSMOS_EMULATOR_CASSANDRA_ENDPOINT=trueAlternatively you can also set the environment variable AZURE_COSMOS_EMULATOR_CASSANDRA_ENDPOINT=true.

  • 安裝 Python 2.7Install Python 2.7

  • 安裝 Cassandra CLI/CQLSHInstall Cassandra CLI/CQLSH

  • 在一般命令提示字元視窗中,執行下列命令:Run the following commands in a regular command prompt window:

    set Path=c:\Python27;%Path%
    cd /d C:\sdk\apache-cassandra-3.11.3\bin
    set SSL_VERSION=TLSv1_2
    set SSL_VALIDATE=false
    cqlsh localhost 10350 -u localhost -p C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw== --ssl
    
  • 在 CQLSH 殼層中,執行下列命令以連線到 Cassandra 端點:In the CQLSH shell, run the following commands to connect to the Cassandra endpoint:

    CREATE KEYSPACE MyKeySpace WITH replication = {'class':'MyClass', 'replication_factor': 1};
    DESCRIBE keyspaces;
    USE mykeyspace;
    CREATE table table1(my_id int PRIMARY KEY, my_name text, my_desc text);
    INSERT into table1 (my_id, my_name, my_desc) values( 1, 'name1', 'description 1');
    SELECT * from table1;
    EXIT
    

Gremlin APIGremlin API

從系統管理員的命令提示字元中,使用 "/EnableGremlinEndpoint" 來啟動模擬器。Start emulator from an administrator command prompt with “/EnableGremlinEndpoint”. 或者,您也可以設定環境變數 AZURE_COSMOS_EMULATOR_GREMLIN_ENDPOINT=trueAlternatively you can also set the environment variable AZURE_COSMOS_EMULATOR_GREMLIN_ENDPOINT=true

  • 安裝 apache-tinkerpop-gremlin-console-3.3.4Install apache-tinkerpop-gremlin-console-3.3.4

  • 在模擬器的 [資料總管] 中,建立資料庫 "db1" 和集合 "coll1";針對分割區索引鍵,選擇 "/name"In the emulator’s Data Explorer create a database "db1" and a collection "coll1"; for the partition key, choose "/name"

  • 在一般命令提示字元視窗中,執行下列命令:Run the following commands in a regular command prompt window:

    cd /d C:\sdk\apache-tinkerpop-gremlin-console-3.3.4-bin\apache-tinkerpop-gremlin-console-3.3.4
    
    copy /y conf\remote.yaml conf\remote-localcompute.yaml
    notepad.exe conf\remote-localcompute.yaml
      hosts: [localhost]
      port: 8901
      username: /dbs/db1/colls/coll1
      password: C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==
      connectionPool: {
      enableSsl: false}
      serializer: { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV1d0,
      config: { serializeResultToString: true  }}
    
    bin\gremlin.bat
    
  • 在 Gremlin 殼層中,執行下列命令以連線到 Gremlin 端點:In the Gremlin shell run the following commands to connect to the Gremlin endpoint:

    :remote connect tinkerpop.server conf/remote-localcompute.yaml
    :remote console
    :> g.V()
    :> g.addV('person1').property(id, '1').property('name', 'somename1')
    :> g.addV('person2').property(id, '2').property('name', 'somename2')
    :> g.V()
    

匯出 SSL 憑證Export the SSL certificate

.NET 語言和執行階段使用 Windows 憑證存放區來安全地連線到 Azure Cosmos DB 本機模擬器。.NET languages and runtime use the Windows Certificate Store to securely connect to the Azure Cosmos DB local emulator. 其他語言則有自己管理和使用憑證的方法。Other languages have their own method of managing and using certificates. Java 使用自己的憑證存放區,而 Python 使用通訊端包裝函式Java uses its own certificate store whereas Python uses socket wrappers.

若要取得憑證來搭配未整合 Windows 憑證存放區的語言和執行階段使用,您必須使用 Windows 憑證管理員將它匯出。In order to obtain a certificate to use with languages and runtimes that do not integrate with the Windows Certificate Store, you will need to export it using the Windows Certificate Manager. 您可以執行 certlm.msc 或依照匯出 Azure Cosmos 模擬器憑證中的逐步指示來啟動它。You can start it by running certlm.msc or follow the step by step instructions in Export the Azure Cosmos Emulator Certificates. 憑證管理員執行之後時,開啟 [個人憑證] (如下所示),並將有 "DocumentDBEmulatorCertificate" 易記名稱的憑證匯出為 BASE-64 編碼的 X.509 (.cer) 檔案。Once the certificate manager is running, open the Personal Certificates as shown below and export the certificate with the friendly name "DocumentDBEmulatorCertificate" as a BASE-64 encoded X.509 (.cer) file.

Azure Cosmos DB 本機模擬器的 SSL 憑證

遵循新增憑證至 Java CA 憑證存放區中的指示,X.509 憑證就可以匯入 Java 憑證存放區。The X.509 certificate can be imported into the Java certificate store by following the instructions in Adding a Certificate to the Java CA Certificates Store. 將憑證匯入至憑證存放區之後,SQL 和適用於 MongoDB 的 Azure Cosmos DB API 的用戶端就可以連線到 Azure Cosmos 模擬器。Once the certificate is imported into the certificate store, clients for SQL and Azure Cosmos DB's API for MongoDB will be able to connect to the Azure Cosmos Emulator.

從 Python 和 Node.js SDK 連接到模擬器時,會停用 SSL 驗證。When connecting to the emulator from Python and Node.js SDKs, SSL verification is disabled.

命令列工具參考Command-line tool reference

您可以從安裝位置使用命令列來啟動和停止模擬器、設定選項,以及執行其他作業。From the installation location, you can use the command-line to start and stop the emulator, configure options, and perform other operations.

命令列語法Command-line syntax

CosmosDB.Emulator.exe [/Shutdown] [/DataPath] [/Port] [/MongoPort] [/DirectPorts] [/Key] [/EnableRateLimiting] [/DisableRateLimiting] [/NoUI] [/NoExplorer] [/EnableMongoDbEndpoint] [/?]

若要檢視選項清單,請在命令提示字元輸入 CosmosDB.Emulator.exe /?To view the list of options, type CosmosDB.Emulator.exe /? at the command prompt.

選項Option 說明Description 命令Command 引數Arguments
[無引數][No arguments] 使用預設設定來啟動 Azure Cosmos 模擬器。Starts up the Azure Cosmos Emulator with default settings. CosmosDB.Emulator.exeCosmosDB.Emulator.exe
[說明][Help] 顯示支援的命令列引數清單。Displays the list of supported command-line arguments. CosmosDB.Emulator.exe /?CosmosDB.Emulator.exe /?
GetStatusGetStatus 取得 Azure Cosmos 模擬器的狀態。Gets the status of the Azure Cosmos Emulator. 狀態會以結束代碼表示:1 = 啟動,2 = 執行中,3 = 已停止。The status is indicated by the exit code: 1 = Starting, 2 = Running, 3 = Stopped. 負數的結束代碼表示發生錯誤。A negative exit code indicates that an error occurred. 不會產生其他輸出。No other output is produced. CosmosDB.Emulator.exe /GetStatusCosmosDB.Emulator.exe /GetStatus
ShutdownShutdown 關閉 Azure Cosmos 模擬器。Shuts down the Azure Cosmos Emulator. CosmosDB.Emulator.exe /ShutdownCosmosDB.Emulator.exe /Shutdown
資料路徑DataPath 指定用來儲存資料檔案的路徑。Specifies the path in which to store data files. 預設值為 %LocalAppdata%\CosmosDBEmulator。Default value is %LocalAppdata%\CosmosDBEmulator. CosmosDB.Emulator.exe /DataPath=<datapath>CosmosDB.Emulator.exe /DataPath=<datapath> <資料路徑>:可存取的路徑<datapath>: An accessible path
PortPort 指定用於模擬器的連接埠號碼。Specifies the port number to use for the emulator. 預設值為 8081。Default value is 8081. CosmosDB.Emulator.exe /Port=<port>CosmosDB.Emulator.exe /Port=<port> <連接埠>:單一連接埠號碼<port>: Single port number
ComputePortComputePort 指定用於計算 Interop 閘道服務的連接埠號碼。Specified the port number to use for the Compute Interop Gateway service. 閘道 HTTP 端點探查連接埠的計算方式為 ComputePort + 79。The Gateway's HTTP endpoint probe port is calculated as ComputePort + 79. 因此,ComputePort 和 ComputePort + 79 必須開啟且可供使用。Hence, ComputePort and ComputePort + 79 must be open and available. 預設值為 8900、8979。The default values are 8900, 8979. CosmosDB.Emulator.exe /ComputePort = <computeport>CosmosDB.Emulator.exe /ComputePort = <computeport> <computeport>:單一連接埠號碼<computeport>: Single port number
EnableMongoDbEndpointEnableMongoDbEndpoint 啟用 MongoDB APIEnables MongoDB API CosmosDB.Emulator.exe /EnableMongoDbEndpointCosmosDB.Emulator.exe /EnableMongoDbEndpoint
MongoPortMongoPort 指定要用於 MongoDB 相容性 API 的連接埠號碼。Specifies the port number to use for MongoDB compatibility API. 預設值為 10255。Default value is 10255. CosmosDB.Emulator.exe /MongoPort= <mongoport>CosmosDB.Emulator.exe /MongoPort= <mongoport> <mongoport>:單一連接埠號碼<mongoport>: Single port number
EnableCassandraEndpointEnableCassandraEndpoint 啟用 Cassandra APIEnables Cassandra API CosmosDB.Emulator.exe /EnableCassandraEndpointCosmosDB.Emulator.exe /EnableCassandraEndpoint
CassandraPortCassandraPort 指定用於 Cassandra 端點的連接埠號碼。Specifies the port number to use for the Cassandra endpoint. 預設值為 10350。Default value is 10350. CosmosDB.Emulator.exe /CassandraPort = <cassandraport>CosmosDB.Emulator.exe /CassandraPort = <cassandraport> <cassandraport>:單一連接埠號碼<cassandraport>: Single port number
EnableGremlinEndpointEnableGremlinEndpoint 啟用 Gremlin APIEnables Gremlin API CosmosDB.Emulator.exe /EnableGremlinEndpointCosmosDB.Emulator.exe /EnableGremlinEndpoint
GremlinPortGremlinPort 用於 Gremlin 端點的連接埠號碼。Port number to use for the Gremlin Endpoint. 預設值為 8901。Default value is 8901. CosmosDB.Emulator.exe /GremlinPort=<port>CosmosDB.Emulator.exe /GremlinPort=<port> <連接埠>:單一連接埠號碼<port>: Single port number
EnableTableEndpointEnableTableEndpoint 啟用 Azure 資料表 APIEnables Azure Table API CosmosDB.Emulator.exe /EnableTableEndpointCosmosDB.Emulator.exe /EnableTableEndpoint
TablePortTablePort 用於 Azure 資料表端點的連接埠號碼。Port number to use for the Azure Table Endpoint. 預設值為 8902。Default value is 8902. CosmosDB.Emulator.exe /TablePort=<port>CosmosDB.Emulator.exe /TablePort=<port> <連接埠>:單一連接埠號碼<port>: Single port number
KeyFileKeyFile 從指定的檔案中讀取授權金鑰。Read authorization key from the specified file. 使用 /GenKeyFile 選項來產生金鑰檔Use the /GenKeyFile option to generate a keyfile CosmosDB.Emulator.exe /KeyFile=<file_name>CosmosDB.Emulator.exe /KeyFile=<file_name> <file_name>:檔案的路徑<file_name>: Path to the file
ResetDataPathResetDataPath 以遞迴方式移除指定路徑中的所有檔案。Recursively removes all the files in the specified path. 如果您未指定路徑,則會預設為 %LOCALAPPDATA%\CosmosDbEmulatorIf you don't specify a path, it defaults to %LOCALAPPDATA%\CosmosDbEmulator CosmosDB.Emulator.exe /ResetDataPath=<path>CosmosDB.Emulator.exe /ResetDataPath=<path> <path>:檔案路徑<path>: File path
StartTracesStartTraces 開始收集偵錯追蹤記錄。Start collecting debug trace logs. CosmosDB.Emulator.exe /StartTracesCosmosDB.Emulator.exe /StartTraces
StopTracesStopTraces 停止收集偵錯追蹤記錄。Stop collecting debug trace logs. CosmosDB.Emulator.exe /StopTracesCosmosDB.Emulator.exe /StopTraces
FailOnSslCertificateNameMismatchFailOnSslCertificateNameMismatch 根據預設,如果憑證的 SAN 不包含模擬器主機的網域名稱、本機 IPv4 位址、'localhost' 及 '127.0.0.1',模擬器就會重新產生其自我簽署的 SSL 憑證。By default the Emulator regenerates its self-signed SSL certificate, if the certificate's SAN does not include the Emulator host's domain name, local IPv4 address, 'localhost', and '127.0.0.1'. 使用此選項,模擬器反而將在啟動時失敗。With this option, the emulator will fail at startup instead. 您接著應該使用 /GenCert 選項,來建立並安裝新的自我簽署 SSL 憑證。You should then use the /GenCert option to create and install a new self-signed SSL certificate. CosmosDB.Emulator.exe /FailOnSslCertificateNameMismatchCosmosDB.Emulator.exe /FailOnSslCertificateNameMismatch
GenCertGenCert 產生並安裝新的自我簽署 SSL 憑證。Generate and install a new self-signed SSL certificate. 選擇性地包括其他 DNS 名稱的逗號分隔清單,以透過網路來存取模擬器。optionally including a comma-separated list of additional DNS names for accessing the Emulator over the network. CosmosDB.Emulator.exe /GenCert=<dns-names>CosmosDB.Emulator.exe /GenCert=<dns-names> <dns-names>:其他 dns 名稱的選擇性逗號分隔清單<dns-names>: Optional comma-separated list of additional dns names
DirectPortsDirectPorts 指定要用於直接連線的連接埠。Specifies the ports to use for direct connectivity. 預設值為 10251、10252、10253、10254。Defaults are 10251,10252,10253,10254. CosmosDB.Emulator.exe /DirectPorts:<directports>CosmosDB.Emulator.exe /DirectPorts:<directports> <directports>:以逗號分隔的 4 個連接埠清單<directports>: Comma-delimited list of 4 ports
KeyKey 模擬器的授權金鑰。Authorization key for the emulator. 金鑰必須是 64 位元組向量的 base-64 編碼方式。Key must be the base-64 encoding of a 64-byte vector. CosmosDB.Emulator.exe /Key:<key>CosmosDB.Emulator.exe /Key:<key> <金鑰>:金鑰必須是 64 位元組向量的 base-64 編碼方式<key>: Key must be the base-64 encoding of a 64-byte vector
EnableRateLimitingEnableRateLimiting 指定要啟用要求率限制行為。Specifies that request rate limiting behavior is enabled. CosmosDB.Emulator.exe /EnableRateLimitingCosmosDB.Emulator.exe /EnableRateLimiting
DisableRateLimitingDisableRateLimiting 指定要停用要求率限制行為。Specifies that request rate limiting behavior is disabled. CosmosDB.Emulator.exe /DisableRateLimitingCosmosDB.Emulator.exe /DisableRateLimiting
NoUINoUI 不要顯示模擬器使用者介面。Do not show the emulator user interface. CosmosDB.Emulator.exe /NoUICosmosDB.Emulator.exe /NoUI
NoExplorerNoExplorer 啟動時不要顯示資料總管。Don't show data explorer on startup. CosmosDB.Emulator.exe /NoExplorerCosmosDB.Emulator.exe /NoExplorer
PartitionCountPartitionCount 指定已分割容器的數目上限。Specifies the maximum number of partitioned containers. 如需詳細資訊,請參閱變更容器的數目See Change the number of containers for more information. CosmosDB.Emulator.exe /PartitionCount=<partitioncount>CosmosDB.Emulator.exe /PartitionCount=<partitioncount> <partitioncount>:允許的單一分割區容器數目上限。<partitioncount>: Maximum number of allowed single partition containers. 預設值為 25。Default value is 25. 允許的上限為 250。Maximum allowed is 250.
DefaultPartitionCountDefaultPartitionCount 指定已分割容器之分割區數目的預設值。Specifies the default number of partitions for a partitioned container. CosmosDB.Emulator.exe /DefaultPartitionCount=<defaultpartitioncount>CosmosDB.Emulator.exe /DefaultPartitionCount=<defaultpartitioncount> <defaultpartitioncount> 預設值為 25。<defaultpartitioncount> Default value is 25.
AllowNetworkAccessAllowNetworkAccess 讓模擬器可以透過網路存取。Enables access to the emulator over a network. 您也必須傳遞 /Key=<key_string> 或 /KeyFile=<file_name> 以啟用網路存取。You must also pass /Key=<key_string> or /KeyFile=<file_name> to enable network access. CosmosDB.Emulator.exe /AllowNetworkAccess /Key=<key_string> 或 CosmosDB.Emulator.exe /AllowNetworkAccess /KeyFile=<file_name>CosmosDB.Emulator.exe /AllowNetworkAccess /Key=<key_string> or CosmosDB.Emulator.exe /AllowNetworkAccess /KeyFile=<file_name>
NoFirewallNoFirewall 不要在使用 /AllowNetworkAccess 選項時調整防火牆規則。Don't adjust firewall rules when /AllowNetworkAccess option is used. CosmosDB.Emulator.exe /NoFirewallCosmosDB.Emulator.exe /NoFirewall
GenKeyFileGenKeyFile 產生新的授權金鑰並儲存到指定的檔案。Generate a new authorization key and save to the specified file. 產生的金鑰可以搭配 /Key 或 /KeyFile 選項使用。The generated key can be used with the /Key or /KeyFile options. CosmosDB.Emulator.exe /GenKeyFile=<金鑰檔案路徑>CosmosDB.Emulator.exe /GenKeyFile=<path to key file>
一致性Consistency 設定帳戶的預設一致性層級。Set the default consistency level for the account. CosmosDB.Emulator.exe /Consistency=<consistency>CosmosDB.Emulator.exe /Consistency=<consistency> <一致性>:值必須屬於下列其中一個一致性層級:Session、Strong、Eventual 或 BoundedStaleness。<consistency>: Value must be one of the following consistency levels: Session, Strong, Eventual, or BoundedStaleness. 預設值為 Session。The default value is Session.
?? 顯示說明訊息。Show the help message.

變更容器數目Change the number of containers

根據預設,您最多可以建立 25 個固定大小的容器 (僅支援使用 Azure Cosmos DB SDK),或者,使用 Azure Cosmos 模擬器來建立 5 個無限制的容器。By default, you can create up to 25 fixed size containers (only supported using Azure Cosmos DB SDKs), or 5 unlimited containers using the Azure Cosmos Emulator. 藉由修改 PartitionCount 值,您最多可以建立 250 個固定大小的容器、50 個無限制的容器,或兩者不超過 250 個固定大小容器的任意組合 (其中一個無限制的容器 = 5 個固定大小的容器)。By modifying the PartitionCount value, you can create up to 250 fixed size containers or 50 unlimited containers, or any combination of the two that does not exceed 250 fixed size containers (where one unlimited container = 5 fixed size containers). 但是,不建議將模擬器設定為搭配超過 200 個固定大小的容器來執行。However it's not recommended to set up the emulator to run with more than 200 fixed size containers. 由於它對磁碟 IO 作業新增了額外負荷,因此,會在使用端點 API 時導致無法預期的逾時。Because of the overhead that it adds to the disk IO operations, which result in unpredictable timeouts when using the endpoint APIs.

如果您在超過目前分割區計數之後嘗試建立容器,模擬器就會擲回 ServiceUnavailable 例外狀況,並隨附下列訊息。If you attempt to create a container after the current partition count has been exceeded, the emulator throws a ServiceUnavailable exception, with the following message.

「很抱歉,這個區域目前出現了大量的需求,此時無法完成您的需求。"Sorry, we are currently experiencing high demand in this region, and cannot fulfill your request at this time. 我們正持續努力讓越來越多容量上線,並建議您再試一次。We work continuously to bring more and more capacity online, and encourage you to try again. 您可以隨時都能基於任何因素寄送電子郵件到 askcosmosdb@microsoft.com。Please do not hesitate to email askcosmosdb@microsoft.com at any time or for any reason. ActivityId:12345678-1234-1234-1234-123456789abc"ActivityId: 12345678-1234-1234-1234-123456789abc"

若要變更 Azure Cosmos 模擬器中可用的容器數目,請執行下列步驟:To change the number of containers available in the Azure Cosmos Emulator, run the following steps:

  1. 以滑鼠右鍵按一下系統匣上的 [Azure Cosmos DB 模擬器] 圖示,然後按一下 [重設資料...] ,來刪除所有的本機 Azure Cosmos 模擬器資料。Delete all local Azure Cosmos Emulator data by right-clicking the Azure Cosmos DB Emulator icon on the system tray, and then clicking Reset Data….
  2. 刪除此資料夾 %LOCALAPPDATA%\CosmosDBEmulator 中的所有模擬器資料。Delete all emulator data in this folder %LOCALAPPDATA%\CosmosDBEmulator.
  3. 結束所有開啟的執行個體,方法是以滑鼠右鍵按一下系統匣上的 [Azure Cosmos DB 模擬器] 圖示,然後按一下 [結束] 。Exit all open instances by right-clicking the Azure Cosmos DB Emulator icon on the system tray, and then clicking Exit. 結束所有執行個體可能需要數分鐘的時間。It may take a minute for all instances to exit.
  4. 安裝最新版的 Azure Cosmos 模擬器Install the latest version of the Azure Cosmos Emulator.
  5. 啟動具有 PartitionCount 旗標的模擬器,方法是設定值 <= 250。Launch the emulator with the PartitionCount flag by setting a value <= 250. 例如: C:\Program Files\Azure Cosmos DB Emulator> CosmosDB.Emulator.exe /PartitionCount=100For example: C:\Program Files\Azure Cosmos DB Emulator> CosmosDB.Emulator.exe /PartitionCount=100.

控制模擬器Controlling the emulator

模擬器隨附 PowerShell 模組,可用於啟動、停止、解除安裝及擷取服務的狀態。The emulator comes with a PowerShell module to start, stop, uninstall, and retrieve the status of the service. 執行下列 Cmdlet 以使用 PowerShell 模組:Run the following cmdlet to use the PowerShell module:

Import-Module "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules\Microsoft.Azure.CosmosDB.Emulator"

或者,將 PSModules 目錄放置於您的 PSModulesPath 並匯入它,如下列命令所示:or place the PSModules directory on your PSModulesPath and import it as shown in the following command:

$env:PSModulesPath += "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules"
Import-Module Microsoft.Azure.CosmosDB.Emulator

以下是從 PowerShell 控制模擬器的命令摘要:Here is a summary of the commands for controlling the emulator from PowerShell:

Get-CosmosDbEmulatorStatus

語法Syntax

Get-CosmosDbEmulatorStatus

備註Remarks

傳回下列其中一個 ServiceControllerStatus 值:ServiceControllerStatus.StartPending、ServiceControllerStatus.Running 或 ServiceControllerStatus.Stopped。Returns one of these ServiceControllerStatus values: ServiceControllerStatus.StartPending, ServiceControllerStatus.Running, or ServiceControllerStatus.Stopped.

Start-CosmosDbEmulator

語法Syntax

Start-CosmosDbEmulator [-DataPath <string>] [-DefaultPartitionCount <uint16>] [-DirectPort <uint16[]>] [-MongoPort <uint16>] [-NoUI] [-NoWait] [-PartitionCount <uint16>] [-Port <uint16>] [<CommonParameters>]

備註Remarks

啟動模擬器。Starts the emulator. 根據預設,命令會等到模擬器準備好接受要求。By default, the command waits until the emulator is ready to accept requests. 如果您希望啟動模擬器時立即傳回 Cmdlet,請使用 -NoWait 選項。Use the -NoWait option, if you wish the cmdlet to return as soon as it starts the emulator.

Stop-CosmosDbEmulator

語法Syntax

Stop-CosmosDbEmulator [-NoWait]

備註Remarks

停止模擬器。Stops the emulator. 根據預設,此命令會等到模擬器完全關機。By default, this command waits until the emulator is fully shut down. 如果您希望模擬器開始關閉時立即傳回 Cmdlet,請使用 -NoWait 選項。Use the -NoWait option, if you wish the cmdlet to return as soon as the emulator begins to shut down.

Uninstall-CosmosDbEmulator

語法Syntax

Uninstall-CosmosDbEmulator [-RemoveData]

備註Remarks

解除安裝模擬器,並選擇性地移除 $env 的完整內容:LOCALAPPDATA\CosmosDbEmulator。Uninstalls the emulator and optionally removes the full contents of $env:LOCALAPPDATA\CosmosDbEmulator. Cmdlet 可確保在解除安裝之前停止模擬器。The cmdlet ensures the emulator is stopped before uninstalling it.

在 Docker 上執行Running on Docker

Azure Cosmos 模擬器可以在適用於 Windows 的 Docker 上執行。The Azure Cosmos Emulator can be run on Docker for Windows. 模擬器無法在 Docker for Oracle Linux 上運作。The emulator does not work on Docker for Oracle Linux.

安裝 Docker for Windows 後,以滑鼠右鍵按一下工具列上的 Docker 圖示,然後選取 [切換到 Windows 容器] ,即可切換到 Windows 容器。Once you have Docker for Windows installed, switch to Windows containers by right-clicking the Docker icon on the toolbar and selecting Switch to Windows containers.

接下來,從最喜愛的殼層執行下列命令,即可從 Docker Hub 提取模擬器映像。Next, pull the emulator image from Docker Hub by running the following command from your favorite shell.

docker pull mcr.microsoft.com/cosmosdb/windows/azure-cosmos-emulator

若要啟動映像,請執行下列命令。To start the image, run the following commands.

從命令列執行:From the command-line:


md %LOCALAPPDATA%\CosmosDBEmulator\bind-mount

docker run --name azure-cosmosdb-emulator --memory 2GB --mount "type=bind,source=%LOCALAPPDATA%\CosmosDBEmulator\bind-mount,destination=C:\CosmosDB.Emulator\bind-mount" --interactive --tty -p 8081:8081 -p 8900:8900 -p 8901:8901 -p 8902:8902 -p 10250:10250 -p 10251:10251 -p 10252:10252 -p 10253:10253 -p 10254:10254 -p 10255:10255 -p 10256:10256 -p 10350:10350 mcr.microsoft.com/cosmosdb/windows/azure-cosmos-emulator

注意

如果您在執行 docker run 命令時看到連接埠衝突錯誤 (指定的連接埠已在使用中),您可以藉由變更埠號碼來傳遞自訂連接埠。If you see a port conflict error (specified port is already in use) when you run the docker run command, you can pass a custom port by altering the port numbers. 例如,您可以將 "-p 8081:8081" 變更為 "-p 443:8081"For example, you can change the "-p 8081:8081" to "-p 443:8081"

從 PowerShell:From PowerShell:


md $env:LOCALAPPDATA\CosmosDBEmulator\bind-mount 2>null

docker run --name azure-cosmosdb-emulator --memory 2GB --mount "type=bind,source=$env:LOCALAPPDATA\CosmosDBEmulator\bind-mount,destination=C:\CosmosDB.Emulator\bind-mount" --interactive --tty -p 8081:8081 -p 8900:8900 -p 8901:8901 -p 8902:8902 -p 10250:10250 -p 10251:10251 -p 10252:10252 -p 10253:10253 -p 10254:10254 -p 10255:10255 -p 10256:10256 -p 10350:10350 mcr.microsoft.com/cosmosdb/windows/azure-cosmos-emulator

回應如下所示:The response looks similar to the following:

Starting emulator
Emulator Endpoint: https://172.20.229.193:8081/
Master Key: C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==
Exporting SSL Certificate
You can import the SSL certificate from an administrator command prompt on the host by running:
cd /d %LOCALAPPDATA%\CosmosDBEmulatorCert
powershell .\importcert.ps1
--------------------------------------------------------------------------------------------------
Starting interactive shell

現在,在您的用戶端使用回應中的端點和主要金鑰,並將 SSL 憑證匯入您的主機。Now use the endpoint and master key-in from the response in your client and import the SSL certificate into your host. 若要匯入 SSL 憑證,請從系統管理員命令提示字元中執行下列命令︰To import the SSL certificate, do the following from an admin command prompt:

從命令列執行:From the command-line:

cd  %LOCALAPPDATA%\CosmosDBEmulator\bind-mount
powershell .\importcert.ps1

從 PowerShell:From PowerShell:

cd $env:LOCALAPPDATA\CosmosDBEmulator\bind-mount
.\importcert.ps1

模擬器啟動之後,關閉互動式殼層將會關閉模擬器的容器。Closing the interactive shell once the emulator has been started will shut down the emulator’s container.

若要開啟資料總管,請在瀏覽器中瀏覽至下列 URL。To open the Data Explorer, navigate to the following URL in your browser. 如上所示,回應訊息中提供模擬器端點。The emulator endpoint is provided in the response message shown above.

https://<emulator endpoint provided in response>/_explorer/index.html

在 Mac 或 Linux 上執行Running on Mac or Linux

目前 Cosmos 模擬器只能在 Windows 上執行。Currently the Cosmos emulator can only be run on Windows. 執行 Mac 或 Linux 的使用者可以在裝載於 Parallels 或 VirtualBox 等 Hypervisor 的 Windows 虛擬機器中執行模擬器。Users running Mac or Linux can run the emulator in a Windows virtual machine hosted a hypervisor such as Parallels or VirtualBox. 以下是此功能的啟用步驟。Below are the steps to enable this.

在 Windows VM 內執行下列命令,並記下 IPv4 位址。Within the Windows VM run the command below and make note of the IPv4 address.

ipconfig.exe

您需要在應用程式內變更 DocumentClient 物件的 URI,以使用 ipconfig.exe 所傳回的 IPv4 位址。Within your application you need to change the URI for the DocumentClient object to use the IPv4 address returned by ipconfig.exe. 下一個步驟是在建構 DocumentClient 物件時,處理 CA 驗證。The next step is to work around the CA validation when constructing the DocumentClient object. 為此您需要提供 HttpClientHandler 給 DocumentClient 建構函式,其中包含 ServerCertificateCustomValidationCallback 本身的實作。For this you will need to provide an HttpClientHandler to the DocumentClient constructor, which has it's own implementation for ServerCertificateCustomValidationCallback.

以下是程式碼外觀的範例。Below is an example of what the code should look like.

using System;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System.Net.Http;

namespace emulator
{
    class Program
    {
        static async void Main(string[] args)
        {
            string strEndpoint = "https://10.135.16.197:8081/";  //IPv4 address from ipconfig.exe
            string strKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";

            //Work around the CA validation
            var httpHandler = new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = (req,cert,chain,errors) => true
            };

            //Pass http handler to document client
            using (DocumentClient client = new DocumentClient(new Uri(strEndpoint), strKey, httpHandler))
            {
                Database database = await client.CreateDatabaseIfNotExistsAsync(new Database { Id = "myDatabase" });
                Console.WriteLine($"Created Database: id - {database.Id} and selfLink - {database.SelfLink}");
            }
        }
    }
}

最後,在 Windows VM 內,使用下列選項從命令列啟動 Cosmos 模擬器。Finally, from the within the Windows VM, launch the Cosmos emulator from the command line using the following options.

Microsoft.Azure.Cosmos.Emulator.exe /AllowNetworkAccess /Key=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==

疑難排解Troubleshooting

使用下列秘訣,可協助您對使用 Azure Cosmos 模擬器時遇到的問題進行疑難排解:Use the following tips to help troubleshoot issues you encounter with the Azure Cosmos Emulator:

  • 如果您已安裝新版本的模擬器但發生了錯誤,請務必重設您的資料。If you installed a new version of the emulator and are experiencing errors, ensure you reset your data. 您可以滑鼠右鍵按一下系統匣上的 [Azure Cosmos 模擬器] 圖示,然後按一下 [重設資料...] 來重設資料。You can reset your data by right-clicking the Azure Cosmos Emulator icon on the system tray, and then clicking Reset Data…. 如果該動作無法修正錯誤,您可以解除安裝模擬器以及任何所找到的舊版模擬器、移除 "C:\Program files\Azure Cosmos DB 模擬器" 目錄,然後重新安裝模擬器。If that does not fix the errors, you can uninstall the emulator and any older versions of the emulator if found, remove "C:\Program files\Azure Cosmos DB Emulator" directory and reinstall the emulator. 如需相關指示,請參閱解除安裝本機模擬器See Uninstall the local emulator for instructions.

  • 如果 Azure Cosmos 模擬器當機,請從 '%LOCALAPPDATA%\CrashDumps' 資料夾中收集傾印檔案、壓縮檔案後附加到電子郵件,然後寄到 askcosmosdb@microsoft.comIf the Azure Cosmos Emulator crashes, collect dump files from '%LOCALAPPDATA%\CrashDumps' folder, compress them, and attach them to an email to askcosmosdb@microsoft.com.

  • 如果您在 Microsoft.Azure.Cosmos.ComputeServiceStartupEntryPoint.exe 中遇到當機,這可能是效能計數器處於損毀狀態的徵兆。If you experience crashes in Microsoft.Azure.Cosmos.ComputeServiceStartupEntryPoint.exe, this might be a symptom where the Performance Counters are in a corrupted state. 通常從系統管理員的命令提示字元中執行下列命令,即可修正此問題:Usually running the following command from an admin command prompt fixes the issue:

    lodctr /R
    
  • 如果您遇到連線問題,請收集追蹤檔案,壓縮檔案後,再附加到電子郵件寄至askcosmosdb@microsoft.comIf you encounter a connectivity issue, collect trace files, compress them, and attach them to an email to askcosmosdb@microsoft.com.

  • 如果您收到服務無法使用訊息,模擬器可能無法初始化網路堆疊。If you receive a Service Unavailable message, the emulator might be failing to initialize the network stack. 由於 Pulse 安全用戶端或 Juniper 網路用戶端的網路篩選驅動程式可能會造成問題,因此請檢查是否已安裝這些驅動程式。Check to see if you have the Pulse secure client or Juniper networks client installed, as their network filter drivers may cause the problem. 解除安裝協力廠商網路篩選驅動程式通常便會修正問題。Uninstalling third-party network filter drivers typically fixes the issue. 或者,使用 /DisableRIO 來啟動模擬器,將模擬器網路通訊切換為一般 Winsock。Alternatively, start the emulator with /DisableRIO, which will switch the emulator network communication to regular Winsock.

  • 當模擬器執行時,如果您的電腦進入睡眠模式或執行任何作業系統更新,您應該會看見服務目前無法使用的訊息。While the emulator is running, if your computer goes to sleep mode or runs any OS updates, you might see a Service is currently unavailable message. 以滑鼠右鍵按一下視窗通知匣上出現的圖示,然後選取 [重設資料] ,來重設模擬器的資料。Reset the emulator's data, by right-clicking on the icon that appears on the windows notification tray and select Reset Data.

收集追蹤檔案Collect trace files

若要收集偵錯追蹤,請從系統管理命令提示字元執行下列命令︰To collect debugging traces, run the following commands from an administrative command prompt:

  1. cd /d "%ProgramFiles%\Azure Cosmos DB Emulator"
  2. CosmosDB.Emulator.exe /shutdownCosmosDB.Emulator.exe /shutdown. 監看系統匣,確認程式已經關閉,這可能需要一分鐘的時間。Watch the system tray to make sure the program has shut down, it may take a minute. 您也可以直接按一下 Azure Cosmos 模擬器使用者介面中的 [結束] 。You can also just click Exit in the Azure Cosmos Emulator user interface.
  3. CosmosDB.Emulator.exe /starttraces
  4. CosmosDB.Emulator.exe
  5. 重現問題。Reproduce the problem. 如果資料總管無法運作,您只需要等候數秒鐘的時間,等到瀏覽器開啟即可攔截錯誤。If Data Explorer is not working, you only need to wait for the browser to open for a few seconds to catch the error.
  6. CosmosDB.Emulator.exe /stoptraces
  7. 瀏覽至 %ProgramFiles%\Azure Cosmos DB Emulator 並尋找 docdbemulator_000001.etl 檔案。Navigate to %ProgramFiles%\Azure Cosmos DB Emulator and find the docdbemulator_000001.etl file.
  8. 將 .etl 檔案以及重現步驟傳送至 askcosmosdb@microsoft.com 進行偵錯。Send the .etl file along with repro steps to askcosmosdb@microsoft.com for debugging.

將本機模擬器解除安裝Uninstall the local emulator

  1. 以滑鼠右鍵按一下系統匣上的 Azure Cosmos 模擬器圖示,然後按一下 [結束],即可結束本機模擬器所有已開啟的執行個體。Exit all open instances of the local emulator by right-clicking the Azure Cosmos Emulator icon on the system tray, and then clicking Exit. 結束所有執行個體可能需要數分鐘的時間。It may take a minute for all instances to exit.
  2. 在 Windows 搜尋方塊中,輸入 App 與功能,然後按一下 [App 與功能 (系統設定)] 結果。In the Windows search box, type Apps & features and click on the Apps & features (System settings) result.
  3. 在應用程式清單中,捲動至 [Azure Cosmos DB 模擬器] 並將其選取,按一下 [解除安裝] ,然後確認並再按一下 [解除安裝] 。In the list of apps, scroll to Azure Cosmos DB Emulator, select it, click Uninstall, then confirm and click Uninstall again.
  4. 當應用程式已解除安裝時,請瀏覽至 %LOCALAPPDATA%\CosmosDBEmulator 然後刪除該資料夾。When the app is uninstalled, navigate to %LOCALAPPDATA%\CosmosDBEmulator and delete the folder.

後續步驟Next steps

在本教學課程中,您學習到如何使用免費的本機模擬器在本機開發。In this tutorial, you've learned how to use the local emulator for free local development. 現在您可以繼續進行下一個教學課程,了解如何匯出模擬器 SSL 憑證。You can now proceed to the next tutorial and learn how to export emulator SSL certificates.