Author: Han Xi | Ali Yunyun native middleware front-end leader

How to use the Serverless architecture to realize the application of full-duplex communication, how to use the database in the Serverless architecture, this article will reveal the answer for you.

Serverless’s philosophy is instant resiliency, run out of time. The service is not long running, which means that long-link request patterns like WebSocket do not seem to be suitable for Serverless.

Is there another way to satisfy long-connection mode requests while taking advantage of Serverless itself?

The answer is yes. In the last article, we talked about the key role of gateways, so this time we also use gateways to solve the problem of full-duplex communication. This time, we will take the bullet-screen scenario as an example to show you how we use the Serverless architecture to achieve this scenario.

Application preview

There are many practical scenarios for danmu application, such as operation and promotion, annual activities and so on. But it usually takes a long time to implement a controlled process and deploy it. This will let you deploy your barrage app in under 2 minutes. You can use it to enrich the format of your company’s annual party. At the end of the article will also be affixed with the source code, can be for your reference and second customization.

Architecture in

Overall architecture is still the DNS – > gateway – > oss | fc. Different is divided into three static resources of the project, the function part uses the combination of event-driven and HTTP, and API part uses TableStore for data persistence.

The process that

Danmu application is composed of three clients: big screen, individual user and administrator, as well as a service & API service for registering devices. The long link between the client and the server is carried by the gateway. Every time the client connects to the gateway, the gateway will store the device number and trigger a registration function, and the device number is stored in the TableStore.

When a user initiates a barrage through the gateway to the API service, the API service will make a query to determine whether the barrage is controlled or not. If there is no control, the current device ID of the big screen will be directly searched and the gateway will make a downlink call. The gateway will display data on the page sent to the front end. If it is controlled, it queries the online administrator device, sends the downlink notification to the gateway, and the gateway sends it to the front-end page of the administrator.

Data table design

  • Equipment (equipment)

  • Barrage

  • Interceptor (filter)

The preparatory work

Like the previous “every man is Serverless architects | modern Web application development of actual combat, the article need ready ahead of time domain, and installed Serverless Devs developer tools, and the following products:

  • Cloud analytical DNS
  • API gateway
  • Function to calculate
  • Object storage OSS
  • Tablestore

This time we introduced tableStore database memory data persistence function, also need to create a good database instance standby.

steps

For better demonstration, this demo uses ServerlessDesktop to show you how to deploy a complex bullet-screen application in 2 minutes. You can select Serverless Devs Cli or Serverless Desktop as required to initialize and deploy the danmu application.

1) Key configuration

Refer to the key documentation:

​​​​http://www.serverless-devs.com/zh-cn/docs/provider-config/alibabacloud.html​​​​

2) Initialization

In addition to the need to download the application template to the local, it will also help initialize the tableStore table and data, so you need to pre-configure several parameters:

  • Key alias – corresponding to your Aliyun account
  • Domain name – Custom domain name
  • BucketName – The bucket name of OSS
  • Endpoint – Public network access address of the TableStore instance
  • Instance – The instance name of the tableStore

After the pre-configuration parameters are written, click “OK” and the next job is called Serverless Devs, which will initialize the table of the barrage application for us.

3) Build deployment

After initialization, we re-enter the configuration page to deploy the project. Config info -> Full operation -> Deploy click and the rest is sent to Serverless Devs, which helps us complete:

  1. Big screen, manage backend and player front-end deployment;
  2. Register functions and the deployment of API functions
  3. And gateway routing Settings and gateway domain name binding

4) Check the deployment effect

  • The gateway

  • Function to calculate

  • Oss

  • DNS

When accessing barragego.serverbasic developer.com, we found that the access is different. The reason is that the apigateway domain name and the OSS domain name are not bound successfully.

To see the results, visit barragego.serverbasic developer.com:

Database Details

The database aspect wants to take out to say, the main database that uses this time is really relatively new, namely tableStore.

1) Database configuration transfer

It can be seen that we have filled in the public network access address and instance name information of the database when initializing the application. During initialization, the user’s input configuration will be written into S.Yaml. It is recommended to extract sensitive information from S. yaml and put it into the.env environment. And ignore this file to reduce the risk of database information being leaked into the repository.

Eventually Devs will put these two basic information into the environment variables that the function evaluates and then each runtime can fetch these values from the environment variables, such as process.env.instance, where nodejs is running.

In addition to the instance name and public access address, database initialization also requires the user’s secret key information. In view of the high sensitivity of the secret key information, it is not recommended to directly configure the secret key information in S. aml, but to allow the function to build temporary secret key information by granting the tableStore role permissions to the function service.

  • Function service authorization configuration is as follows:

  • The key information obtained in the function is as follows:

