English
WeChat, Alipay, and Baidu's MiniApp all provide cloud development. But they only support their own MiniApp and cannot be used on other terminals.
uniCloud
uses the same infrastructure platform as WeChat MiniApp MiniApp Development and Alipay MiniApp Program Cloud Development. Behind WeChat Mini Program Cloud Development is the TCB team of Tencent Cloud, and behind Alipay MiniApp Cloud Development is the Alibaba Mini MiniApp Cloud Team. uniCloud
is a cross-device cloud development solution provided by DCloud, Alibaba MiniApp Cloud team, and Tencent Cloud's TCB team, who directly carry out in-depth cooperation and perform secondary packaging on the basis of their underlying resources.
In short, uniCloud is as stable and robust as WeChat MiniApp Cloud Development and Alipay MiniApp Cloud Development, but has more advantages:
clientDB
神器,减少90%的服务器开发工作量,且保障数据安全。详见JQL
query language, which is simpler and easier to master than the query syntax of SQL and MongoDB, especially the join table query is very simple. See detailsIf you have used WeChat MiniApp cloud development and want to learn more about the comparison and differences or how to migrate from WeChat MiniApp cloud to uniCloud, see
uniCloud
is a cloud service product jointly launched by DCloud and mature cloud vendors such as Alibaba Cloud and Tencent Cloud. Alibaba Cloud and Tencent Cloud provide basic cloud resources, and DCloud provides API design, front-end framework, IDE tool support, management console, and plug-ins For services such as ecology, developers' cloud functions are directly hosted on the serverless platforms of service providers such as Alibaba Cloud.
When the application on the user terminal is running, it is directly connected to the serverless platform of the cloud service provider without going through the DCloud server. Developers do not need to worry about the problem of affecting their business due to the load of the DCloud server.
阿里云和腾讯云都有商业级SLA。如果真出问题,他们会负责赔偿。
Cloud Functions is equivalent to Node.js + Serverless + DCloud improvements.
To sum up, even if the front-end students can write Node.js code proficiently, they still lack experience in DB optimization, elastic expansion, attack protection, disaster recovery processing, etc., but uniCloud
encapsulates these and truly achieves Only focus on business implementation, and entrust cloud vendors with other services.
In addition, in terms of Node.js code implementation, the host environment (which can be simply understood as a virtual machine or server hardware) for each execution of a cloud function may be the same or different. Therefore, in traditional Node.js
development, some information is stored locally Hard disk or memory solutions are no longer suitable, and it is recommended to use cloud database or cloud storage solutions instead.
Of course, there is the most important point. In uniCloud, it is recommended to use clientDB for a large number of businesses. Too many cloud functions cannot be written in one application.
uni-app can develop web interface, see: uni-app widescreen adaptation guide
If you need admin for PC, uniCloud provides uniCloud admin
uniCloud provides cloud function URLization
to meet the above requirements. See details
uniCloud provides a better front-end operation database solution than WeChat cloud development, see: clientDB
The performance of nodejs is better than php, and the performance of MongoDB is better than mysql.
For the front end, a json-like document database such as MongoDB is easier to use and has higher flexibility. The method of operating MongoDB still uses js.
MongoDB is very flexible and can add fields to tables with large amounts of data at will. However, once the amount of data in mysql table becomes large, every time a field is added, the size and performance of the database will be negatively affected.
The fields of MongoDB can be nested, and it is very convenient to express tree-type data, and it can be expanded as you like.
For developers who want to increase data redundancy to improve performance, nosql databases are a powerful tool.
Of course, for developers who prefer traditional databases, the database table structure can still be designed in the traditional way.
MongoDB is much more powerful than mysql. SQL is too simple. A SQL statement is actually a string, and complex logic cannot be written.
And MongoDB has a lot of js APIs and various aggregation operators, which are programmable, rather than expressed by a string of SQL statements.
For example, there are 4 fields in the product data table: views, favorites, purchases, and reviews. It is necessary to generate a list of recent popular products, each of which has a weight of 25% in each of the four fields, and sort them after weighting. This requirement cannot be directly realized by sql. In MongoDB, a query can directly return the sorted results.
The fuzzy query of SQL is also very weak, like only before and after %, so many developers have to use third-party databases such as ElastciSearch. Although later versions of mysql also support limited regularization. But MongoDB's regular query is still more powerful than developers expected.
Although MongoDB is powerful, it is not easy to use, especially the aggregation operation is very complicated to write.
uniCloud improves on the basis of MongoDB and further provides DB Schema
and JQL
.
DB Schema
is a json file that can describe data, agree on field value ranges, control operation permissions, and describe the relationship between fields, making database management more efficient and greatly reducing the workload of code development on the server side. See details
JQL
is a set of methods to operate the uniCloud database, which is more in line with the habits of js developers, and greatly reduces the learning cost and code volume.
For example, joint table query and tree query have become very simple. Such as tree query is a function that only Oracle has in the past. JQL
documentation see details
In the past, DCloud officially promoted Alibaba Cloud and Tencent Cloud to provide serverless mysql. However, after in-depth research and improvement of MongoDB, DCloud has given up the difficult-to-use mysql. It is recommended that developers learn about uniCloud's cloud database, which is more powerful and convenient to use.
注意
在云函数请求三方服务器时支持任意方式请求,包括http、websocket(需要使用nodejs原始的写法或三方包,后续uniCloud会支持websocket相关接口)等。下面说明的是针对云函数和客户端之间的通讯的说明
If the resources corresponding to cloud functions are not used for a long time, they will be released from memory by Alibaba Cloud or Tencent Cloud Platform. Once released, there will be a cold start process when starting the cloud function.
The performance is: after a long time without use, the first use will be slower, and then the second visit immediately will be very fast, with a millisecond response.
The cold start speed generally does not exceed 1.5 seconds. If it exceeds 1.5 seconds, it should be a problem with the cloud function or the network.
In terms of resource recovery policy, Alibaba Cloud will be recycled if there is no second visit to the cloud function within 15 minutes. Tencent Cloud is half an hour.
The two cloud vendors are still optimizing this problem. At present, if developers care about this issue, the suggestions for developers are:
A developer installs php or java on a single computer and connects to mysql on the same computer. Then compare the speed with uniCloud, and think that uniCloud is slow. The following differences need to be clarified here:
Cause 1. Cold start. For detailed analysis, see the previous question
Reason 2. Code and database are not on the same server Install php or java on a single machine, and install the database at the same time, the access speed is really fast. But when using a cloud database, that is, the database is a separate server, and the running code is not on the same server, it will cause a slight delay. But the databases for commercial applications must all be independent servers.
Reason 3. Interceptor Requests for back-end development generally have routing management frameworks or interceptors, and each request must be intercepted and permissions verified. Using such frameworks will definitely increase the time consumption.
This is the case with clientDB, because clientDB has a permission verification system inside, and the verification of certain permissions also requires database queries.
Therefore, although the speed of clientDB is slower, in fact, after developers write the framework for routing interception and authority management, the speed will also decrease.
From uni-id 3.0 onwards, the user's role permissions are cached in the token, and the library is no longer checked. The speed of clientDB is about 100 milliseconds faster than before. If you have not upgraded, please upgrade as soon as possible. At the same time, note that if you use uniCloud admin, you must also upgrade it. If you have written relevant business logic in cloud functions, please be sure to read the upgrade notes.
The index of the query table must be correctly configured. It is recommended to add an index to the fields that need to be queried in where, otherwise the query will be very slow.
But be careful not to have too many indexes, otherwise it will slow down when adding, deleting, and modifying data. Accuracy is very important. It is recommended to read Index Document in detail
uniCloud supports front-end web hosting, and it is completely free when you choose Alibaba Cloud as a cloud provider!
If it is because WeChat js sdk and other services require the configuration of a fixed ip whitelist, then Tencent Cloud’s charging space already supports fixed ip, see details
uniCloud's cloud database itself is a document database, which can be searched in full text.
Regular expressions can be passed in when querying data. Compared with SQL's like, which only has % before and after, regular expressions are much more powerful. For details, please refer to Regular Expression Query
Of course, if you need to configure additional third-party databases such as ElastciSearch, you can also find a server to install these services yourself, synchronize data, and synchronize the data that needs to be searched.
nodejs itself does not support formdata, but it can be supported by manually assembling formdata, reference
Example of using with uniCloud.httpclient.request
const FormData = require('form-data');
let form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('img', new Buffer(10), {
filename: `${Date.now()}.png`,
contentType: 'image/png'
})
uniCloud.httpclient.request('https://example.com',{
content: form.getBuffer(),
headers: form.getHeaders()
})
There is no need to control the quantity, and the limit will not be broken in actual development.
Because the framework will be used in actual development instead of developing cloud functions one by one.
以免费空间的48个云函数举例,一般情况下:
The above are the cloud functions carried by several commonly used frameworks recommended by the government, and in the developer’s own code, most of the business is developed using clientDB, without writing cloud functions, or writing supporting action cloud functions without occupying cloud functions Quantity; if you still need to write some cloud functions yourself, add uni-cloud-router, and use this single-router cloud function to meet the remaining needs; in addition, if you need to run batch data, you can add another cloud function. So in any case, 48 cloud functions are not enough.
Each cloud function of uniCloud is an independent process, and there is no multi-level directory concept at the cloud function level.
There can be subdirectories under each cloud function, but they all belong to a part of this cloud function, not another cloud function.
The single-router cloud function framework is not only the official uni-cloud-router, there are many similar frameworks in the plug-in market: [see for details](https://ext.dcloud.net.cn/search?q=%E8%B7%AF %E7%94%B1&cat1=7&orderBy=TotalDownload)
港澳台及海外/国外用户需要使用全球加速(海外加速)。uniCloud服务商为阿里云时支持配置全球加速,步骤如下:
own domain name
api.next.bspapp.com
When opening Tencent Cloud service space, the real-name authentication prompts that the real-name subject already has three accounts. This is often because the developer has accidentally opened multiple free MiniApp clouds in the WeChat MiniApp development tool. At this time, you can refer to the following process to cancel the unused accounts. :
At the same time, if you pay to purchase Tencent Cloud service space, each account can have a maximum of 50 Tencent Cloud service spaces (note that only one of them enjoys a free quota).
uniCloud Alibaba Cloud now supports redis. To enable and use redis, please refer to: Redis activation and use. md?id=snap-over-sell) (recommended). The following method is not flexible for scenarios without redis (not recommended)
When the concurrency is high, many users read and write a piece of data at the same time, which can easily cause data confusion, which is manifested in scenarios such as flash sales and panic buying, which are oversold. Taking seckill as an example, developers can start from deducting inventory to greatly limit overselling. The following is a simple example (note that the following code does not use transactions)
// cloud function
const db = uniCloud.database()
const dbCmd = db.command
exports.main = async function(event){
const transaction = await db.startTransaction()
// other business logic...
// Inventory minus one
const reduceRes = await db.collection('goods').where({
_id: 'goods_id', // 商品ID
stock: dbCmd.gt(1) // 限制库存大于1的才允许扣除库存
}).update({
stock: dbCmd.inc(-1)
})
if(reduceRes.updated === 0) { // 如果没成功更新库存就认为下单失败
await transaction.rollback()
return {
code: 1001,
message: '下单失败'
}
}
}
About cloud storage: The number of reads and writes here is not necessarily for files: including: uploading files, modifying policies, modifying ACLs, modifying CORS, etc., will be considered as COS writes. When the environment is initialized, many initialization operations will be performed, and configuration information such as policy/acl/cors will be written. Every time the user operates to modify the security domain name, modify the static domain name, etc., it will also trigger the writing of CORS.
About the database: Developers accessing the database through the uniCloud web console will also increase a small number of reads and writes
Tencent Cloud will store some information in the local storage, please do not use interfaces such as clearStorage to directly delete the storage during application use.
This domain name has already been added and cannot be added again
Front-end web hosting will conflict with other CDN services on Alibaba Cloud (including but not limited to CDN). If you want to bind to front-end web hosting, please first disassociate this domain name from other services.
The root domain of your domain is reserved by another account
Currently, the domain name has services related to site-wide acceleration enabled on Alibaba Cloud (the pan-domain name acceleration may be configured), which conflicts with the front-end web page hosting. You can consider using a third-level domain name or removing the pan-domain name for acceleration and instead configuring the domain name that needs to be accelerated separately.
For details, please refer to the document: Multiplayer Collaboration in Service Space
The uniCloud client callFunction and database-related interfaces will return Promise-type results, please refer to the following writing method:
// index.vue
<template>
<view class="content">
<button type="default" @click="testThen">promise+then</button>
<button type="default" @click="testAwait">async+await</button>
</view>
</template>
<script>
export default {
data() {
return {}
},
methods: {
testThen() {
uniCloud.callFunction({
name: 'test'
}).then(res => {
console.log(res)
}).catch(err => {
console.error(err)
})
},
async testAwait() {
const res = await uniCloud.callFunction({
name: 'test'
})
console.log(res)
// try {
// const res = await uniCloud.callFunction({
// name: 'test'
// })
// console.log(res)
// } catch (err) {
// console.error(err)
// }
}
}
}
</script>
<style>
</style>
When there is a problem with your system, how to judge whether it is DCloud or Alibaba Cloud or Tencent Cloud?
First of all, it is stated again that DCloud's services are limited to the development stage. After release and deployment, the access of the application does not go through the DCloud server.
Of course, there is another situation where an error is reported. In fact, it is a problem with the client, including the cross-domain problem of the browser, or the whitelist problem of the domain name of the MiniApp, which makes the client unable to connect to uniCloud. This needs to be solved through configuration, refer to the document: Domain name access configuration for MiniApp and browsers
If the test system is abnormal, it means that the cloud vendor's service is out of order.
These two systems are completely independent. If both systems fail, it means that both cloud vendors fail, not the DCloud service. Again, the published service does not connect to DCloud's server.
When encountering uniCloud faults, just give feedback in the QQ group or forum of uniCloud. Because Alibaba Cloud and Tencent Cloud actually have a dial-up testing system, they will know the fault and solve it in time.
** operation exceeded time limit
, cloud database execution time exceeded
error**
This error is generally caused by database operation timeout. For details on how to optimize it, please refer to: Performance Optimization
WriteConflict
error when using transactions
The execution of the transaction will lock the row, and different transactions executed at the same time will conflict when operating the same row of data, resulting in write failure. Optimize the process as much as possible to avoid transaction conflicts
** An error will be reported when the service space that has not been used for a long time is accessed again **
Possible error messages include: Request cloud function timeout
, Response timeout for 10000ms, POST https://api.next.bspapp.com/server -1
This problem is generally caused by the fact that the database has not been accessed for a long time, and the mongoDB WiredTiger storage engine eliminated tables and indexes in memory, causing the database request to time out and causing the cloud function to report an error.
Tencent Cloud reported SIGN_PARAM_INVALID signature is expired
error
This problem usually occurs when the Tencent Cloud function is debugged locally, and it is usually caused by the wrong system time of the current development machine
Tencent Cloud reports access token disabled for ANONYMOUS login
error
The service space has never uploaded a cloud function, just upload a cloud function
This chapter only explains the adjustment of the let's encrypt certificate. In other cases, please check whether the certificate of the corresponding website has expired
The root certificate of let's encrypt expires on September 30, 2021 and switches to a new version of the root certificate. For details, please refer to: DST Root CA X3 Expiration (September 2021). This expiration behavior caused a certificate has expired
error when nodejs8 requested a website using a let's encrypt certificate.
There are two solutions:
Upgrade the cloud function to nodejs12, delete the old cloud function, and re-upload after configuring the node version. For details, refer to: cloud function package.json
(Not recommended) Use rejectUnauthorized: false
when using uniCloud.httpclient.request
. The sample code is as follows:
const https = require('https')
const httpsAgent = new https.Agent({
rejectUnauthorized: false
})
await uniCloud.httpclient.request('https://xxx.com/get', {
httpsAgent
})
If Tencent Cloud is used as the service provider, please check whether the clearStorage operation has been executed on the front end when this problem occurs. clearStorage will clear the token set by Tencent Cloud, resulting in an error when requesting cloud functions.
如需云厂商提供等级保护证书,请发送邮件到service@dcloud.io申请,邮件模板参考:申请解除限制邮件模板
商用版如果使用uniCloud.init需要自行传递endpoint参数,参考:uniCloud.init
检查云函数运行时间是否超出配置的超时时间,优化代码逻辑或配置更长的超时时间
对于针对ip地址进行的流量攻击是无法到达云函数的,云厂商的网关会拦截此类攻击流量。如果攻击者模拟真实请求,此时可以通过云函数IP防刷功能,进行一定程度的防护。云厂商也正在提供网关层面的防刷机制。
如何处理针对云存储的流量攻击,参考:阿里云云存储安全策略