authors are vetted experts in their fields and write on topics in which they have demonstrated experience. 我们所有的内容都经过同行评审,并由同一领域的Toptal专家验证.
菲利普·爱德华兹的头像

Phillip Edwards

Phillip在软件开发的各个方面都有丰富的经验. 最近,他一直在使用谷歌Firebase开发应用程序.

Previously At

Okta
Share

移动和web应用程序通常需要一个后端服务器. Web应用程序需要Web服务器来交付内容. 应用程序还需要存储用户配置文件和媒体,如图像和视频. 应用程序和服务器之间的通信通常使用API完成, which is usually REST.

应用程序是用一系列语言编写的. iOS应用程序是用Swift或Objective-C编写的. Android应用是用Java或Kotlin编写的. Web应用程序是用HTML编写的, CSS, JavaScript, 通常是复杂的框架,比如Angular或React. Front-end developers need to know the relevant languages and their associated development tools.

后端服务器是用多种语言编写的,包括Go、Java、PHP和Python. Each of these languages has its own suite of libraries to facilitate writing complex applications.

大多数开发人员认为自己是前端或后端开发人员. 精通这两种角色的全栈开发人员相对较少.

运行和维护后端服务器有其自身的挑战. 服务器需要构建、更新和备份. Servers also need to be secured to prevent accidental or malicious data loss or access to sensitive data. In addition, 服务器需要分配主机名和IP地址,以便连接到它们.

What Is Firebase?

Firebase 最初是一个移动信息架构,后来被b谷歌收购. 它已经发展成为一个超过25个组件的套件,可以与 Google Cloud Platform.

Firebase由软件开发工具包(sdk)组成, 它允许移动和web开发人员简单地访问云功能, securely, and reliably. 它们会自动补偿较差的网络连接. 有一个用于启用、管理和保护组件的Firebase web控制台. 还有命令行工具和REST api供更深入的使用.

有些Firebase组件比其他组件更知名. 组件之间几乎没有依赖关系, 哪一个允许增量采用功能. Firebase身份验证和分析是最广泛使用的.

Firebase has evolved to become a platform that allows mobile and web front-end developers to develop complete applications without the need for back-end servers. 最近的增强极大地促进了无服务器解决方案,它提供了一个可行的, scalable, 云虚拟机服务器解决方案的经济高效替代方案.

Firebase定价和计费计划

Firebase的基本计费计划名为Spark,是免费的. 云资源的使用是有限制的,但它们是相当慷慨的. 运行一个合理大小的应用程序而不产生任何费用是可能的.

A website with up to 1GB content and transfers of less than 10GB/month can be hosted under the Spark plan. Firestore允许高达1GB的数据和网络流量高达10GB/月. 云存储限制为数据最多5GB,下载最多1GB/天.

If the application needs more resources, a paid billing plan such as pay as you go is required. Spark计划免费限制仍然适用. 收费相当低. 价格可以在 Firebase pricing page.

在云中运行的虚拟机在运行时会产生费用, 即使它们没有被使用. Firebase无服务器解决方案可扩展到零. This means that resources are effectively only running when in use and do not incur charges when not in use. This is ideal for applications for seasonal businesses such as holiday rentals or periodic events such as concerts. 会有很多活动,然后是几个月的不活动.

How to Set Up Firebase

需要使用电子邮件账号进行认证. 建议使用谷歌邮件帐户. They can be created at http://mail.google.com.

还需要一个谷歌GCP (Cloud Platform)帐户. 可以免费试用 here. 这给了你300美元的信用额度,一年可用. 需要信用卡作为身份证明. b谷歌可能收取1美元,然后退款. The credit card will be debited monthly if billing is enabled and billable resources are used. 还有100家提供商公司充当结算的中介. 你向供应商支付云服务费用,他们支付100美元. 他们有自己的计费计划,可能会提供免费试用.

It is important to monitor the billing section of the cloud console frequently to monitor usage. 在不需要时,很容易保持存储等资源的活动状态, 随着时间的推移,哪一种会产生相当大的成本.

