快速入门:将 Azure Cache for Redis 与 Rust 配合使用Quickstart: Use Azure Cache for Redis with Rust

本文将介绍如何使用 Rust 编程语言来与 Azure Cache for Redis 交互。In this article, you will learn how to use the Rust programming language for interacting with Azure Cache for Redis. 本文还会演示常用的 Redis 数据结构示例,如字符串哈希列表等。It will demonstrate examples of commonly used Redis data structures such as String, Hash, List etc. 使用 Redis 的 redis-rs 库。using the redis-rs library for Redis. 此客户端公开高级别和低级别 API,可利用本文提供的示例代码了解这两种样式的实际应用。This client exposes both high and low-level APIs and you will see both these styles in action with the help of sample code presented in this article.

跳到 GitHub 上的代码Skip to the code on GitHub

如果要直接跳到代码,请参阅 GitHub 上的 Rust 快速入门If you want to skip straight to the code, see the Rust quickstart on GitHub.

先决条件Prerequisites

创建用于 Redis 的 Azure 缓存实例Create an Azure Cache for Redis instance

  1. 若要创建缓存,请登录到 Azure 门户并选择“创建资源” 。To create a cache, sign in to the Azure portal and select Create a resource.

    左侧导航窗格中突出显示了“创建资源”。

  2. 在“新建”页上选择“数据库”,然后选择“Azure Cache for Redis”。On the New page, select Databases and then select Azure Cache for Redis.

    在“新建”中,突出显示了“数据库”和“Azure Cache for Redis”。

  3. 在“新建 Redis 缓存”页上配置新缓存的设置。On the New Redis Cache page, configure the settings for your new cache.

    设置Setting 建议的值Suggested value 说明Description
    DNS 名称DNS name 输入任何全局唯一的名称。Enter a globally unique name. 缓存名称必须是包含 1 到 63 个字符的字符串,只能包含数字、字母或连字符。The cache name must be a string between 1 and 63 characters that contains only numbers, letters, or hyphens. 该名称必须以数字或字母开头和结尾,且不能包含连续的连字符。The name must start and end with a number or letter, and can't contain consecutive hyphens. 缓存实例的主机名将是 <DNS name>.redis.cache.chinacloudapi.cnYour cache instance's host name will be <DNS name>.redis.cache.chinacloudapi.cn.
    订阅Subscription 单击下拉箭头并选择你的订阅。Drop down and select your subscription. 要在其下创建此新的 Azure Cache for Redis 实例的订阅。The subscription under which to create this new Azure Cache for Redis instance.
    资源组Resource group 单击下拉箭头并选择一个资源组,或者选择“新建”并输入新的资源组名称。Drop down and select a resource group, or select Create new and enter a new resource group name. 要在其中创建缓存和其他资源的资源组的名称。Name for the resource group in which to create your cache and other resources. 将所有应用资源放入一个资源组可以轻松地统一管理或删除这些资源。By putting all your app resources in one resource group, you can easily manage or delete them together.
    位置Location 单击下拉箭头并选择一个位置。Drop down and select a location. 选择与要使用该缓存的其他服务靠近的区域Select a region near other services that will use your cache.
    定价层Pricing tier 单击下拉箭头并选择一个定价层Drop down and select a Pricing tier. 定价层决定可用于缓存的大小、性能和功能。The pricing tier determines the size, performance, and features that are available for the cache. 有关详细信息,请参阅用于 Redis 的 Azure 缓存概述For more information, see Azure Cache for Redis Overview.
  4. 选择“网络”选项卡,或单击页面底部的“网络”按钮 。Select the Networking tab or click the Networking button at the bottom of the page.

  5. 在“网络”选项卡中,选择你的连接方法。In the Networking tab, select your connectivity method.

  6. 选择页面底部的“下一步:高级”选项卡,或者单击页面底部的“下一步:高级”按钮。Select the Next: Advanced tab or click the Next: Advanced button on the bottom of the page.

  7. 在基本或标准缓存实例的“高级”选项卡中,如果想要启用非 TLS 端口,请选择启用开关。In the Advanced tab for a basic or standard cache instance, select the enable toggle if you want to enable a non-TLS port. 还可以选择你想使用的 Redis 版本,4 或(预览版)6。You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

    Redis 版本 4 或 6。

  8. 在高级缓存实例的“高级”选项卡中,配置非 TLS 端口、群集和数据持久性的设置。In the Advanced tab for premium cache instance, configure the settings for non-TLS port, clustering, and data persistence. 还可以选择你想使用的 Redis 版本,4 或(预览版)6。You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

  9. 选择页面底部的“下一步:标记”选项卡,或者单击“下一步:标记”按钮。Select the Next: Tags tab or click the Next: Tags button at the bottom of the page.

  10. 或者,在“标记”选项卡中,如果希望对资源分类,请输入名称或值。Optionally, in the Tags tab, enter the name and value if you wish to categorize the resource.

  11. 选择“查看 + 创建” 。Select Review + create. 随后你会转到“查看 + 创建”选项卡,Azure 将在此处验证配置。You're taken to the Review + create tab where Azure validates your configuration.

  12. 显示绿色的“已通过验证”消息后,选择“创建”。After the green Validation passed message appears, select Create.

