Introduction: How to use the Serverless architecture to achieve full duplex communication applications, Serverless architecture is how to use the database, this article will reveal the answer for you.

The author | cold inclined greetings native middleware, head of the front-end (ali)

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)

1. Preparation

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.

2. Operation 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:

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

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

At this time to visit

barragego.serverless-developer.com

The apigateway domain name and the OSS domain name are not bound successfully.

Next visit

barragego.serverless-developer.com

You can see the effect:

2. 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);

}

}

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.

// Single primary key query

const getInterceptor = async (ctx) => {

const { tableClient } = ctx.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]);

}

// Insert double primary keys (one partition key, one increment key)

const addBarrage = async (ctx) => {

const { tableClient, TableStore } = ctx.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.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;

}

// Conditional query

const getBarrageByCondition = async (ctx) => {

const { tableClient, TableStore } = ctx.req.requestContext.internal;

const res = await tableClient.table(‘barrage’).search(‘index’, [‘checkStatus’, 0])

return res;

}

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.

The original link

This article is the original content of Aliyun and shall not be reproduced without permission.