Firebase项目也是GCP项目. 您可以创建GCP项目并将其导入Firebase, 或者创建一个Firebase项目, 这也将创建一个GCP项目. The Firebase console is here.

不同类型的应用程序需要不同的设置. 主要是Android、iOS和web应用程序. 安装说明可以在官方的 Firebase Guides.

某些操作需要使用Firebase命令行工具. These require that Node.js and the npm tool are installed. 如果在macOS或Linux上运行,则 npm 命令将需要使用 sudo.

NPM安装-g firebase-tools

身份验证和授权

Firebase身份验证可能是使用最广泛的Firebase组件. 用户可以选择一种或多种身份验证机制. 这些是电子邮件地址和密码, telephone numbers, 和联邦身份提供者谷歌, Facebook, Twitter, and GitHub. 可以启用任意数量的身份验证机制.

Firebase UI提示用户使用的机制:

Firebase authentication

Firebase provides user interfaces for authentication that can be invoked from a few lines of code on the client side. 也有用于手动进行身份验证的api. 验证成功, 生成一个身份令牌,可用于后端验证.

这些api允许管理用户以编程方式管理用户. Operations include:

  • 创建、更新和删除用户
  • 通过电子邮件地址或电话号码等搜索条件查找用户
  • 访问信息,如帐户创建日期和最后登录日期和时间
  • Validate email addresses and telephone numbers without having to use the existing workflows

Most mobile and web applications want large numbers of users to sign into their applications. For example, anyone with a Google Mail account can authenticate themselves to any application that allows Google authentication. A form of authorization is required to restrict access to the application to certain users. This can be easily done by storing associations between email addresses and access roles in data storage. 身份验证成功后,将在数据存储中查找电子邮件地址. 是否存在具有正确角色的用户, then access is granted; otherwise, 强制注销用户.

Firebase Hosting

Firebase托管允许静态web内容, 其中包括JavaScript, 在云中托管而不需要web服务器. 内容被缓存在全局内容分发网络(CDN)的边缘。. 这允许从世界任何地方快速访问内容.