创建缓存需要花费片刻时间。It takes a while for the cache to create. 可以在 Azure Cache for Redis 的“概述”页上监视进度。 You can monitor progress on the Azure Cache for Redis Overview page. 如果“状态”显示为“正在运行”,则表示该缓存可供使用。 When Status shows as Running, the cache is ready to use.

从 Azure 门户检索主机名、端口和访问密钥Retrieve host name, ports, and access keys from the Azure portal

若要连接到某个 Azure Cache for Redis 实例,缓存客户端需要该缓存的主机名、端口和密钥。To connect to an Azure Cache for Redis instance, cache clients need the host name, ports, and a key for the cache. 在某些客户端中,这些项的名称可能略有不同。Some clients might refer to these items by slightly different names. 可以从 Azure 门户检索主机名、端口和访问密钥。You can get the host name, ports, and keys from the Azure portal.

  • 若要获取访问密钥,请在缓存的左侧导航中选择“访问密钥”。 To get the access keys, from your cache left navigation, select Access keys.

    Azure Redis 缓存密钥

  • 若要获取主机名和端口,请在缓存的左侧导航栏中选择“属性”。 To get the host name and ports, from your cache left navigation, select Properties. 主机名的格式为 <DNS 名称>.redis.cache.chinacloudapi.cn 。The host name is of the form <DNS name>.redis.cache.chinacloudapi.cn.

    Azure Redis 缓存属性

查看代码(可选)Review the code (optional)

如果有意了解代码的工作原理,可以查看以下代码片段。If you're interested in learning how the code works, you can review the following snippets. 否则,可以直接跳到运行应用程序Otherwise, feel free to skip ahead to Run the application.

connect 函数用于与 Azure Cache for Redis 建立连接。The connect function is used to establish a connection to Azure Cache for Redis. 它需要分别通过环境变量 REDIS_HOSTNAMEREDIS_PASSWORD 传入主机名和密码(访问密钥)。It expects host name and the password (Access Key) to be passed in via environment variables REDIS_HOSTNAME and REDIS_PASSWORD respectively. 连接 URL 的格式为 rediss://<username>:<password>@<hostname> - Azure Cache for Redis 仅接受以 TLS 1.2 作为所需的最低版本的安全连接。The format for the connection URL is rediss://<username>:<password>@<hostname> - Azure Cache for Redis only accepts secure connections with TLS 1.2 as the minimum required version.

redis::Client::open 的调用会执行基本验证,同时 get_connection() 实际启动连接 - 如果因任何原因(如密码错误)导致连接失败,程序将停止。The call to redis::Client::open performs basic validation while get_connection() actually initiates the connection - the program stops if the connectivity fails due to any reason such as an incorrect password.

fn connect() -> redis::Connection {
    let redis_host_name =
        env::var("REDIS_HOSTNAME").expect("missing environment variable REDIS_HOSTNAME");
    let redis_password =
        env::var("REDIS_PASSWORD").expect("missing environment variable REDIS_PASSWORD");
    let redis_conn_url = format!("rediss://:{}@{}", redis_password, redis_host_name);

    redis::Client::open(redis_conn_url)
        .expect("invalid connection URL")
        .get_connection()
        .expect("failed to connect to redis")
}

