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

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

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

​​https://ost.​​

1、前言

上帖子使用云函数端云一体化开发计算十二生肖,此贴使用云数据库端云一体化开发计算十二生肖,在DevEco Studio可以完成端侧代码开发和云侧代码开发,一键部署云数据库,效果与之前使用云函数一样,计算获取方式不同。

2、真机效果

3、讲解

 开发云数据库 端云一体化项目结构和之前不一样,多了CloudProgram模块, 下面介绍项目开发,先从云侧开发开始,再到端侧开发。

4、云侧开发

(1)介绍云数据库目录结构

展开CloudProgram模块,展开clouddb目录,dataentry目录是存储数据条目文件,objecttype目录是存储对象类型文件,db-config.json自动生成,内容包含云数据库配置,目录结构如下图:

(2)定义对象类型

右击objecttype目录,创建对象类型。

{
"fields": [
{
"belongPrimaryKey": true,
"fieldName": "idx",
"fieldType": "Integer",
"isNeedEncrypt": false,
"notNull": true
},
{
"belongPrimaryKey": false,
"fieldName": "zodiacName",
"fieldType": "String",
"isNeedEncrypt": false,
"notNull": false
}
],
"indexes": [
{
"indexName": "idxIndex",
"indexList": [
{
"fieldName": "idx",
"sortType": "ASC"
}
]
},
{
"indexName": "zodiacIndex",
"indexList": [
{
"fieldName": "zodiacName",
"sortType": "DESC"
}
]
}
],
"objectTypeName": "ZodiacObject",
"permissions": [
{
"rights": [
"Read"
],
"role": "World"
},
{
"rights": [
"Read",
"Upsert"
],
"role": "Authenticated"
},
{
"rights": [
"Read",
"Upsert",
"Delete"
],
"role": "Creator"
},
{
"rights": [
"Read",
"Upsert",
"Delete"
],
"role": "Administrator"
}
]
}

(3)定义数据条目

右击dataentry目录,创建数据条目。

{
"cloudDBZoneName": "cloudDBZoneZodiac",
"objectTypeName": "ZodiacObject",
"objects": [
{
"idx": 0,
"zodiacName": "猴"
},
{
"idx": 1,
"zodiacName": "鸡"
},
{
"idx": 2,
"zodiacName": "狗"
},
{
"idx": 3,
"zodiacName": "猪"
},
{
"idx": 4,
"zodiacName": "鼠"
},
{
"idx": 5,
"zodiacName": "牛"
},
{
"idx": 6,
"zodiacName": "虎"
},
{
"idx": 7,
"zodiacName": "兔"
},
{
"idx": 8,
"zodiacName": "龙"
},
{
"idx": 9,
"zodiacName": "蛇"
},
{
"idx": 10,
"zodiacName": "马"
},
{
"idx": 11,
"zodiacName": "羊"
}
]
}

(4)部署云数据库

部署云侧代码到AGC上,右击clouddb目录,选择Deploy Cloud DB, 自动部署到AGC上,如果提示没有登录,登录成功后,再操作一次部署。

(5)导出文件格式

登录到AGC->云数据库,进入当前项目的云数据库服务菜单,可分别在“对象类型”、“存储区”与“数据”页签查看到您刚刚部署的云数据库资源。

导出json格式文件。

导出js格式文件。

导出json文件和js文件,端侧使用到。

5、端侧开发

(1)端侧模块结构

先看一下端侧模块结构:

(2)common目录

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

(3)services目录

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

services目录下AgcConfig.ts。

importagconnectfrom'@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';

constTAG="[AGCConfig]";

exportfunctiongetAGConnect(context) {
try {
agconnect.instance().init(context);
Log.info(TAG, "xx init AGC SDK success");
returnagconnect;
}
catch (err) {
Log.error(TAG, "xx initAgcSDK failed"+err);
}
}

在services目录下创建app-schema.json文件,复制上面在AGC下载的json格式文件内容到app-schema.json里。

{
"schemaVersion": 1,
"permissions": [{
"permissions": [{
"role": "World",
"rights": ["Read"]
}, {
"role": "Authenticated",
"rights": ["Read", "Upsert"]
}, {
"role": "Creator",
"rights": ["Read", "Upsert", "Delete"]
}, {
"role": "Administrator",
"rights": ["Read", "Upsert", "Delete"]
}],
"objectTypeName": "ZodiacObject"
}],
"objectTypes": [{
"indexes": [{
"indexName": "zodiacIndex",
"indexList": [{
"fieldName": "zodiacName",
"sortType": "DESC"
}]
}, {
"indexName": "idxIndex",
"indexList": [{
"fieldName": "idx",
"sortType": "ASC"
}]
}],
"objectTypeName": "ZodiacObject",
"fields": [{
"isNeedEncrypt": false,
"fieldName": "idx",
"notNull": true,
"isSensitive": false,
"belongPrimaryKey": true,
"fieldType": "Integer"
}, {
"isNeedEncrypt": false,
"fieldName": "zodiacName",
"notNull": false,
"isSensitive": false,
"belongPrimaryKey": false,
"fieldType": "String"
}]
}]
}

在services目录下创建ZodiacObject.js文件,复制上面在AGC下载的js格式文件内容到ZodiacObject.js里。

/*
* Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
* Generated by the CloudDB ObjectType compiler. DO NOT EDIT!
*/

