首页 > 其他分享 >端云一体化开发-计算十二生肖-云函数

端云一体化开发-计算十二生肖-云函数

时间:2023-03-16 18:33:02浏览次数:42  
标签:十二生肖 Log 一体化 value born year action 端云 agconnect

(目录)

1. 前言

    之前帖子介绍过用不同方式计算十二生肖,也用过Serverless云函数计算,但那时是用Java调用云函数,这次直接使用端云一体化开发,方便了很多,不用手工集成云函数SDK, 而且在DevEco Studio 就可以完成端侧代码开发和云侧代码开发,一键部署云函数和云数据库,下面先来看一下效果。

2. 效果

20230308.gif

3. 讲解

创建端云一体化项目,这里就不介绍的,可以移步到官方详细教程 创建端云一体化开发工程-端云一体化开发-应用/服务开发-DevEco Studio使用指南(HarmonyOS)-工具-HarmonyOS应用开发 端云一体化项目结构和之前不一样,多了CloudProgram模块, 下面介绍项目开发,先从云侧开发开始,再到端侧开发。

4. 云侧开发

4.1 展开CloudProgram模块,右击cloudfunctions目录,创建自定义云函数:

image.png image.png

4.2 打开function-config.json文件,记录修改authType为apigw-client

{
  "handler": "zodiacFun.myHandler",
  "triggers": [
    {
      "type": "http",
      "properties": {
        "enableUriDecode": true,
        "authFlag": "true",
        "authAlgor": "HDA-SYSTEM",
        "authType": "apigw-client"
      }
    }
  ]
}

4.3 打开zodiacFun.ts文件,编写自定云函数逻辑,计算十二生肖方法就是写在这里,同时把结果返回端侧.

