新手也能用:AGC云函数在鸿蒙5中的调用方法详解

一、AGC云函数基础介绍

  1. 什么是AGC云函数
    AGC(AppGallery Connect)云函数是华为提供的Serverless计算服务,允许开发者在云端运行代码而无需管理服务器。在HarmonyOS 5应用中,你可以直接调用这些云函数来处理业务逻辑。

  2. 云函数在鸿蒙应用中的典型应用场景
    处理复杂计算任务
    访问第三方API服务
    执行数据库聚合操作
    实现业务逻辑的隔离和复用
    二、环境准备与配置

  3. 在AGC控制台开通云函数服务
    登录AppGallery Connect
    进入你的项目
    在左侧菜单选择"构建" > "云函数"
    点击"立即开通"按钮

  4. 配置HarmonyOS项目
    在entry/build.gradle中添加依赖:

dependencies {
// AGC核心库
implementation 'com.huawei.agconnect:agconnect-core-harmony:1.6.5.300'
// 云函数库
implementation 'com.huawei.agconnect:agconnect-cloudfunctions-harmony:1.6.5.300'
}
3. 获取并配置agconnect-services.json
在AGC控制台下载agconnect-services.json文件
将其放入entry/src/main/resources/rawfile/目录
三、创建第一个云函数

  1. 在AGC控制台创建云函数
    进入"云函数"服务页面
    点击"创建函数"
    填写函数信息:
    函数名称:helloWorld
    描述:我的第一个云函数
    运行时:Node.js 14
    点击"下一步"
  2. 编写云函数代码
    替换默认代码为以下内容:

// 简单示例:返回问候语
exports.handler = async (event, context) => {
const name = event.name || "World";
return {
message: Hello ${name}!,
timestamp: new Date().toISOString()
};
};
3. 部署云函数
点击"部署"按钮
等待部署完成(约1-2分钟)
记下函数名称(如helloWorld-$latest)
四、从HarmonyOS应用调用云函数

  1. 初始化AGC客户端
    在应用启动时初始化(通常在EntryAbility.ets中):

import agconnect from '@hw-agconnect/core';

// 在onCreate方法中初始化
onCreate() {
agconnect.instance().init();
}
2. 创建云函数调用封装类
新建CloudFunctionsManager.ets文件:

import cloudfunctions from '@hw-agconnect/cloudfunctions';
import agconnect from '@hw-agconnect/core';

export class CloudFunctionsManager {
private static instance: CloudFunctionsManager | null = null;
private cloudFunctions = cloudfunctions.functionCall();

private constructor() {
    // 初始化云函数实例
    this.cloudFunctions = cloudfunctions.functionCall(
        agconnect.instance(),
        "YOUR_REGION" // 如"cn-north-1"
    );
}

public static getInstance(): CloudFunctionsManager {
    if (!CloudFunctionsManager.instance) {
        CloudFunctionsManager.instance = new CloudFunctionsManager();
    }
    return CloudFunctionsManager.instance;
}

// 调用云函数通用方法
async callFunction<T>(functionName: string, data?: Object): Promise<T> {
    try {
        const result = await this.cloudFunctions.call({
            functionName: functionName,
            parameters: data || {}
        });
        return result.getValue() as T;
    } catch (error) {
        console.error(`调用云函数${functionName}失败:`, error);
        throw error;
    }
}

}
3. 调用helloWorld云函数
在页面中调用示例:

import { CloudFunctionsManager } from './CloudFunctionsManager';

@Entry
@Component
struct CloudFunctionDemo {
@State message: string = "点击按钮调用云函数";
@State result: string = "";

private cloudManager = CloudFunctionsManager.getInstance();

build() {
    Column({ space: 20 }) {
        Text(this.message)
            .fontSize(20)
        
        Button('调用helloWorld云函数')
            .width(200)
            .height(50)
            .backgroundColor(Color.Blue)
            .onClick(async () => {
                this.message = "正在调用云函数...";
                try {
                    const response = await this.cloudManager.callFunction<{
                        message: string,
                        timestamp: string
                    }>("helloWorld-$latest", { name: "HarmonyOS" });
                    
                    this.result = `${response.message}\n时间: ${response.timestamp}`;
                    this.message = "调用成功!";
                } catch (e) {
                    this.message = "调用失败";
                    this.result = e.toString();
                }
            })
        
        Text(this.result)
            .fontSize(16)
            .multilineTextAlign(TextAlign.Start)
            .width('90%')
    }
    .width('100%')
    .height('100%')
    .padding(20)
    .justifyContent(FlexAlign.Center)
}

}
五、进阶云函数开发

  1. 带参数的云函数示例
    在AGC控制台创建新函数calculate:

