模拟器的一个常见用例是在构建应用程序时充当开发数据库。 使用模拟器进行开发可帮助你了解为 Azure Cosmos DB 等数据库创建和建模数据的特点,且不会产生任何服务费用。 此外,将模拟器用作自动化工作流的一部分,可以确保能够运行相同的集成测试套件。 模拟器可以确保在本地开发计算机和远程持续集成作业中运行相同的测试。
先决条件
安装模拟器
模拟器有多个变体,每个变体的安装过程都相对顺畅。
要开始使用,请从 Microsoft 容器注册表 (MCR) 获取容器映像的 Linux 变体。
将 mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator
Linux 容器映像从容器注册表拉取到本地 Docker 主机。
docker pull mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest
检查以确保模拟器映像在本地 Docker 主机上可用。
docker images
要开始使用,请从 Microsoft 容器注册表 (MCR) 获取容器映像的 Windows 变体。
将 mcr.microsoft.com/cosmosdb/windows/azure-cosmos-emulator
Windows 容器映像从容器注册表拉取到本地 Docker 主机。
docker pull mcr.microsoft.com/cosmosdb/windows/azure-cosmos-emulator
检查以确保模拟器映像在本地 Docker 主机上可用。
docker images
若要开始,请在本地计算机上下载并安装最新版本的 Azure Cosmos DB 模拟器。
提示
模拟器发行说明一文列出了所有可用版本以及每个版本中所做的功能更新。
下载 Azure Cosmos DB 模拟器。
使用“管理权限”在本地计算机上运行安装程序。
模拟器会自动安装相应的开发人员证书,并在本地计算机上配置防火墙规则。
要开始使用,请从 Microsoft 容器注册表 (MCR) 获取容器映像的 Linux 变体。
使用 mongodb
标记将 mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator
Linux 容器映像从容器注册表拉取到本地 Docker 主机。
docker pull mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:mongodb
检查以确保模拟器映像在本地 Docker 主机上可用。
docker images
Docker (Windows) 容器映像不支持 API for MongoDB。
若要开始,请在本地计算机上下载并安装最新版本的 Azure Cosmos DB 模拟器。
提示
模拟器发行说明一文列出了所有可用版本以及每个版本中所做的功能更新。
下载 Azure Cosmos DB 模拟器。
使用“管理权限”在本地计算机上运行安装程序。
模拟器会自动安装相应的开发人员证书,并在本地计算机上配置防火墙规则。
模拟器的 Docker 容器变体(Linux 或 Windows)不支持 API for Apache Cassandra、API for Apache Gremlin 或 API for Table。
若要开始,请在本地计算机上下载并安装最新版本的 Azure Cosmos DB 模拟器。
提示
模拟器发行说明一文列出了所有可用版本以及每个版本中所做的功能更新。
下载 Azure Cosmos DB 模拟器。
使用“管理权限”在本地计算机上运行安装程序。
模拟器会自动安装相应的开发人员证书,并在本地计算机上配置防火墙规则。
启动模拟器
下载后,启用指定的 API 并启动模拟器。
模拟器的 Docker 容器变体不支持 API for Apache Cassandra。
在 %ProgramFiles%\Azure Cosmos DB Emulator
路径上启动模拟器的可执行文件 (Microsoft.Azure.Cosmos.Emulator.exe
)。 使用以下参数来配置模拟器:
|
说明 |
EnableCassandraEndpoint |
启用 API for Apache Cassandra 终结点。 |
CassandraPort |
用于终结点的端口号。 |
Microsoft.Azure.Cosmos.Emulator.exe /EnableCassandraEndpoint /CassandraPort=65200
注意
有关命令行参数的详细信息,请参阅 命令行参数。
模拟器使用 URL https://localhost:8081/_explorer/index.html
自动打开数据资源管理器。
模拟器的 Docker 容器变体不支持 API for Apache Gremlin。
在 %ProgramFiles%\Azure Cosmos DB Emulator
路径上启动模拟器的可执行文件 (Microsoft.Azure.Cosmos.Emulator.exe
)。 使用以下参数来配置模拟器:
|
说明 |
EnableGremlinEndpoint |
启用 API for Apache Gremlin。 |
GremlinPort |
用于终结点的端口号。 |
Microsoft.Azure.Cosmos.Emulator.exe /EnableGremlinEndpoint /GremlinPort=65400
注意
有关命令行参数的详细信息,请参阅 命令行参数。
模拟器使用 URL https://localhost:8081/_explorer/index.html
自动打开数据资源管理器。
模拟器的 Docker 容器变体不支持 API for Table。
在 %ProgramFiles%\Azure Cosmos DB Emulator
路径上启动模拟器的可执行文件 (Microsoft.Azure.Cosmos.Emulator.exe
)。 使用以下参数来配置模拟器:
|
说明 |
EnableTableEndpoint |
启用 API for Table 终结点。 |
TablePort |
用于终结点的端口号。 |
Microsoft.Azure.Cosmos.Emulator.exe /EnableTableEndpoint /TablePort=65500
注意
有关命令行参数的详细信息,请参阅 命令行参数。
模拟器使用 URL https://localhost:8081/_explorer/index.html
自动打开数据资源管理器。
使用容器映像和以下配置来运行新容器:
|
说明 |
(可选)AZURE_COSMOS_EMULATOR_PARTITION_COUNT |
指定要使用的分区数。 |
(可选)AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE |
在模拟器运行间隙启用数据持久性。 |
(可选)AZURE_COSMOS_EMULATOR_IP_ADDRESS_OVERRIDE |
替代模拟器的默认 IP 地址。 |
对于 Linux 系统,请使用:
docker run \
--publish 8081:8081 \
--publish 10250-10255:10250-10255 \
--name linux-emulator \
--detach \
mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest
对于 Windows 系统,请使用:
$parameters = @(
"--publish", "8081:8081"
"--publish", "10250-10255:10250-10255"
"--name", "windows-emulator"
"--detach"
)
docker run @parameters mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest
导航到 https://localhost:8081/_explorer/index.html
以访问数据资源管理器。
为绑定装载创建新目录
使用容器映像运行新容器。
$parameters = @(
"--publish", "8081:8081"
"--publish", "10250-10255:10250-10255"
"--name", "windows-emulator"
"--detach"
)
docker run @parameters mcr.microsoft.com/cosmosdb/windows/azure-cosmos-emulator
导航到 https://localhost:8081/_explorer/index.html
以访问数据资源管理器。
在 Windows“开始菜单”中选择应用程序,启动模拟器。
或者,可以在 %ProgramFiles%\Azure Cosmos DB Emulator
路径启动模拟器的可执行文件 (Microsoft.Azure.Cosmos.Emulator.exe
)。
此外,还可以从命令行启动模拟器。 使用以下参数来配置模拟器:
|
说明 |
Port |
用于 API for NoSQL 终结点的端口号。 |
Microsoft.Azure.Cosmos.Emulator.exe /Port=65000
注意
有关命令行参数的详细信息,请参阅 命令行参数。
模拟器使用 URL https://localhost:8081/_explorer/index.html
自动打开数据资源管理器。
使用容器映像和以下配置来运行新容器:
|
说明 |
AZURE_COSMOS_EMULATOR_ENABLE_MONGODB_ENDPOINT |
指定要使用的 MongoDB 终结点版本。 支持的终结点包括:3.2 、3.6 或 4.0 。 |
(可选)AZURE_COSMOS_EMULATOR_PARTITION_COUNT |
指定要使用的分区数。 |
(可选)AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE |
在模拟器运行间隙启用数据持久性。 |
(可选)AZURE_COSMOS_EMULATOR_IP_ADDRESS_OVERRIDE |
替代模拟器的默认 IP 地址。 |
对于 Linux 系统,请使用:
docker run \
--publish 8081:8081 \
--publish 10250:10250 \
--env AZURE_COSMOS_EMULATOR_ENABLE_MONGODB_ENDPOINT=4.0 \
--name linux-emulator \
--detach \
mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:mongodb
对于 Windows 系统,请使用:
$parameters = @(
"--publish", "8081:8081"
"--publish", "10250:10250"
"--env", "AZURE_COSMOS_EMULATOR_ENABLE_MONGODB_ENDPOINT=4.0"
"--name", "windows-emulator"
"--detach"
)
docker run @parameters mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:mongodb
导航到 https://localhost:8081/_explorer/index.html
以访问数据资源管理器。
Docker (Windows) 容器映像不支持 API for MongoDB。
在 %ProgramFiles%\Azure Cosmos DB Emulator
路径上启动模拟器的可执行文件 (Microsoft.Azure.Cosmos.Emulator.exe
)。 使用以下参数来配置模拟器:
|
说明 |
EnableMongoDbEndpoint |
在指定的 MongoDB 版本中启用 API for MongoDB 终结点。 |
MongoPort |
用于终结点的端口号。 |
Microsoft.Azure.Cosmos.Emulator.exe /EnableMongoDbEndpoint=4.0 /MongoPort=65200
注意
有关模拟器支持的命令行参数和 MongoDB 版本的详细信息,请参阅命令行参数。
模拟器使用 URL https://localhost:8081/_explorer/index.html
自动打开数据资源管理器。
导入模拟器的 TLS/SSL 证书
导入模拟器的 TLS/SSL 证书,以便在客户端不禁用 TLS/SSL的情况下将模拟器与首选开发人员 SDK 一起使用。
模拟器的 Docker 容器变体(Linux 或 Windows)不支持 API for Apache Cassandra、API for Apache Gremlin 或 API for Table。
仿真器的 Windows 本地安装会自动导入 TLS/SSL 证书。 无需进一步操作。
模拟器的证书位于正在运行的容器上的 _explorer/emulator.pem
路径中。 使用 curl
可将证书从正在运行的容器下载到本地计算机。
从正在运行的容器获取证书。
对于 Linux 系统,请使用:
curl --insecure https://localhost:8081/_explorer/emulator.pem > ~/emulatorcert.crt
对于 Windows 系统,请使用:
$parameters = @{
Uri = 'https://localhost:8081/_explorer/emulator.pem'
Method = 'GET'
OutFile = 'emulatorcert.crt'
SkipCertificateCheck = $True
}
Invoke-WebRequest @parameters
使用适用于操作系统的相应命令重新生成证书捆绑包。
对于基于 Debian 的 Linux 系统(例如 Ubuntu),请使用:
sudo update-ca-certificates
对于基于 Red Hat 的 Linux 系统(例如 CentOS、Fedora),请使用:
sudo update-ca-trust
对于 Windows 系统,请使用:
certutil -f -addstore "Root" ~/emulatorcert.crt
有关详细说明,请参阅特定于你的操作系统的文档。
Docker (Windows) 容器映像不支持 API for MongoDB。
仿真器的 Windows 本地安装会自动导入 TLS/SSL 证书。 无需进一步操作。
模拟器的证书位于正在运行的容器上的 /_explorer/emulator.pem
路径中。
从正在运行的容器将证书下载到本地计算机。
对于 Linux 系统,请使用:
curl --insecure https://localhost:8081/_explorer/emulator.pem > ~/emulatorcert.crt
对于 Windows 系统,请使用:
$parameters = @{
Uri = 'https://localhost:8081/_explorer/emulator.pem'
Method = 'GET'
OutFile = 'emulatorcert.crt'
SkipCertificateCheck = $True
}
Invoke-WebRequest @parameters
注意
如果以前修改过主机(或 IP 地址)和端口号,则可能需要更改这些值。
按照通常用于操作系统的过程安装证书。 例如,在 Linux 中,将证书复制到 /usr/local/share/ca-certificates/
路径。
对于 Linux 系统,请使用:
cp ~/emulatorcert.crt /usr/local/share/ca-certificates/
对于 Windows 系统,请使用:
$parameters = @{
FilePath = 'emulatorcert.crt'
CertStoreLocation = 'Cert:\CurrentUser\Root'
}
Import-Certificate @parameters
对于 Linux 系统,使用适用于 Linux 发行版的相应命令重新生成证书捆绑包。
对于基于 Debian 的 Linux 系统(例如 Ubuntu),请使用:
sudo update-ca-certificates
对于基于 Red Hat 的 Linux 系统(例如 CentOS、Fedora),请使用:
sudo update-ca-trust
有关详细说明,请参阅特定于你的操作系统的文档。
模拟器的证书位于正在运行的容器上的 C:\CosmosDB.Emulator\bind-mount
文件夹中。 该文件夹还包含用于自动安装证书的脚本。
使用 docker cp
将整个文件夹复制到本地计算机。
docker cp windows-emulator:C:\CosmosDB.Emulator\bind-mount .
在文件夹中运行 importcert.ps1 脚本。
.\bind-mount\importcert.ps1
仿真器的 Windows 本地安装会自动导入 TLS/SSL 证书。 无需进一步操作。
从 SDK 连接到仿真器
每个 SDK 都包含一个客户端类,通常用于将 SDK 连接到 Azure Cosmos DB 帐户。 使用模拟器的凭据,可以改为将 SDK 连接到模拟器实例。
使用 Azure Cosmos DB API for NoSQL .NET SDK 从 .NET 应用程序连接到模拟器。
从空文件夹开始。
创建新的 .NET 控制台应用程序
dotnet new console
从 NuGet 添加 Microsoft.Azure.Cosmos
包。
dotnet add package Microsoft.Azure.Cosmos
打开 Program.cs 文件。
删除文件中的任何现有内容。
为 Microsoft.Azure.Cosmos
命名空间添加一个 using 块。
using Microsoft.Azure.Cosmos;
使用模拟器的凭据创建 CosmosClient 的新实例。
using CosmosClient client = new(
accountEndpoint: "https://localhost:8081/",
authKeyOrResourceToken: "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
);
使用 CreateDatabaseIfNotExistsAsync 和 CreateContainerIfNotExistsAsync 创建新的数据库和容器。
Database database = await client.CreateDatabaseIfNotExistsAsync(
id: "cosmicworks",
throughput: 400
);
Container container = await database.CreateContainerIfNotExistsAsync(
id: "products",
partitionKeyPath: "/id"
);
使用 UpsertItemAsync 在容器中创建新项。
var item = new
{
id = "68719518371",
name = "Kiama classic surfboard"
};
await container.UpsertItemAsync(item);
运行 .NET 应用程序。
dotnet run
警告
如果收到 SSL 错误,可能需要为应用程序禁用 TLS/SSL。 如果在本地计算机上进行开发,在容器中使用 Azure Cosmos DB 模拟器,并且尚未导入容器的 SSL 证书,则通常会发生这种情况。 要解决此问题,请在创建客户端之前配置客户端选项,禁用 TLS/SSL 验证:
CosmosClientOptions options = new ()
{
HttpClientFactory = () => new HttpClient(new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
}),
ConnectionMode = ConnectionMode.Gateway,
};
using CosmosClient client = new(
...,
...,
clientOptions: options
);
使用 Azure Cosmos DB API for NoSQL Python SDK 从 Python 应用程序连接到模拟器。
从空文件夹开始。
从 Python 包索引导入 azure-cosmos
包。
pip install azure-cosmos
创建 app.py 文件。
从 azure.cosmos
模块导入 CosmosClient
和 PartitionKey
。
from azure.cosmos import CosmosClient, PartitionKey
使用模拟器的凭据创建新的 CosmosClient。
client = CosmosClient(
url="<https://localhost:8081>",
credential=(
"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGG"
"yPMbIZnqyMsEcaGQy67XIw/Jw=="
),
)
使用 create_database_if_not_exists 和 create_container_if_not_exists 创建新的数据库和容器。
database = client.create_database_if_not_exists(
id="cosmicworks",
offer_throughput=400,
)
container = database.create_container_if_not_exists(
id="products",
partition_key=PartitionKey(
path="/id",
),
)
使用 upsert_item 在容器中创建新项。
item = {"id": "68719518371", "name": "Kiama classic surfboard"}
container.upsert_item(item)
运行 Python 应用程序。
python app.py
警告
如果收到 SSL 错误,则可能需要为应用程序禁用 TLS/SSL。 如果在本地计算机上进行开发,在容器中使用 Azure Cosmos DB 模拟器,并且尚未导入容器的 SSL 证书,则通常会发生这种情况。 要解决此问题,请在创建客户端之前配置应用程序,禁用 TLS/SSL 验证:
import urllib3
urllib3.disable_warnings()
如果仍然遇到 SSL 错误,则可能 Python 正在从其他证书存储中检索证书。 若要确定 Python 查找证书的路径,请执行以下步骤:
重要
如果使用 Python 虚拟环境 (venv),请务必在运行命令之前激活环境!
打开终端
根据 Python 版本键入 python 或 python3,启动 Python 解释器。
在 Python 解释器中运行以下命令:
from requests.utils import DEFAULT_CA_BUNDLE_PATH
print(DEFAULT_CA_BUNDLE_PATH)
在虚拟环境中,路径可能是(至少在 Ubuntu 中):
path/to/venv/lib/pythonX.XX/site-packages/certifi/cacert.pem
在虚拟环境外,路径可能是(至少在 Ubuntu 中):
/etc/ssl/certs/ca-certificates.crt
找到 DEFAULT_CA_BUNDLE_PATH 后,打开新终端并运行以下命令,将模拟器证书附加到证书捆绑包中:
重要
如果 DEFAULT_CA_BUNDLE_PATH 变量指向系统目录,则可能会遇到“权限被拒绝”错误。 在这种情况下,需要使用提升的权限(以 root 身份)运行命令。 此外,在执行提供的命令后,还需要更新和重新生成证书捆绑包。
# Add a new line to the certificate bundle
echo >> /path/to/ca_bundle
# Append the emulator certificate to the certificate bundle
cat /path/to/emulatorcert.crt >> /path/to/ca_bundle
使用 Azure Cosmos DB API for NoSQL Node.js SDK 从 Node.js/JavaScript 应用程序连接到模拟器。
从空文件夹开始。
初始化新模块。
npm init es6 --yes
从节点包管理器安装 @azure/cosmos
包。
npm install --save @azure/cosmos
创建 app.js 文件。
从 @azure/cosmos
模块导入 CosmosClient
类型。
import { CosmosClient } from '@azure/cosmos'
使用 CosmosClient
通过模拟器的凭据创建新客户端实例。
const cosmosClient = new CosmosClient({
endpoint: 'https://localhost:8081/',
key: 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=='
})
使用 Databases.createIfNotExists
和 Containers.createIfNotExists
创建数据库和容器。
const { database } = await cosmosClient.databases.createIfNotExists({
id: 'cosmicworks',
throughput: 400
})
const { container } = await database.containers.createIfNotExists({
id: 'products',
partitionKey: {
paths: [
'/id'
]
}
})
使用 Items.upsert
更新插入新项。
const item = {
id: '68719518371',
name: 'Kiama classic surfboard'
}
container.items.upsert(item)
运行 Node.js 应用程序。
node app.js
警告
如果收到 SSL 错误,可能需要为应用程序禁用 TLS/SSL。 如果在本地计算机上进行开发,在容器中使用 Azure Cosmos DB 模拟器,并且尚未导入容器的 SSL 证书,则通常会发生这种情况。 要解决此问题,请在创建客户端之前配置应用程序,禁用 TLS/SSL 验证:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0
使用 MongoDB .NET 驱动程序 从 .NET 应用程序连接到模拟器。
从空文件夹开始。
创建新的 .NET 控制台应用程序
dotnet new console
从 NuGet 添加 MongoDB.Driver
包。
dotnet add package MongoDB.Driver
打开 Program.cs 文件。
删除文件中的任何现有内容。
为 MongoDB.Driver
命名空间添加一个 using 块。
using MongoDB.Driver;
使用模拟器的凭据创建 MongoClient
的新实例。
var client = new MongoClient(
"mongodb://localhost:C2y6yDjf5%2FR%2Bob0N8A7Cgv30VRDJIWEHLM%2B4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw%2FJw%3D%3D@localhost:10255/admin?ssl=true&retrywrites=false"
);
使用 GetDatabase
和 GetCollection<>
获取数据库和容器。
var database = client.GetDatabase("cosmicworks");
var collection = database.GetCollection<dynamic>("products");
使用 InsertOneAsync
在 XXX 中创建新项。
var item = new
{
name = "Kiama classic surfboard"
};
await collection.InsertOneAsync(item);
运行 .NET 应用程序。
dotnet run
使用 MongoDB Python 驱动程序 从 Python 应用程序连接到模拟器。
从空文件夹开始。
从 Python 包索引导入 pymongo
包。
pip install pymongo
创建 app.py 文件。
导入 os
、sys
和 pymongo
模块。
import pymongo
使用模拟器的凭据创建新的 MongoClient
。
client = pymongo.MongoClient(
host=(
"mongodb://localhost:C2y6yDjf5%2FR%2Bob0N8A7Cgv30VRDJIWEHLM%2B4QDU5DE2"
"nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw%2FJw%3D%3D@localhost:10255/a"
"dmin?ssl=true"
),
tls=True,
)
将 list_database_names
和 list_collection_names
与 CreateDatabase
和 CreateCollection
自定义命令搭配使用,创建新的数据库和容器。
db = client["cosmicworks"]
if "cosmicworks" not in client.list_database_names():
db.command(
{
"customAction": "CreateDatabase",
"offerThroughput": 400,
}
)
collection = db["products"]
if "products" not in db.list_collection_names():
db.command({"customAction": "CreateCollection", "collection": "products"})
使用 update_one
在容器中创建新项。
item = {"id": "68719518371", "name": "Kiama classic surfboard"}
collection.update_one(
filter={"id": item["id"]}, update={"$set": item}, upsert=True
)
运行 Python 应用程序。
python app.py
使用 MongoDB Node.js 驱动程序 从 Node.js/JavaScript 应用程序连接到模拟器。
从空文件夹开始。
初始化新模块。
npm init es6 --yes
从节点包管理器安装 mongodb
包。
npm install --save mongodb
创建 app.js 文件。
从 mongodb
模块导入 MongoClient
类型。
import { MongoClient } from 'mongodb'
使用 MongoClient
通过模拟器的凭据创建新客户端实例。 使用 connect
连接到模拟器。
const client = new MongoClient(
'mongodb://localhost:C2y6yDjf5%2FR%2Bob0N8A7Cgv30VRDJIWEHLM%2B4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw%2FJw%3D%3D@localhost:10255/admin?ssl=true&retrywrites=false'
)
await client.connect()
使用 db
和 collection
创建数据库和容器。
const database = client.db('cosmicworks')
const collection = database.collection('products')
使用 insertOne
创建新项。
const item = {
name: 'Kiama classic surfboard'
}
await collection.insertOne(item)
运行 Node.js 应用程序。
node app.js
警告
如果收到 SSL 错误,可能需要为应用程序禁用 TLS/SSL。 如果在本地计算机上进行开发,在容器中使用 Azure Cosmos DB 模拟器,并且尚未导入容器的 SSL 证书,则通常会发生这种情况。 要解决此问题,请在创建客户端之前配置应用程序,禁用 TLS/SSL 验证:
const client = new MongoClient(
...,
{ tlsAllowInvalidCertificates: true }
)
使用 Apache Cassandra .NET 驱动程序 从 .NET 应用程序连接到模拟器。
从空文件夹开始。
创建新的 .NET 控制台应用程序
dotnet new console
从 NuGet 添加 CassandraCSharpDriver
包。
dotnet add package CassandraCSharpDriver
打开 Program.cs 文件。
删除文件中的任何现有内容。
为 Cassandra
命名空间添加一个 using 块。
using Cassandra;
使用模拟器的凭据创建 Cluster
的新实例。 使用 Connect
新建会话。
var options = new SSLOptions(
sslProtocol: System.Security.Authentication.SslProtocols.Tls12,
checkCertificateRevocation: true,
remoteCertValidationCallback: (_, _, _, policyErrors) => policyErrors == System.Net.Security.SslPolicyErrors.None);
using var cluster = Cluster.Builder()
.WithCredentials(
username: "localhost",
password: "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
)
.WithPort(
port: 10350
)
.AddContactPoint(
address: "localhost"
)
.WithSSL(
sslOptions: options
)
.Build();
using var session = cluster.Connect();
使用 PrepareAsync
和 ExecuteAsync
创建新的数据库和容器。
var createKeyspace = await session.PrepareAsync("CREATE KEYSPACE IF NOT EXISTS cosmicworks WITH replication = {'class':'basicclass', 'replication_factor': 1};");
await session.ExecuteAsync(createKeyspace.Bind());
var createTable = await session.PrepareAsync("CREATE TABLE IF NOT EXISTS cosmicworks.products (id text PRIMARY KEY, name text)");
await session.ExecuteAsync(createTable.Bind());
使用 ExecuteAsync
在表中创建新项。 使用 Bind
为项分配属性。
var item = new
{
id = "68719518371",
name = "Kiama classic surfboard"
};
var createItem = await session.PrepareAsync("INSERT INTO cosmicworks.products (id, name) VALUES (?, ?)");
var createItemStatement = createItem.Bind(item.id, item.name);
await session.ExecuteAsync(createItemStatement);
运行 .NET 应用程序。
dotnet run
使用 Apache Cassandra Python 驱动程序 从 Python 应用程序连接到模拟器。
从空文件夹开始。
从 Python 包索引导入 cassandra-driver
包。
pip install cassandra-driver
创建 app.py 文件。
从 ssl
模块导入 PROTOCOL_TLS_CLIENT
、SSLContext
和 CERT_NONE
模块。 然后,从 cassandra.cluster
模块导入 Cluster
。 最后,从 cassandra.auth
模块导入 PlainTextAuthProvider
。
from ssl import PROTOCOL_TLS_CLIENT, SSLContext, CERT_NONE
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
使用 SSLContext
创建新的 TLS/SSL 上下文变量。 将上下文配置为不验证模拟器的自签名证书。
ssl_context = SSLContext(PROTOCOL_TLS_CLIENT)
ssl_context.check_hostname = False
ssl_context.verify_mode = CERT_NONE
使用模拟器的凭据 PlainTextAuthProvider
、Cluster
和 cluster.connect()
创建新的 session
。
auth_provider = PlainTextAuthProvider(
username="localhost",
password=(
"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnq"
"yMsEcaGQy67XIw/Jw=="
),
)
cluster = Cluster(
["localhost"],
port="10350",
auth_provider=auth_provider,
ssl_context=ssl_context,
)
session = cluster.connect()
使用 session.execute
创建新的密钥空间和表。
session.execute(
"CREATE KEYSPACE IF NOT EXISTS cosmicworks WITH replication = {'class':'ba"
"sicclass', 'replication_factor': 1};"
)
session.execute(
"CREATE TABLE IF NOT EXISTS cosmicworks.products (id text PRIMARY KEY, nam"
"e text)"
)
使用 session.execute
在表中创建新项。
item = {"id": "68719518371", "name": "Kiama classic surfboard"}
session.execute(
"INSERT INTO cosmicworks.products (id, name) VALUES (%s, %s)",
[item["id"], item["name"]],
)
运行 Python 应用程序。
python app.py
使用 Apache Cassandra Node.js 驱动程序,从 Node.js/JavaScript 应用程序中使用模拟器。
从空文件夹开始。
初始化新模块。
npm init es6 --yes
从节点包管理器安装 cassandra-driver
包。
npm install --save cassandra-driver
创建 app.js 文件。
从 cassandra-driver
模块导入 Client
类型和 auth
命名空间。
import { Client, auth } from 'cassandra-driver'
使用 PlainTextAuthProvider
为模拟器的凭据创建新对象。 使用 Client
通过凭据连接到模拟器。
const credentials = new auth.PlainTextAuthProvider(
'localhost',
'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=='
)
const client = new Client({
contactPoints: [
'localhost:10350'
],
authProvider: credentials,
localDataCenter: 'South Central US'
})
使用 execute
在服务器端运行命令,以创建密钥空间和表。
await client.execute(
'CREATE KEYSPACE IF NOT EXISTS cosmicworks WITH replication = {\'class\':\'basicclass\', \'replication_factor\': 1};'
)
await client.execute(
'CREATE TABLE IF NOT EXISTS cosmicworks.products (id text PRIMARY KEY, name text)'
)
再次使用 execute
,创建具有参数的新项。
const item = {
id: '68719518371',
name: 'Kiama classic surfboard'
}
await client.execute(
'INSERT INTO cosmicworks.products (id, name) VALUES (?, ?)',
[
item.id,
item.name
]
)
运行 Node.js 应用程序。
node app.js
警告
如果收到 SSL 错误,可能需要为应用程序禁用 TLS/SSL。 如果在本地计算机上进行开发,在容器中使用 Azure Cosmos DB 模拟器,并且尚未导入容器的 SSL 证书,则通常会发生这种情况。 要解决此问题,请将客户端配置为禁用 TLS/SSL 验证:
const client = new Client({
...,
...,
...,
sslOptions: {
rejectUnauthorized: false
}
})
重要
在启动之前,API for Apache Gremlin 要求你在模拟器中创建资源。 创建名为 db1
的数据库和名为 coll1
的容器。 吞吐量设置与本指南无关,可以随意设置。
使用 Apache Gremlin .NET 驱动程序 从 .NET 应用程序连接到模拟器。
从空文件夹开始。
创建新的 .NET 控制台应用程序
dotnet new console
从 NuGet 添加 Gremlin.Net
包。
dotnet add package Gremlin.Net
打开 Program.cs 文件。
删除文件中的任何现有内容。
为 Gremlin.Net.Driver
命名空间添加一个 using 块。
using Gremlin.Net.Driver;
使用模拟器的凭据创建 GremlinServer
和 GremlinClient
的新实例。
var server = new GremlinServer(
hostname: "localhost",
port: 65400,
username: "/dbs/db1/colls/coll1",
password: "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
);
using var client = new GremlinClient(
gremlinServer: server,
messageSerializer: new Gremlin.Net.Structure.IO.GraphSON.GraphSON2MessageSerializer()
);
使用 SubmitAsync
清理图形。
await client.SubmitAsync(
requestScript: "g.V().drop()"
);
再次使用 SubmitAsync
,可使用指定参数向图形添加新项。
await client.SubmitAsync(
requestScript: "g.addV('product').property('id', prop_id).property('name', prop_name)",
bindings: new Dictionary<string, object>
{
{ "prop_id", "68719518371" },
{ "prop_name", "Kiama classic surfboard" }
}
);
运行 .NET 应用程序。
dotnet run
使用 Apache Gremlin Python 驱动程序 从 Python 应用程序连接到模拟器。
从空文件夹开始。
从 Python 包索引导入 gremlinpython
包。
pip install gremlinpython
创建 app.py 文件。
从 gremlin_python.driver
模块导入 client
。
from gremlin_python.driver import client
使用模拟器的凭据创建新的 Client
。
client = client.Client(
url="ws://localhost:8901/",
traversal_source="g",
username="/dbs/db1/colls/coll1",
password=(
"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnq"
"yMsEcaGQy67XIw/Jw=="
),
)
使用 client.submit
清理图形。
client.submit(message="g.V().drop()")
再次使用 client.submit
,可使用指定参数向图形添加新项。
client.submit(
message=(
"g.addV('product').property('id', prop_id).property('name', prop_name)"
),
bindings={
"prop_id": "68719518371",
"prop_name": "Kiama classic surfboard",
},
)
运行 Python 应用程序。
python app.py
使用 Apache Gremlin Node.js 驱动程序,从 Node.js/JavaScript 应用程序中使用模拟器。
从空文件夹开始。
初始化新模块。
npm init es6 --yes
从节点包管理器安装 gremlin
包。
npm install --save gremlin
创建 app.js 文件。
导入 gremlin
模块。
import gremlin from 'gremlin'
使用 PlainTextSaslAuthenticator
为模拟器的凭据创建新对象。 使用 Client
通过凭据连接到模拟器。
const credentials = new gremlin.driver.auth.PlainTextSaslAuthenticator(
'/dbs/db1/colls/coll1',
'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=='
)
const client = new gremlin.driver.Client(
'ws://localhost:8901/',
{
credentials,
traversalsource: 'g',
rejectUnauthorized: false,
mimeType: 'application/vnd.gremlin-v2.0+json'
}
)
client.open()
如果图形已有数据,使用 submit
在服务器端运行命令以清除图形。
await client.submit('g.V().drop()')
再次使用 submit
,可使用指定参数向图形添加新项。
await client.submit(
'g.addV(\'product\').property(\'id\', prop_id).property(\'name\', prop_name)', {
prop_id: '68719518371',
prop_name: 'Kiama classic surfboard'
}
)
运行 Node.js 应用程序。
node app.js
使用 适用于 .NET 的 Azure Tables SDK 从 .NET 应用程序连接到模拟器。
从空文件夹开始。
创建新的 .NET 控制台应用程序
dotnet new console
从 NuGet 添加 Azure.Data.Tables
包。
dotnet add package Azure.Data.Tables
打开 Program.cs 文件。
删除文件中的任何现有内容。
为 Azure.Data.Tables
命名空间添加一个 using 块。
using Azure.Data.Tables;
使用模拟器的凭据创建 TableServiceClient
的新实例。
var serviceClient = new TableServiceClient(
connectionString: "DefaultEndpointsProtocol=http;AccountName=localhost;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==;TableEndpoint=http://localhost:8902/;"
);
使用 GetTableClient
创建带有表名称的 TableClient
的新实例。 然后使用 CreateIfNotExistsAsync
确保表存在。
var client = serviceClient.GetTableClient(
tableName: "cosmicworksproducts"
);
await client.CreateIfNotExistsAsync();
为项创建新 record
类型。
public record Product : Azure.Data.Tables.ITableEntity
{
public required string RowKey { get; set; }
public required string PartitionKey { get; set; }
public required string Name { get; init; }
public Azure.ETag ETag { get; set; }
public DateTimeOffset? Timestamp { get; set; }
}
使用 UpsertEntityAsync
和 Replace
模式在表中创建新项。
var item = new Product
{
RowKey = "68719518371",
PartitionKey = "Surfboards",
Name = "Kiama classic surfboard",
Timestamp = DateTimeOffset.Now
};
await client.UpsertEntityAsync(
entity: item,
mode: TableUpdateMode.Replace
);
运行 .NET 应用程序。
dotnet run
使用 Azure Tables Python SDK 从 Python 应用程序连接到模拟器。
从空文件夹开始。
从 Python 包索引导入 azure-data-tables
包。
pip install azure-data-tables
创建 app.py 文件。
从 azure.data.tables
模块导入 TableServiceClient
和 UpdateMode
。
from azure.data.tables import TableServiceClient, UpdateMode
使用 TableServiceClient.from_connection_string
新建服务级别客户端。
service = TableServiceClient.from_connection_string(
conn_str=(
"DefaultEndpointsProtocol=http;AccountName=localhost;AccountKey=C2y6yD"
"jf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEca"
"GQy67XIw/Jw==;TableEndpoint=http://localhost:8902/;"
)
)
使用 create_table_if_not_exists
新建表级客户端。
client = service.create_table_if_not_exists(table_name="cosmicworksproducts")
使用 upsert_entity
在容器中创建新项。
item = {
"PartitionKey": "68719518371",
"RowKey": "Surfboards",
"name": "Kiama classic surfboard",
}
client.upsert_entity(entity=item, mode=UpdateMode.REPLACE)
运行 Python 应用程序。
python app.py
使用 Azure Tables JavaScript SDK 从 Node.js/JavaScript 应用程序中使用模拟器。
从空文件夹开始。
初始化新模块。
npm init es6 --yes
从节点包管理器安装 @azure/data-tables
包。
npm install --save @azure/data-tables
创建 app.js 文件。
从 @azure/data-tables
模块导入 TableClient
类型。
import { TableClient } from '@azure/data-tables'
使用 TableClient.fromConnectionString
通过模拟器的连接字符串创建新客户端实例。
const client = TableClient.fromConnectionString(
'DefaultEndpointsProtocol=http;AccountName=localhost;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==;TableEndpoint=http://localhost:8902/;',
'cosmicworksproducts'
)
如果新表尚不存在,请使用 createTable
创建一个。
await client.createTable()
使用 upsertEntity
创建或替换项。
const item = {
partitionKey: '68719518371',
rowKey: 'Surfboards',
name: 'Kiama classic surfboard'
}
await client.upsertEntity(
item,
'Replace'
)
运行 Node.js 应用程序。
node app.js
警告
如果收到 SSL 错误,可能需要为应用程序禁用 TLS/SSL。 如果在本地计算机上进行开发,在容器中使用 Azure Cosmos DB 模拟器,并且尚未导入容器的 SSL 证书,则通常会发生这种情况。 要解决此问题,请将客户端配置为禁用 TLS/SSL 验证:
const client = TableClient.fromConnectionString(
...,
...,
{
allowInsecureConnection: true
}
)
在 GitHub Actions CI 工作流中使用模拟器
若要运行可自动验证应用程序的持续集成工作负载,请将 Azure Cosmos DB 模拟器与所选框架的测试套件配合使用。 GitHub Action 的托管运行器的 windows-latest
变体中预装了Azure Cosmos DB 模拟器。
使用 .NET 内置测试驱动程序和测试框架(如 MSTest、 NUnit 或 XUnit)来运行测试套件。
验证应用程序的单元测试套件是否按预期运行。
dotnet test
在 GitHub 存储库中创建新工作流,文件名为 .github/workflows/ci.yml
。
将作业添加到工作流,以便使用 PowerShell 启动 Azure Cosmos DB 模拟器并运行单元测试套件。
name: Continuous Integration
on:
push:
branches:
- main
jobs:
unit_tests:
name: Run .NET unit tests
runs-on: windows-latest
steps:
- name: Checkout (GitHub)
uses: actions/checkout@v3
- name: Start Azure Cosmos DB emulator
run: |
Write-Host "Launching Cosmos DB Emulator"
Import-Module "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules\Microsoft.Azure.CosmosDB.Emulator"
Start-CosmosDbEmulator
- name: Run .NET tests
run: dotnet test
注意
使用各种参数或 PowerShell 命令从命令行启动模拟器。 有关详细信息,请参阅 模拟器命令行参数。
使用 pytest
测试 Python 应用程序和数据库操作。
验证应用程序的单元测试套件是否按预期运行。
pip install -U pytest
pytest
在 GitHub 存储库中创建新工作流,文件名为 .github/workflows/ci.yml
。
将作业添加到工作流,以便使用 PowerShell 启动 Azure Cosmos DB 模拟器并运行单元测试套件。
name: Continuous Integration
on:
push:
branches:
- main
jobs:
unit_tests:
name: Run Python unit tests
runs-on: windows-latest
steps:
- name: Checkout (GitHub)
uses: actions/checkout@v3
- name: Start Azure Cosmos DB emulator
run: |
Write-Host "Launching Cosmos DB Emulator"
Import-Module "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules\Microsoft.Azure.CosmosDB.Emulator"
Start-CosmosDbEmulator
- name: Install test runner
run: pip install pytest
- name: Run Python tests
run: pytest
注意
使用各种参数或 PowerShell 命令从命令行启动模拟器。 有关详细信息,请参阅 模拟器命令行参数。
使用 mocha
测试 Node.js 应用程序及其数据库修改。
验证应用程序的单元测试套件是否按预期运行。
npm install --global mocha
mocha
在 GitHub 存储库中创建新工作流,文件名为 .github/workflows/ci.yml
。
将作业添加到工作流,以便使用 PowerShell 启动 Azure Cosmos DB 模拟器并运行单元测试套件。
name: Continuous Integration
on:
push:
branches:
- main
jobs:
unit_tests:
name: Run Node.js unit tests
runs-on: windows-latest
steps:
- name: Checkout (GitHub)
uses: actions/checkout@v3
- name: Start Azure Cosmos DB emulator
run: |
Write-Host "Launching Cosmos DB Emulator"
Import-Module "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules\Microsoft.Azure.CosmosDB.Emulator"
Start-CosmosDbEmulator
- name: Install test runner
run: npm install --global mocha
- name: Run Node.js tests
run: mocha
注意
使用各种参数或 PowerShell 命令从命令行启动模拟器。 有关详细信息,请参阅 模拟器命令行参数。
后续步骤