快速入门:使用适用于 Azure 和 Azure MCP 服务器的GitHub Copilot,使用 Azure Cache for Redis 创建和部署应用

本快速入门介绍如何创建一个简单的Python应用,

  • 连接到 Azure Cache for Redis
  • 将当前日期和时间写入 Redis
  • 读取返回的值
  • 将结果打印到控制台

使用 GitHub Copilot 生成大部分代码和预配步骤。

先决条件

有关完整的设置说明,请参阅入门文章。 请确保准备以下物品:

  • Azure 帐户和对 Azure 订阅的访问权限。 有关如何设置它们的详细信息,请参阅 Azure 帐户的定价页。

  • GitHub 帐户和 GitHub Copilot 订阅。 有关如何设置它们的详细信息,请参阅 在 GitHub 上创建账户GitHub Copilot 快速入门指南

  • Visual Studio Code。 有关如何下载和安装它的详细信息,请参阅 Setting up Visual Studio Code

  • GitHub Copilot扩展和GitHub Copilot聊天扩展。 有关如何安装这些扩展的说明,请参阅在 VS Code 中设置 GitHub Copilot,以及在 VS Code 中开始使用 GitHub Copilot 聊天。

重要

GitHub Copilot 是由 GitHub 管理的单独订阅。 有关 GitHub Copilot 订阅和支持的问题,请参阅 GitHub Copilot 计划入门

重要

GitHub Copilot 是由 GitHub 管理的单独订阅。 有关 GitHub Copilot 订阅和支持的问题,请参阅 GitHub Copilot 计划入门

重要

GitHub Copilot 是由 GitHub 管理的单独订阅。 有关 GitHub Copilot 订阅和支持的问题,请参阅 GitHub Copilot 计划入门

构建应用

请按照本文中所述的步骤操作:

  1. 在工作区中创建 .env 文件,以将Azure部署信息存储为环境变量。
  2. 编写提示以在订阅中创建Azure Cache for Redis实例。 Redis 连接信息也存储在 .env 文件中。
  3. 验证是否已正确创建资源和 .env 文件。
  4. 编写提示以创建Python应用,以使用环境变量从缓存中检索、写入和读取。
  5. 验证应用是否正常工作。
  6. 清理Azure中的资源。

确保已选择正确的工具

必须安装Azure MCP服务器和GitHub Copilot for Azure。

  1. 在聊天窗格中选择 “配置工具...” 图标。
  2. 配置工具 显示在命令面板中。 确保已选中“Azure MCP”和“GitHub Copilot for Azure”的顶级节点。
  1. 在聊天窗格中选择 “选择工具...” 图标。
  2. 将显示“选择工具”菜单。 确保已选择“Azure MCP 服务器”顶部节点。
  1. 在聊天窗格中选择 “选择工具 ”图标。
  2. 将显示 “选择工具” 菜单。 确保同时勾选“Azure”和“Azure MCP”的顶级节点。

创建本地环境变量

常见的开发做法是将重要密钥和其他设置存储为工作区文件夹中的 .env 文件的环境变量。 项目内的所有配置都保持独立。

重要

请确保文件 .gitignore 包含 .env ,以避免无意中将机密信息提交到版本控制。

在此步骤中,使用如下所示的提示在工作区中创建 .env 文件:

Create a .env file in this workspace with the following environment variables filled in:

AZURE_SUBSCRIPTION_ID
AZURE_TENANT_ID
AZURE_LOCATION
AZURE_RESOURCE_GROUP
AZURE_RESOURCE_PREFIX

Use my <your-subscription-name> subscription and I want to put everything in eastus.

<your-subscription-name> 替换为Azure订阅的名称。 Copilot 会为你查找订阅和租户 ID,生成资源组的名称和前缀,并创建.env文件。

创建文件后,打开该文件并验证值是否正确:

AZURE_SUBSCRIPTION_ID=<your-azure-subscription-id>
AZURE_TENANT_ID=<your-azure-tenant-id>
AZURE_LOCATION=eastus
AZURE_RESOURCE_GROUP=<resource-group>
AZURE_RESOURCE_PREFIX=<resource-prefix>

创建Azure Cache for Redis

打开 GitHub Copilot 对话助手并粘贴以下提示:

You have access to Azure MCP tools.

Use the variables in the `.env` file in this workspace to create an Azure Cache for Redis instance.