basics 函数涵盖 SETGETINCR 命令。The basics function covers SET, GET, and INCR commands. 低级别 API 用于 SETGET,以设置和检索名为 foo 的键的值。The low-level API is used for SET and GET, which sets and retrieves the value for a key named foo. INCRBY 命令是使用高级 API 执行的,即 incr2 为增量递增键(名为 counter)的值,然后调用 get 来检索该值。The INCRBY command is executed using a high-level API i.e. incr increments the value of a key (named counter) by 2 followed by a call to get to retrieve it.

fn basics() {
    let mut conn = connect();
    let _: () = redis::cmd("SET")
        .arg("foo")
        .arg("bar")
        .query(&mut conn)
        .expect("failed to execute SET for 'foo'");

    let bar: String = redis::cmd("GET")
        .arg("foo")
        .query(&mut conn)
        .expect("failed to execute GET for 'foo'");
    println!("value for 'foo' = {}", bar);

    let _: () = conn
        .incr("counter", 2)
        .expect("failed to execute INCR for 'counter'");
    let val: i32 = conn
        .get("counter")
        .expect("failed to execute GET for 'counter'");
    println!("counter = {}", val);
}

以下代码片段演示 Redis HASH 数据结构的功能。The below code snippet demonstrates the functionality of a Redis HASH data structure. 使用低级别 API 调用 HSET,以存储有关 Redis 驱动程序(客户端)的信息(nameversionrepo)。HSET is invoked using the low-level API to store information (name, version, repo) about Redis drivers (clients). 例如,Rust 驱动程序(在此示例代码中使用的驱动程序!)的详细信息以 BTreeMap 的形式捕获,然后传递到低级别 API。For example, details for the Rust driver (one being used in this sample code!) is captured in form of a BTreeMap and then passed on to the low-level API. 然后使用 HGETALL 进行检索。It is then retrieved using HGETALL.

还可使用高级别 API 通过接受元组数组的 hset_multiple 执行 HSETHSET can also be executed using a high-level API using hset_multiple that accepts an array of tuples. 然后执行 hget 以提取单个属性的值(在本例中为 repo)。hget is then executed to fetch the value for a single attribute (the repo in this case).

fn hash() {
    let mut conn = connect();

    let mut driver: BTreeMap<String, String> = BTreeMap::new();
    let prefix = "redis-driver";
    driver.insert(String::from("name"), String::from("redis-rs"));
    driver.insert(String::from("version"), String::from("0.19.0"));
    driver.insert(
        String::from("repo"),
        String::from("https://github.com/mitsuhiko/redis-rs"),
    );

    let _: () = redis::cmd("HSET")
        .arg(format!("{}:{}", prefix, "rust"))
        .arg(driver)
        .query(&mut conn)
        .expect("failed to execute HSET");

    let info: BTreeMap<String, String> = redis::cmd("HGETALL")
        .arg(format!("{}:{}", prefix, "rust"))
        .query(&mut conn)
        .expect("failed to execute HGETALL");
    println!("info for rust redis driver: {:?}", info);

    let _: () = conn
        .hset_multiple(
            format!("{}:{}", prefix, "go"),
            &[
                ("name", "go-redis"),
                ("version", "8.4.6"),
                ("repo", "https://github.com/go-redis/redis"),
            ],
        )
        .expect("failed to execute HSET");

    let repo_name: String = conn
        .hget(format!("{}:{}", prefix, "go"), "repo")
        .expect("HGET failed");
    println!("go redis driver repo name: {:?}", repo_name);
}

在下面的函数中,可了解如何使用 LIST 数据结构。In the function below, you can see how to use a LIST data structure. 通过执行 LPUSH(使用低级别 API)将条目添加到列表,并使用高级别 lpop 方法从列表中检索该条目。LPUSH is executed (with the low-level API) to add an entry to the list and the high-level lpop method is used to retrieve that from the list. 然后使用 rpush 方法将几个条目添加到列表中,然后使用低级别 lrange 方法提取这些条目。Then, the rpush method is used to add a couple of entries to the list which are then fetched using the low-level lrange method.