let myHandler = async function (event, context, callback, logger) {
  // 打印参数
  logger.info("**event: "+JSON.stringify(event))
  // 定义十二生肖
  let zodiac = ["猴", "鸡", "狗", "猪", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊"];

  // 转化参数为对象参数
  event.body = JSON.parse(event.body);
  // 根据年份计算生肖下标
  let idx = parseInt(event.body.year)%12;
  // 获取生肖
  let sx = zodiac[idx];
  // 生成HTTP响应对象
  let res = new context.HTTPResponse({"zodiac": sx}, {
    "faas-content-type": "json"
  }, "application/json", "200");

  // 回调
  callback(res);

};

export { myHandler };

4.4 部署云侧代码到AGC上,右击自定义云函数目录,选择Deploy Function, 自动部署到Serverless上,如果提示没有登录,登录成功后,再操作一次部署。

image.png

4.5 到这里云侧开发就完成了,可以登录到AGC->云函数,找到刚才部署的云函数,测试一下自定义云函数。

5. 端侧开发

5.1 先看一下端侧模块结构:

image.png

5.2 common目录放一些公共的封装类,比如Log类; components目录放自定义组件;entryability是自动生成的,里面有一个EntryAbility类,包含生命周期;pages目录放UI布局页面;services目录放业务逻辑类,比如调用云侧接口。

5.3 这里只介绍services目录和pages目录下的工作,先介绍如何和AGC连接上的,这里使用一个单独的文件来处理:

5.3.1 services目录下AgcConfig.ts
import agconnect from '@hw-agconnect/api-ohos';
import "@hw-agconnect/core-ohos";
import "@hw-agconnect/auth-ohos";
import '@hw-agconnect/auth-types-ohos';

import { Log } from '../common/Log';

const TAG = "[AGCConfig]";

export function getAGConnect(context) {
    try {
        agconnect.instance().init(context);
        Log.info(TAG, "xx init AGC SDK success");
        return agconnect;
    }
    catch (err) {
        Log.error(TAG, "xx initAgcSDK failed" + err);
    }
}
5.3.2 services目录下Function.ts
import agconnect from '@hw-agconnect/api-ohos';
import "@hw-agconnect/function-ohos";

import { Log } from '../common/Log';
import { getAGConnect } from './AgcConfig';

const TAG = "[AGCFunction]";


export function zodiac(context, params: any): Promise<string> {
    console.info('xx Function Params: ' + JSON.stringify(params))
    return new Promise((resolve, reject) => {
        // 获取AGC连接
        getAGConnect(context);
        let functionResult;
        // 获取云函数回调
        let functionCallable = agconnect.function().wrap("zodiacfun-$latest");
        // 传递参数调用云函数
        functionCallable.call(params).then((ret: any) => {
            Log.info(TAG,'xx Zodiac Function Sucess')
            // 获取成功返回结果集
            functionResult = ret.getValue();
            Log.info(TAG, "xx Zodiac Function Called, Returned Value: " + JSON.stringify(ret.getValue()));
            // 返回结果集给界面
            resolve(functionResult.zodiac);
        }).catch((error: any) => {
            Log.error(TAG, "xx Error - could not obtain zodiac function result. " );
            Log.error(TAG, "xx Error Detail: " + JSON.stringify(error));
            reject(error);
        });
    });
}
5.3.3 pages目录 Index.ts 这里是页面布局,上面看到的效果,就是这里实现的。
import { zodiac } from '../services/Function';

@Entry
@Component
struct Index {
  // 存储选择年份
  @State year: number = 2022
  // 计算出来生肖
  @State born: string = "?"
  // 是否在计算中
  @State flag: boolean = false

  // 计算生肖
  getBorn() {
    // 标识为计算中
    this.flag = true;
    console.info('xx Page year: ' + this.year)
    // 封装参数
    let params = {
      "year": this.year
    }
    // 调用函数
    zodiac(getContext(this), params).then((res) => {
      // 计算完成
      this.flag = false;
      // 结果赋值给生肖变量
      this.born = res;
    }).catch((err) => {
      // 计算完成
      this.flag = false;
      console.error('xx error: ', err && err.message);
    });
  }

  build() {
    Stack() {
      if (!this.flag) {
        Column({space: 20}) {
          Text('请选择年份')
            .fontSize(20)
            .fontWeight(FontWeight.Bold)

          // 选择年份
          Column() {
            Text(this.year + '')
              .fontSize(20)
              .fontWeight(FontWeight.Bold)
              .padding(10)
              .width(100)
              .border({ width: 1, radius: 8 })
          }
          .bindMenu([
            { value: '2006', action: () => {this.year = 2006; this.born = '?'} },
            { value: '2007', action: () => {this.year = 2007; this.born = '?'} },
            { value: '2008', action: () => {this.year = 2008; this.born = '?'} },
            { value: '2009', action: () => {this.year = 2009; this.born = '?'} },
            { value: '2010', action: () => {this.year = 2010; this.born = '?'} },
            { value: '2011', action: () => {this.year = 2011; this.born = '?'} },
            { value: '2012', action: () => {this.year = 2012; this.born = '?'} },
            { value: '2013', action: () => {this.year = 2013; this.born = '?'} },
            { value: '2014', action: () => {this.year = 2014; this.born = '?'} },
            { value: '2015', action: () => {this.year = 2015; this.born = '?'} },
            { value: '2016', action: () => {this.year = 2016; this.born = '?'} },
            { value: '2017', action: () => {this.year = 2017; this.born = '?'} },
            { value: '2018', action: () => {this.year = 2018; this.born = '?'} },
            { value: '2019', action: () => {this.year = 2019; this.born = '?'} },
            { value: '2020', action: () => {this.year = 2020; this.born = '?'} },
            { value: '2021', action: () => {this.year = 2021; this.born = '?'} },
            { value: '2022', action: () => {this.year = 2022; this.born = '?'} },
            { value: '2023', action: () => {this.year = 2023; this.born = '?'} },
            { value: '2024', action: () => {this.year = 2024; this.born = '?'} },
            { value: '2025', action: () => {this.year = 2025; this.born = '?'} }
          ])

          // 计算按钮操作
          Button('计算', {type: ButtonType.Normal, stateEffect: true})
            .fontSize(18)
            .borderRadius(8)
            .width(100)
            .margin({bottom: 20})
            .onClick(() => {
              // 根据年份计算生肖
              this.getBorn()
            })

            // 显示计算结果
            Text(`${this.year} 年生肖是  ${this.born}`)
              .fontSize(20)
              .fontWeight(FontWeight.Bold)
        }
        .width('100%')
        .height('100%')
        .padding({top: '33%'})
      } else {
        // 计算中
        LoadingProgress().color(Color.Blue)
          .backgroundColor(Color.Transparent)
      }
    }
  }
}

6. 总结

    由于调用云侧云函数是异步的,不能马上返回结果,这里添加LoadingProgress组件,让用户知道在运行中,效果看得不是很明显,可能录制时,网速很快,LoadingProgress组件闪一下就不见了,如果遇到网络慢时,LoadingProgress就会一直转,直到云函数返回响应时,再消失LoadingProgress。

本文作者:狼哥Army

想了解更多关于开源的内容,请访问:​

​51CTO 开源基础软件社区​

​https://ost.51cto.com/#bkwz​

标签:十二生肖,Log,一体化,value,born,year,action,端云,agconnect
From: https://blog.51cto.com/harmonyos/6125182

相关文章

  • 一体化智能机房解决方案(下)
    5.运维任务管理混乱在日常运维过程中,我们会有一些故障处理、业务变更需求、性能扩展、新业务上线等的任务,但是我们通常都像救火队一样,来一个事情处理一个事情,甚至有的时候......
  • 一体化智能机房解决方案(上)
    IT运维人员的思考?IT运维工作面临如何进行数字化赋能转型?数壳针对IT痛点给你答案! IT运维人员的痛点:1、故障发现机制延迟2、各类故障事件频发3、巡检工作繁琐低效4......
  • 创维VR软硬件一体化项目研发管理实践
    揭秘|创维VR软硬件一体化项目研发管理实践https://mp.weixin.qq.com/s?__biz=MzA3OTQwMDcwNg==&mid=2650834412&idx=1&sn=fdfc36deca34f9bd2f964c33970cefcd&chksm=84403f8......
  • 众安科技DevCube研发运维一体化平台获评InsurStar2022优秀数字化创新项目
    近日,保险行业头部自媒体平台保观发布了2022年InsurStar行业榜单,众安科技DevCube研发运维一体化平台凭借平台一体化、流程自动化、数据可视化等产品能力,从一众项目提名中脱......
  • 模切ERP的智能备料、智能分切,业财一体化解决方案
    精细化管理做得好,可以使一个模切工厂的管理化繁为简,将复杂的现场人、机、料、法、环简单化,条理化。运用点晴模切ERP系统提供一整套业财一体化解决方案,实现模切企业车间生产......
  • 业务+研发=一体化管理平台?
    兼顾研发及业务协作,又能够关注生态连接的工具,似乎在市面上还没有见到接近完美的产品。当然,万物皆在不断的进化,没有最好,只有更好。伴随着互联网在中国进程的发展,线上研发效......
  • WorkPlus即时通讯集成工作平台,提效企业一体化管控
    在当今信息化时代,越来越多的企业开始注重数字化办公,WorkPlus正是满足这种需求的应用之一。WorkPlus以即时通讯为核心,将企业内部通讯、日程安排、工作任务等多个功能进行集......
  • 业务-研发一体化,助力中国软件行业更新
    中国软件行业从未停止过持续的创新,线上研发效能及业务应用软件也不落后于时代进步的脚步,在持续的发展。2022年,业务应用开发正在简化,研发效能也在提升,其中不得不提软件在协同......
  • 业务与研发一体化最佳突破口在何处?
    近年来,一方面业务应用的开发逐渐走向简化,企业更加注重业务应用实质的提效性。另一方面,各企业的研发效能也在逐步提升。而这两者也促进了研发一体化管理、业务模版化等软件(......
  • 一体化移动办公平台,让政企工作更轻松、更便捷
    当前,中国经济正处于高质量发展关键阶段,党中央、国务院不断出台关于推动新一代信息技术与制造业深度融合,打造数字经济新优势等决策的部署文件。加速推动企业的数字化转型,打造......