Tasks:
1. Ensure the resource group exists.
2. Create Azure Cache for Redis:
    - Name: {AZURE_RESOURCE_PREFIX}-redis
    - SKU: Basic C0
    - TLS enabled (port 6380)
3. Write the following values into the `.env` file:
    REDIS_HOST
    REDIS_PORT=6380
    REDIS_PASSWORD (primary key)
    REDIS_SSL=true

Important:
- Use Azure MCP to create resources and fetch keys.

Copilot创建 Redis 资源,然后创建一个包含主机名、主键和其他环境变量的 .env 文件。

验证 .env 文件是否具有 Redis 设置

  1. 打开 .env 项目文件夹中的文件,并验证它是否具有值。

    REDIS_HOST=<your-cache-name>.redis.cache.windows.net
    REDIS_PORT=6380
    REDIS_PASSWORD=<primary-key>
    REDIS_SSL=true
    
  2. 使用以下提示验证Azure Cache for Redis实例是否正在运行。

    Use the values in the `.env` file in this workspace to validate that an instance of Azure Cache for Redis is running and ready to be used.
    

提示编写Python应用

使用以下提示创建一个Python应用程序,该应用程序可以对Azure Cache for Redis的新实例进行写入和读取。

Create a minimal Python console app in this workspace.

Important:
- Do ALL work directly by editing files.
- Do NOT ask me to copy/paste code.
- Create files if they do not exist.

Goal:
Build a simple app that writes the current date/time to Azure Cache for Redis, reads it back, and prints results to the console.

Project requirements:

1. Create or update these files:

- main.py
- requirements.txt
- .gitignore

2. requirements.txt must include:
- redis
- python-dotenv

3. .gitignore must include:
- .venv/
- __pycache__/
- .env

4. main.py must:

- Load environment variables using python-dotenv
- Read:
    REDIS_HOST
    REDIS_PORT
    REDIS_PASSWORD
    REDIS_SSL
- Connect to Azure Cache for Redis using TLS (ssl=True when REDIS_SSL=true)
- Use decode_responses=True
- Test connection with PING and print:
    Connected to Redis
- Write current datetime (ISO format) to key:
    demo:timestamp
- Read the value back
- Print exactly:

    WROTE: <value>
    READ : <value>

- Wrap connection logic in a try/except and print a helpful error message.

5. Keep the code simple and beginner-friendly:
- Single file
- No classes
- About 40–60 lines

After editing the files:
- Show a summary of what you changed.
- Do NOT print the full file contents unless I ask.

验证Python应用

  1. 确保提示中请求的文件存在。 直观地检查文件,以查看文件是否具有看似合理的值。

  2. 检查 main.py 文件,以确保它从 .env 文件中检索值,导入 redis 包,并连接到Azure Cache for Redis。 检查它是否写入并读取缓存。 你可能会看到类似于以下代码的代码:

    
    import os
    from datetime import datetime
    from dotenv import load_dotenv
    import redis
    
    # Load local environment variables
    load_dotenv()
    
    host = os.getenv("REDIS_HOST")
    port = int(os.getenv("REDIS_PORT", "6380"))
    password = os.getenv("REDIS_PASSWORD")
    ssl_enabled = os.getenv("REDIS_SSL", "true").lower() == "true"
    
    try:
        client = redis.Redis(
            host=host,
            port=port,
            password=password,
            ssl=ssl_enabled,
            decode_responses=True
        ) 
    
        # Verify connection
        client.ping()
        print("Connected to Redis")
    
        # Write current time
        now = datetime.now().isoformat()
        client.set("demo:timestamp", now)
        print(f"WROTE: {now}")
    
        # Read value back
        value = client.get("demo:timestamp")
        print(f"READ : {value}")
    
    except Exception as ex:
        print("Connection failed.")
        print(ex)
    

    重要

    AI 辅助软件开发是不确定的,这意味着你不会得到两次生成的相同代码。 但是,在这样的简单应用程序中,基本方法、语法和最终结果应接近,但并不完全相同。

运行应用

在终端中,运行应用:

python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
python main.py

此时会看到与下面类似的输出:

Connected to Redis
WROTE: 2026-03-01T10:22:11.452331
READ : 2026-03-01T10:22:11.452331

清理资源

使用以下提示:

I am finished with this instance. Please remove the Azure Cache for Redis that you created earlier by using the values in the `.env` file. ONLY remove this resource and nothing else.