fn list() {
    let mut conn = connect();
    let list_name = "items";

    let _: () = redis::cmd("LPUSH")
        .arg(list_name)
        .arg("item-1")
        .query(&mut conn)
        .expect("failed to execute LPUSH for 'items'");

    let item: String = conn
        .lpop(list_name)
        .expect("failed to execute LPOP for 'items'");
    println!("first item: {}", item);

    let _: () = conn.rpush(list_name, "item-2").expect("RPUSH failed");
    let _: () = conn.rpush(list_name, "item-3").expect("RPUSH failed");

    let len: isize = conn
        .llen(list_name)
        .expect("failed to execute LLEN for 'items'");
    println!("no. of items in list = {}", len);

    let items: Vec<String> = conn
        .lrange(list_name, 0, len - 1)
        .expect("failed to execute LRANGE for 'items'");

    println!("listing items in list");
    for item in items {
        println!("item: {}", item)
    }
}

可在此处查看一些 SET 操作。Here you can see some of the SET operations. 使用 sadd(高级别 API)方法将几个条目添加到名为 usersSETThe sadd (high-level API) method is used to add couple of entries to a SET named users. 然后执行 SISMEMBER(低级别 API)以检查 user1 是否存在。SISMEMBER is then executed (low-level API) to check whether user1 exists. 最后使用 smembers 以向量 (Vec) 形式提取所有集合条目并对其进行循环访问。Finally, smembers is used to fetch and iterate over all the set entries in the form of a Vector (Vec).

fn set() {
    let mut conn = connect();
    let set_name = "users";

    let _: () = conn
        .sadd(set_name, "user1")
        .expect("failed to execute SADD for 'users'");
    let _: () = conn
        .sadd(set_name, "user2")
        .expect("failed to execute SADD for 'users'");

    let ismember: bool = redis::cmd("SISMEMBER")
        .arg(set_name)
        .arg("user1")
        .query(&mut conn)
        .expect("failed to execute SISMEMBER for 'users'");
    println!("does user1 exist in the set? {}", ismember);

    let users: Vec<String> = conn.smembers(set_name).expect("failed to execute SMEMBERS");
    println!("listing users in set");

    for user in users {
        println!("user: {}", user)
    }
}

下面的 sorted_set 函数演示排序集数据结构。sorted_set function below demonstrates the Sorted Set data structure. 调用 ZADD(使用低级别 API)为播放机(player-1)添加随机整数分数。ZADD is invoked (with the low-level API) to add a random integer score for a player (player-1). 接下来使用 zadd 方法(高级别 API)添加更多播放机(player-2player-5)及其各自(随机生成)的分数。Next, the zadd method (high-level API) is used to add more players (player-2 to player-5) and their respective (randomly generated) scores. 排序集内的条目数是使用 ZCARD 来确定的,它被用作 ZRANGE 命令(使用低级别 API 调用)的限制,以按分数升序列出播放机。The number of entries in the sorted set is figured out using ZCARD and that's used as the limit to the ZRANGE command (invoked with the low-level API) to list out the players with their scores in ascending order.

fn sorted_set() {
    let mut conn = connect();
    let sorted_set = "leaderboard";

    let _: () = redis::cmd("ZADD")
        .arg(sorted_set)
        .arg(rand::thread_rng().gen_range(1..10))
        .arg("player-1")
        .query(&mut conn)
        .expect("failed to execute ZADD for 'leaderboard'");

    for num in 2..=5 {
        let _: () = conn
            .zadd(
                sorted_set,
                String::from("player-") + &num.to_string(),
                rand::thread_rng().gen_range(1..10),
            )
            .expect("failed to execute ZADD for 'leaderboard'");
    }

    let count: isize = conn
        .zcard(sorted_set)
        .expect("failed to execute ZCARD for 'leaderboard'");

    let leaderboard: Vec<(String, isize)> = conn
        .zrange_withscores(sorted_set, 0, count - 1)
        .expect("ZRANGE failed");

    println!("listing players and scores in ascending order");

    for item in leaderboard {
        println!("{} = {}", item.0, item.1)
    }
}

克隆示例应用程序Clone the sample application