exports.handler = async (event, context) => {
const { a, b, operation } = event;

if (isNaN(a) || isNaN(b)) {
    throw new Error("参数必须为数字");
}

let result;
switch (operation) {
    case 'add':
        result = a + b;
        break;
    case 'subtract':
        result = a - b;
        break;
    case 'multiply':
        result = a * b;
        break;
    case 'divide':
        if (b === 0) throw new Error("除数不能为0");
        result = a / b;
        break;
    default:
        throw new Error("不支持的操作类型");
}

return {
    operation,
    a,
    b,
    result,
    timestamp: new Date().toISOString()
};

};
2. 在鸿蒙应用中调用带参函数
@Entry
@Component
struct CalculatorDemo {
@State a: number = 10;
@State b: number = 5;
@State operation: string = "add";
@State result: string = "";

private cloudManager = CloudFunctionsManager.getInstance();

build() {
    Column({ space: 20 }) {
        Row({ space: 10 }) {
            TextInput({ text: this.a.toString() })
                .width(80)
                .onChange((value: string) => {
                    this.a = Number(value) || 0;
                })
            
            Picker({ range: ["add", "subtract", "multiply", "divide"] })
                .selected(this.operation)
                .onChange((index: number, value: string) => {
                    this.operation = value;
                })
                .width(120)
            
            TextInput({ text: this.b.toString() })
                .width(80)
                .onChange((value: string) => {
                    this.b = Number(value) || 0;
                })
        }
        
        Button('执行计算')
            .width(200)
            .height(50)
            .backgroundColor(Color.Green)
            .onClick(async () => {
                try {
                    const response = await this.cloudManager.callFunction<{
                        operation: string,
                        a: number,
                        b: number,
                        result: number,
                        timestamp: string
                    }>("calculate-$latest", {
                        a: this.a,
                        b: this.b,
                        operation: this.operation
                    });
                    
                    this.result = `${response.a} ${this.getOperationSymbol(response.operation)} ${response.b} = ${response.result}`;
                } catch (e) {
                    this.result = `计算错误: ${e.message}`;
                }
            })
        
        Text(this.result)
            .fontSize(18)
            .fontColor(Color.Red)
    }
    .width('100%')
    .height('100%')
    .padding(20)
}

private getOperationSymbol(op: string): string {
    switch (op) {
        case 'add': return '+';
        case 'subtract': return '-';
        case 'multiply': return '×';
        case 'divide': return '÷';
        default: return op;
    }
}

}
六、错误处理与调试技巧

  1. 增强错误处理
    修改CloudFunctionsManager.ets中的调用方法:

async callFunction(functionName: string, data?: Object): Promise {
try {
const result = await this.cloudFunctions.call({
functionName: functionName,
parameters: data || {}
});

    if (!result.getValue()) {
        throw new Error("云函数返回空结果");
    }
    
    return result.getValue() as T;
} catch (error) {
    console.error(`调用云函数${functionName}失败:`, error);
    
    // 转换为用户友好的错误消息
    let errorMessage = "网络错误,请重试";
    if (error instanceof Object && error.hasOwnProperty("message")) {
        errorMessage = error.message;
    } else if (typeof error === "string") {
        errorMessage = error;
    }
    
    throw new Error(errorMessage);
}

}
2. 添加日志记录
在云函数中添加日志:

exports.handler = async (event, context) => {
console.log("收到请求参数:", JSON.stringify(event));

try {
    // ...函数逻辑...
    
    console.log("计算结果:", result);
    return {
        // ...返回数据...
    };
} catch (error) {
    console.error("执行出错:", error);
    throw error;
}

};
3. 查看云函数日志
在AGC控制台进入云函数服务
选择你的函数
点击"监控"标签页
查看"运行日志"
七、性能优化建议

  1. 批量操作减少调用次数
    创建批量处理函数batchProcess:

exports.handler = async (event, context) => {
const { operations } = event;

if (!Array.isArray(operations)) {
    throw new Error("参数operations必须是数组");
}

const results = [];
for (const op of operations) {
    const { a, b, operation } = op;
    // ...执行计算...
    results.push({
        a, b, operation, result
    });
}

return { results };

};
2. 客户端缓存策略
import { CloudFunctionsManager } from './CloudFunctionsManager';