classZodiacObject {
constructor() {
this.idx=undefined;
this.zodiacName=undefined;
}

setIdx(idx) {
this.idx=idx;
}

getIdx() {
returnthis.idx;
}

setZodiacName(zodiacName) {
this.zodiacName=zodiacName;
}

getZodiacName() {
returnthis.zodiacName;
}
}

ZodiacObject.className='ZodiacObject';

export {ZodiacObject}

services目录下创建CloudDB.ts。

import*asschemafrom'./app-schema.json';
import { ZodiacObject } from'./ZodiacObject'
import { AGConnectCloudDB, CloudDBZone, CloudDBZoneQuery } from'@hw-agconnect/database-ohos';
import { AGCRoutePolicy } from'@hw-agconnect/core-ohos';
import { getAGConnect } from'./AgcConfig';
exportclassCloudDBService {
privatestaticZONE_NAME: string="cloudDBZoneZodiac"
privatestaticinit(context: any): Promise<CloudDBZone> {
returnnewPromise((resolve, reject) => {
// 获取AGC连接
getAGConnect(context);
AGConnectCloudDB.initialize(context);

AGConnectCloudDB.getInstance({
context: context,
agcRoutePolicy: AGCRoutePolicy.CHINA,
objectTypeInfo: schema
}).then((ret) => {
returnresolve(ret.openCloudDBZone(this.ZONE_NAME));
}).catch((err) => {
returnreject(err);
});
})
}

publicstaticquery(context: any, year: number): Promise<ZodiacObject> {
letidx=year%12;

returnnewPromise((resolve, reject) => {
constquery=CloudDBZoneQuery.where(ZodiacObject).equalTo("idx", idx);
this.init(context).then((ret) => {
ret.executeQuery(query).then((ret) => {
resolve(ret.getSnapshotObjects()[0]);
})
}).catch((err) => {
reject(err);
});
})
}
}

(4)pages目录

pages目录 Index.ts 这里是页面布局,上面看到的效果,就是这里实现的。

import { CloudDBService } from'../services/CloudDB';

@Entry
@Component
structIndex {
// 存储选择年份
@Stateyear: number=2022
// 计算出来生肖
@Stateborn: string="?"
// 是否在计算中
@Stateflag: boolean=false

// 计算生肖
getBorn() {
// 标识为计算中
this.flag=true;
console.info('xx Page year: '+this.year)
// 封装参数
letparams= {
"year": this.year
}
// 调用云数据库
CloudDBService.query(getContext(this), this.year).then((res) => {
console.info('xx cloud db result: '+JSON.stringify(res));
// 计算完成
this.flag=false;
// 结果赋值给生肖变量
this.born=res.zodiacName;

}).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。

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

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

​​https://ost.​​

文章来源网络,作者:管理,如若转载,请注明出处:https://shuyeidc.com/wp/229435.html<

(0)
管理的头像管理
上一篇2025-04-18 18:37
下一篇 2025-04-18 18:38

相关推荐

  • 弹性云服务器到底是什么意思怎么收费,多少钱一个月

    弹性云服务器(Elastic Cloud Server,ECS)是一种可随时调整计算资源的云服务器,收费方式以按需付费和包年包月为主,用户只需为实际使用的资源买单,什么是弹性云服务器弹性云服务器本质上是一台运行在云端、配置可以灵活调整的虚拟机,它不像物理服务器那样固定规格,你可以在业务高峰期快速增加CPU、内存……

    2026-07-26
    0
  • 黑洞解封到底是什么意思,需要多久才能恢复

    黑洞解封是指将被黑洞路由策略屏蔽的IP地址恢复正常通信的过程,恢复时间通常取决于攻击流量是否彻底停止,多数情况下在攻击停止后10分钟到24小时内自动解除,用户也可通过联系服务商手动加速解封,黑洞解封到底是什么用拟人化的方式理解,黑洞就是网络世界的“强制隔离区”,当某个IP地址遭遇大量异常流量,比如DDoS攻击……

    2026-07-26
    0
  • 站群服务器IP段怎么选最安全,有哪些注意事项

    选择站群服务器IP段的安全核心在于IP地址的独立性、机房的路由策略以及服务商的合规资质,一个可靠的IP段必须来自持牌自营机房,具备独立C段和清洗能力,才能避免被关联风险,为什么IP段选择决定站群安全搜索引擎对IP关联的识别算法近年来越来越精细,同一C段或广播域的IP,爬虫通过反向DNS、路由跳数等特征很容易判断……

    2026-07-26
    0
  • 企业上云到底有什么实际好处,企业上云怎么选云服务商

    企业上云最大的实际好处,是把传统的机房运维包袱转化为可按需购买的专业服务,让企业成本更可控、业务更敏捷、安全更合规,成本重构:从买硬件到买服务传统企业自建机房,一次性投入大量资金购买服务器和网络设备,还得预留资源应对业务高峰,平时这些资源可能闲置浪费,上云之后,计算资源变成像水电一样按量付费的运营支出,告别资源……

    2026-07-26
    0
  • 流量清洗的工作原理到底是什么,有什么作用?

    流量清洗本质上是实时识别并过滤攻击流量,只将干净流量放行至目标服务器,是DDoS防护体系中的核心环节,为什么需要流量清洗近年来,DDoS攻击的规模和频率持续攀升,据行业报告,攻击带宽已轻松突破T级,攻击手法从单一的流量型攻击向应用层攻击演变,传统的防火墙或入侵检测系统在面对海量攻击流量时,往往自身先被耗尽,导致……

    2026-07-26
    0

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注