首先从 GitHub 克隆应用程序开始。Start by cloning the application from GitHub.

  1. 打开命令提示符,然后创建一个新的名为 git-samples 的文件夹。Open a command prompt and create a new folder named git-samples.

    md "C:\git-samples"
    
  2. 打开 git 终端窗口(例如 git bash)。Open a git terminal window, such as git bash. 使用 cd 命令转到新文件夹,你将在其中克隆示例应用。Use the cd command to change into the new folder where you will be cloning the sample app.

    cd "C:\git-samples"
    
  3. 运行下列命令,克隆示例存储库。Run the following command to clone the sample repository. 此命令在计算机上创建示例应用程序的副本。This command creates a copy of the sample app on your computer.

    git clone https://github.com/Azure-Samples/azure-redis-cache-rust-quickstart.git
    

运行应用程序Run the application

应用程序接受环境变量形式的连接和凭据。The application accepts connectivity and credentials in the form of environment variables.

  1. Azure 门户中为 Azure Cache for Redis 实例提取“主机名”和“访问密钥”(可通过访问密钥获得) 。Fetch the Host name and Access Keys (available via Access Keys) for Azure Cache for Redis instance in the Azure portal.

  2. 将它们设置为相应的环境变量:Set them to the respective environment variables:

    set REDIS_HOSTNAME=<Host name>:<port> (e.g. <name of cache>.redis.cache.chinacloudapi.cn:6380)
    set REDIS_PASSWORD=<Primary Access Key>
    
  3. 在“终端”窗口中,切换到正确的文件夹。In the terminal window, change to the correct folder. 例如:For example:

    cd "C:\git-samples\azure-redis-cache-rust-quickstart"
    
  4. 在终端中,运行以下命令以启动应用程序。In the terminal, run the following command to start the application.

    cargo run
    

    应会看到如下所示的输出:You will see an output as such:

    ******* Running SET, GET, INCR commands *******
    value for 'foo' = bar
    counter = 2
    ******* Running HASH commands *******
    info for rust redis driver: {"name": "redis-rs", "repo": "https://github.com/mitsuhiko/redis-rs", "version": "0.19.0"}
    go redis driver repo name: "https://github.com/go-redis/redis"
    ******* Running LIST commands *******
    first item: item-1
    no. of items in list = 2
    listing items in list
    item: item-2
    item: item-3
    ******* Running SET commands *******
    does user1 exist in the set? true
    listing users in set
    user: user2
    user: user1
    user: user3
    ******* Running SORTED SET commands *******
    listing players and scores
    player-2 = 2
    player-4 = 4
    player-1 = 7
    player-5 = 6
    player-3 = 8
    

    如果要运行特定函数,请在 main 函数中注释禁止其他函数:If you want to run a specific function, comment out other functions in the main function:

    fn main() {
        basics();
        hash();
        list();
        set();
        sorted_set();
    }
    

清理资源Clean up resources

如果已完成在此快速入门中创建的 Azure 资源组和资源,则可以删除它们以避免产生费用。If you're finished with the Azure resource group and resources you created in this quickstart, you can delete them to avoid charges.

重要

删除资源组的操作不可逆,资源组以及其中的所有资源将被永久删除。Deleting a resource group is irreversible, and the resource group and all the resources in it are permanently deleted. 如果在要保留的现有资源组中创建了 Azure Redis 缓存实例,可从缓存“概述”页选择“删除”以便仅删除缓存 。If you created your Azure Cache for Redis instance in an existing resource group that you want to keep, you can delete just the cache by selecting Delete from the cache Overview page.

删除资源组及其 Azure Redis 缓存实例:To delete the resource group and its Redis Cache for Azure instance:

  1. Azure 门户中,搜索并选择“资源组”。From the Azure portal, search for and select Resource groups.

  2. 在“按名称筛选”文本框中,输入包含缓存实例的资源组的名称,然后从搜索结果中选择它。In the Filter by name text box, enter the name of the resource group that contains your cache instance, and then select it from the search results.

  3. 在资源组页上,选择“删除资源组”。On your resource group page, select Delete resource group.

  4. 键入资源组名称,然后选择“删除”。Type the resource group name, and then select Delete.

    删除 Azure Redis 缓存的资源组

后续步骤Next steps

在本快速入门中,你已了解如何使用 Redis 的 Rust 驱动程序在 Azure Cache for Redis 中进行连接和执行操作。In this quickstart, you learned how to use the Rust driver for Redis to connect and execute operations in Azure Cache for Redis.