@Entry
@Component
struct CachedFunctionDemo {
private cloudManager = CloudFunctionsManager.getInstance();
private cache = new Map<string, { data: any, timestamp: number }>();
private cacheDuration = 5 * 60 * 1000; // 5分钟缓存

async callWithCache<T>(functionName: string, params?: any): Promise<T> {
    const cacheKey = `${functionName}_${JSON.stringify(params)}`;
    
    // 检查缓存
    if (this.cache.has(cacheKey)) {
        const cached = this.cache.get(cacheKey)!;
        if (Date.now() - cached.timestamp < this.cacheDuration) {
            return cached.data as T;
        }
    }
    
    // 调用云函数
    const result = await this.cloudManager.callFunction<T>(functionName, params);
    
    // 更新缓存
    this.cache.set(cacheKey, {
        data: result,
        timestamp: Date.now()
    });
    
    return result;
}

// ...页面实现...

}
八、实际应用案例:用户反馈系统

  1. 创建反馈云函数
    exports.handler = async (event, context) => {
    const { userId, content, contact } = event;

    if (!content || content.length < 10) {
    throw new Error("反馈内容至少需要10个字符");
    }

    // 这里可以添加存储到数据库的逻辑
    // 例如使用CloudDB或第三方服务

    return {
    status: "success",
    feedbackId: Date.now().toString(),
    receivedAt: new Date().toISOString()
    };
    };

  2. 鸿蒙端实现反馈页面
    @Entry
    @Component
    struct FeedbackPage {
    @State content: string = "";
    @State contact: string = "";
    @State result: string = "";
    @State isSubmitting: boolean = false;

    private cloudManager = CloudFunctionsManager.getInstance();

    build() {
    Column({ space: 20 }) {
    Text("用户反馈")
    .fontSize(24)
    .fontWeight(FontWeight.Bold)

         TextArea({ text: this.content })
             .placeholder("请输入您的反馈意见(至少10个字符)")
             .height(150)
             .width('90%')
             .onChange((value: string) => {
                 this.content = value;
             })
         
         TextInput({ text: this.contact })
             .placeholder("联系方式(可选)")
             .width('90%')
             .onChange((value: string) => {
                 this.contact = value;
             })
         
         Button(this.isSubmitting ? "提交中..." : "提交反馈")
             .width(200)
             .height(50)
             .backgroundColor(this.isSubmitting ? Color.Gray : Color.Blue)
             .enabled(!this.isSubmitting)
             .onClick(async () => {
                 if (this.content.length < 10) {
                     this.result = "反馈内容至少需要10个字符";
                     return;
                 }
                 
                 this.isSubmitting = true;
                 this.result = "";
                 
                 try {
                     const response = await this.cloudManager.callFunction<{
                         status: string,
                         feedbackId: string,
                         receivedAt: string
                     }>("submitFeedback-$latest", {
                         userId: "current_user_id", // 实际应用中替换为真实用户ID
                         content: this.content,
                         contact: this.contact
                     });
                     
                     this.result = `反馈提交成功!编号: ${response.feedbackId}`;
                     this.content = "";
                     this.contact = "";
                 } catch (e) {
                     this.result = `提交失败: ${e.message}`;
                 } finally {
                     this.isSubmitting = false;
                 }
             })
         
         Text(this.result)
             .fontSize(16)
             .fontColor(this.result.includes("成功") ? Color.Green : Color.Red)
             .width('90%')
     }
     .width('100%')
     .height('100%')
     .padding(20)
    

    }
    }
    总结
    通过本文的学习,你已经掌握了在HarmonyOS 5应用中调用AGC云函数的完整流程:

​​环境配置​​:正确设置AGC项目和HarmonyOS应用
​​基础调用​​:实现简单的helloWorld函数调用
​​参数传递​​:处理带参数的云函数调用
​​错误处理​​:增强客户端的错误处理能力
​​性能优化​​:通过批处理和缓存提升性能
​​实战案例​​:实现用户反馈系统
云函数为HarmonyOS应用提供了强大的后端能力,同时免去了服务器管理的复杂性。随着你对云函数的深入使用,可以探索更多高级功能,如:

结合CloudDB实现数据持久化
使用云函数作为微服务架构的中间层
实现定时触发的后台任务
与其他AGC服务(如认证服务、存储服务)集成

posted @ 2025-06-28 22:27  暗雨YA  阅读(74)  评论(0)    收藏  举报