2) Database initialization

To reduce the number of database initialization times, we can initialize the function in the initializer method, so that when the function is not released, the database instance can be used directly without reconnecting. This reduces the request response time. It is more practical in the case of single instance and multiple concurrency.

exports.initializer = (context, callback) => { try { const ak = context.credentials.accessKeyId; const sk = context.credentials.accessKeySecret; const stsToken = context.credentials.securityToken; SAT.init(endpoint, instance, ak, sk, stsToken); internal = { tableClient: SAT, TableStore }; callback(); } catch (err) { callback(err.message); }}Copy the code

After the database instance is initialized, we get the instance from other methods by assigning to global variables for subsequent operations.

3) the CRUD

Tablestore native API to do CRUD operation user experience is not friendly, TableStore community provides a good encapsulation of SAT. It will be very convenient for us to do basic add, delete, change and check, and the code will look very clean.

/ / a single primary key query const getInterceptor = async (CTX) = > {const {tableClient} = CTX. The req. RequestContext. Internal; const res = await tableClient.table('interceptor').get(1, cols = []); return res; // Query all const getAllEquipment = async (tableClient,TableStore) => {const res = await tableClient.table('equipment').getRange(TableStore.INF_MIN, TableStore.INF_MAX, cols = []) return Object.keys(res).map((key)=> res[key]); } // Double primary key (one partition key, A) on the key insert const addBarrage = async (CTX) = > {const {tableClient, TableStore} = CTX. The req. RequestContext. Internal; const { fromId, fromName, color, fontSize = '28px', checkStatus = 0, message } = ctx.request.body; const currentTime = Date.now().toString(); const newData = Object.assign({}, { fromId, fromName, color, fontSize, checkStatus: parseInt(checkStatus), message }, { sendTime: currentTime, checkTime: currentTime }); const res = await tableClient.table('barrage', ['gid', 'id']).put([1, TableStore.PK_AUTO_INCR], newData, c = 'I'); return res; } / / update const updateBarrage = async (CTX) = > {const {tableClient} = CTX. The req. RequestContext. Internal; const { checkStatus } = ctx.request.body; const { id } = ctx.request.params; const currentTime = Date.now().toString(); const res = await tableClient.table('barrage', ['gid', 'id']).update([1, parseInt(id)], { checkStatus: parseInt(checkStatus), checkTime: currentTime }, c = 'I') return res; } const getBarrageByCondition = async (CTX) => {const {tableClient, TableStore } = ctx.req.requestContext.internal; const res = await tableClient.table('barrage').search('index', ['checkStatus', 0]) return res; }Copy the code

Of course, if you want to do more advanced queries, you need to consult the official website documentation.

conclusion

The project itself is an example of how Websocket can be used by Serverless. You can turn it into any similar form of application, such as chat room, multiplayer collaboration platform, etc.

The app itself also has a lot of room for improvement, such as adding “like” effect, the control section can add administrator login registration, etc. In short, you can customize more advanced functions according to their own needs, the relevant source code has been provided for your reference. In the next chapter, I’ll continue talking about Serverless and low code scenarios and share a recent practice we’ve been working on.

A link to the

1) Serverless Devs:

Github.com/Serverless-…

2) Cloud DNS resolution:

wanwang.aliyun.com/domain/dns

3) API Gateway:

www.aliyun.com/product/api…

4) Function calculation:

www.aliyun.com/product/fc

5) Object storage OSS:

www.aliyun.com/product/oss

6) ServerlessDesktop:

www.serverless-devs.com/zh-cn/deskt…

7) Serverless Devs Cli:

www.serverless-devs.com/zh-cn/cli/i…

8) Serverless Hub:

Serverlesshub.resume.net.cn/#/hubs/spec…

9) Tablestore:

www.aliyun.com/product/ots

10) Official website Documents:

Help.aliyun.com/document_de…

11) Source code:

​​https://github.com/devsapp/start-barrage​​

About the author:

Wang Qing (Hanxi) | Head of aliyunyun native middleware front-end

In 2016, I joined Ali Middleware, engaged in the r&d of enterprise console of cloud products, and was responsible for the front-end r&d of more than 20 cloud products of middleware. The main technology stack is the general technology of big front-end. At present, I focus on the construction of Serverless developer tool chain, and I am one of the r&d leaders of cloud native Serverless Devs.

Click here to skip to Serverless Devs~