One or more websites can be hosted by adding them to the Hosting section of a Firebase project in the Firebase Console. 内容通过SSL传递,并给出两个形式为[http://site-name]的url.web.app] and http://site-name.firebaseapp.com, where site-name 是项目名称还是用户指定的站点名称.

It is very easy to have the site hosted from your own domain name provided you can change the DNS records for the domain. 在Firebase控制台将域名添加到站点. 然后,您将得到一个DNS TXT记录, 你必须将其添加到域名的DNS中以向谷歌证明你拥有该域名. TXT记录显示后,即可获取局点的DNS A记录. 自动为站点发放SSL证书. 一旦提供了证书,该站点就可以在全局范围内使用. 原则上,DNS更新和证书供应可能需要几个小时. 在实践中,这个过程可以在20分钟内完成.

要向主机添加内容,首先,为站点和创建一个目录 cd 从命令行输入. 接下来,登录Firebase并初始化项目目录.

firebase login
firebase init

系统将提示您选择一个项目以及需要哪些客户端服务. 服务总是可以在以后添加,而不必在这个阶段进行选择.

Create a file called firebase.json,它定义了网站根目录和要排除的文件. You will also need a .gitignore 文件从版本控制中排除文件.

{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

然后,将静态内容复制到公共目录中. 最后,将站点部署到云中.

firebase deploy

要更改web内容,只需更改内容文件并发出deploy命令. 每个部署在Firebase控制台中显示为一个版本. 只需单击一下就可以回滚到以前的版本.

Firebase Hosting还可以将uri重写为文件、云功能和云运行. This greatly 简化了事情,因为不需要为这些服务分配域. The rewrites are 通过向firebase的托管部分添加重写部分来定义.json. The hosting 如果服务不存在,部署将失败.

{
	"hosting": {
		"public": "public",
		"rewrites": [
		{
			"source": "/xxx",
			“目的地”:“/概要文件.html"
		},
		{
			"source": "/yyy",
			"function": "profile"
		},
		{
			"source": "/api{,/**}",
			"run": {	
				“serviceId”:“云api”,
				“地区”:“europe-west1”
			}
		}
		]
	}
}

Data Storage

Firebase提供了用于访问基于云的数据存储的客户端api. 存储有三种类型:

  • Realtime Database
  • Cloud Firestore
  • Cloud Storage

This allows mobile and web clients to store and retrieve data without the need for a server.

Realtime Database

实时数据库是一个云托管的NoSQL数据库. Data in the Realtime Database is automatically synchronized in real time to all connected devices. 它可以跨平台运行于Android, iOS和web. 数据存储为JSON树结构. 可以设置安全规则来控制对数据的读和写访问.

每个设备都保留数据库的本地副本. 这意味着数据在未连接到网络时可用. 在重新连接时,数据的本地副本和基于云的副本将同步.

数据由使用侦听器的应用程序读取. 侦听器侦听JSON树中的节点. 在控制台上或由其他用户更改数据时, 使用新数据值调用侦听器回调. 实时数据库也支持查询. 每个查询返回一个节点及其所有子节点.

默认情况下,安全规则不允许访问数据. 规则可以全局添加,也可以添加到JSON对象的单个节点. 安全规则控制对数据的读写访问,并可以执行验证.

Realtime Database is best suited to small pieces of data that do not require a deeply nested data structure. 免费限制是1GB的数据.

Cloud Firestore

Cloud Firestore被视为实时数据库的替代品. 它扩展了实时数据库的功能. 数据不在JSON树中,而是在文档的分层集合中. 每个文档由一组键值对和可选子文档组成. 查询允许更复杂的过滤和排序,并且只返回完整的文档. 查询不返回子文档.

云Firestore将很快取代云数据存储. 它可以在数据存储模式或本机模式下运行 mode. 所有数据存储应用程序将自动迁移到Cloud Firestore.

Cloud Firestore最适合相对较小的数据块. 它可以有一个深度嵌套的数据结构. 免费限制是1GB的数据.

Cloud Storage

云存储用于存储图像和视频剪辑等文件. Mobile and web clients can use Firebase to upload and download files directly to and from the cloud without the need for a back-end server. 免费限制是5GB的数据.

Cloud Functions

云功能是创建无服务器应用程序的重要技术. 云函数可以用JavaScript编写, TypeScript, Python, or Go, 直接部署到谷歌云中. A function is triggered by an HTTP request or by an event in the cloud such as writing to Cloud Storage.

一个云函数一次只能处理一个请求, 但是云会自动通过复制来扩展功能. 用Python编写的云函数使用Flask库来处理HTTP请求. 该函数接受一个请求对象作为参数,并返回响应体.

A simple Python Cloud Function requires a working directory, and the entry point goes in the file main.py.

def simple_cloud_function(请求):
    return "It worked"

依赖关系由pip管理,并放入一个名为 requirements.txt.

Flask==1.0.2

方法部署功能 gcloud command line tool. 它指定函数名、语言和触发器.

Gcloud函数部署simple_cloud_function——runtime python37 \ 
       --trigger-http

The URL for the function is displayed on deployment and can be found by running the describe command.

Gcloud函数描述simple_cloud_function
Url: http://europe-west1-project-id.cloudfunctions.net/simplecloud_function

Cloud Functions can call Google Cloud and Firebase APIs to provide back-end functionality. 它们提供关于执行启动和执行时间的日志信息. 可以很容易地添加额外的日志记录. 日志可以在Stackdriver Logging UI中查看,也可以通过 gcloud command line tool.

Gcloud函数日志读取simple_cloud_function 

在谷歌云控制台中可以查看和删除功能.

谷歌云控制台:功能

云函数最适合用于相对不频繁发生的操作. 一个使用示例是在将图像上传到云存储时创建缩略图. 免费的上限是每月125,000次调用.

Cloud Run

Cloud Run is recently added functionality that greatly facilitates serverless applications. It enables Docker containers to be run in the cloud without having to do complex infrastructure setup. 它可以在托管模式下运行,这种模式使用Knative运行时,Knative运行时构建在Kubernetes上. 它也可以在Anthos上运行, which is also built on Kubernetes but allows containers to be run across clouds and even on your own data center. There is no need to set up and manage a Kubernetes cluster as it is all done automatically.

任何可以构建到Docker镜像中的应用程序都可以通过Cloud Run进行管理. 它会根据需求自动扩展容器的数量. 当服务不被使用时,它也会缩减为零. 未使用的服务不收取任何费用.

如果要响应HTTP请求,Docker容器需要运行web服务器. Python服务将使用Flask. 入口就在里面 app.py.

从flask中导入flask

app = Flask(__name__)

@app.route(’/api/profile’)
def profile():
	page = ’’’
Page content
	’’’
	return page

The application needs a Dockerfile to create the image.

FROM python
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . .
ENV PORT 8080
运行pip安装Flask gunicorn firebase-admin
CMD exec gunicorn——绑定:$PORT——工人1——线程8 app:app

Cloud Run容器直接部署到云中.

Gcloud运行deploy——image=image_name——platform=managed \
       ——区域= europe-west1——允许匿名  

If the service name, platform, region, or whether to allow unauthenticated are not defined in the project configuration or supplied on the command line, 他们将被提示. Once 部署完成后,将显示服务URL. URL也可以通过命令获取 the gcloud command.

gcloud run services list
  最后一次部署的服务区域url
   Cloud-api europe-west1 http://cloud-api-h42ifbxkyq-ew.a.run.app myemail@gmail.com 2020-02-05T10:53:30.006Z

URL包含一个难以管理的随机数. 这就是Firebase Hosting重写规则变得最有用的地方.

在谷歌云控制台中可以查看和删除服务.

谷歌云控制台:服务

Cloud Run非常适合托管REST API. 每月免费限额是180英镑,000 CPU seconds, 360,000 GB seconds of memory, 2 million requests, and 1GB network egress. The free network egress limit only applies if the service is deployed in a North America region.

Authentication

By default, Cloud Functions and Cloud Run containers are public and can be accessed by anybody on the internet. 在Cloud Console中使用IAM规则, 服务可以仅限于项目成员, Google Groups, 个人邮箱地址.

如果有限制,则禁止未经授权的访问. 要启用访问,必须向请求标头添加标识令牌. The identity token can be obtained using the gcloud command or during the Firebase authentication process.

Gcloud认证打印身份令牌

需要一个Authorization头.

授权方式:承载id-token

Summary

Google Cloud Platform and Firebase provide a range of products that greatly facilitate the development of mobile and web applications. The need for a back-end server can be completely eliminated by allowing clients to access cloud functionality directly or by deploying back-end code into the cloud using Cloud Functions or Cloud Run.

现有的应用程序可以增量地迁移到无服务器. In fact, the way the technology is evolving could mean that traditional virtual machine-based server solutions will no longer be necessary.

Understanding the basics

  • What apps use Firebase?

    需要用户身份验证、数据存储、消息传递和使用统计的应用程序.

  • Firebase只适用于移动应用吗?

    不,它也可以用于网络应用和管理应用.

  • Firebase的优势是什么?

    它提供了许多应用程序需要的开箱即用、易于使用的功能.

  • Firebase的目的是什么?

    It is designed to allow mobile and web front-end developers to access cloud-based server functionality without the need for a server.

  • 什么时候应该使用Firebase?

    在开发新应用程序或增强现有应用程序时,请考虑使用Firebase.

就这一主题咨询作者或专家.
Schedule a call
菲利普·爱德华兹的头像
Phillip Edwards

Located in Marseillan, France

Member since October 10, 2018

About the author

Phillip在软件开发的各个方面都有丰富的经验. 最近,他一直在使用谷歌Firebase开发应用程序.

Toptalauthors are vetted experts in their fields and write on topics in which they have demonstrated experience. 我们所有的内容都经过同行评审,并由同一领域的Toptal专家验证.

Previously At

Okta

世界级的文章,每周发一次.

订阅意味着同意我们的 privacy policy

世界级的文章,每周发一次.

订阅意味着同意我们的 privacy policy

Toptal Developers

Join the Toptal® community.