In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
Today, I would like to talk to you about what the full-stack solution based on Serverless Component is, many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.
What is Serverless Component?
Serverless Component is a Serverless Framework-based scenario that supports multiple cloud resource orchestrations and organizations.
The goal of Serverless Component is to smooth out the differences between different cloud service platforms, and you can think of it as a dependency module that makes it easier to build applications. At present, Serverless Component has formed an ecosystem driven by community contributions, and you can browse and use all the components of the community to quickly develop an application you want.
How Serverless Component works
Based on the Serverless Component architecture, you can package any cloud service into a component. This component will contain a serverless.yml configuration file and can be used by simply configuring it. This article uses @ serverless/tencent-express as an example.
If we want to use it, we just need to create a new project express-demo, and then modify the serverless.yml configuration as follows:
Express: component:'@ serverless/tencent-express' inputs: region: ap-shanghai
Because the authentication deployed to the cloud by the serverless framework is based on global variables injected by dotenv, you need to add a .env file to the root directory and configure the corresponding authentication parameters.
Then we can easily write express-based interface services in app.js:
Const express = require ('express') const app = express () app.get (' /', function (req, res) {res.send ('Hello Express')}) / / Don't forget to export, because the component wraps it and outputs the cloud function module.exports = app
All the process logic behind this is implemented within the component, including the deployment of cloud functions, the generation of API gateways, and so on.
Here is a simple component dependency diagram:
Through this diagram, you can clearly see the benefits of the components, and with the community's existing @ serverless/tencent-express and @ serverless/tencent-website components, we can quickly build the full-stack application we want.
Full stack application practice
Next, we will introduce how to quickly develop full-stack Web applications with Serverless Component.
Before starting all the steps, you need to execute the npm install-g serverless command to install serverless cli globally.
Prepare for
Create a new project directory fullstack-application-vue, and add api and dashboard directories to the project directory. Then add serverless.yml and .env configuration files, and the project directory structure is as follows:
├── README.md / / Project description document ├── api / / Restful api backend service ├── dashboard / / frontend page ├── .env / / Tencent Cloud related authentication parameters: TENCENT_APP_ID,TENCENT_SECRET_ID TENCENT_SECRET_KEY └── serverless.yml / / serverless file back-end service development
Enter the directory api, add the app.js file, and write the express service code. First, add a route /, and return the current server time:
Const express = require ('express') const cors = require (' cors') const app = express () app.use (cors ()) app.get ('/', (req, res) = > {res.send (JSON.stringfy ({message: `Server time: ${new Date (). ToString ()})) module.exports = app front-end page development
This case uses the front-end template of Vue.js + Parcel, and of course you can use any front-end project scaffolding, such as the Vue CLI-generated project officially recommended by Vue.js. Enter the dashboard directory and use static resources to directly copy the project template I have prepared and write the entry file src/index.js:
/ / there is no env.js module at the beginning. Require ('.. / env') const Vue = require ('vue') module.exports = new Vue ({el:' # root', data: {message: 'Click meteorology, isVisible: true,}, methods: {async queryServer () {const response = await fetch (window.env.apiUrl) const result = await response.json () this.message = result.message},},}) configuration is automatically generated after the first deployment
Now that the front and back end code is ready, we need to simply configure the serverless.yml file:
Name: fullstack-application-vuefrontend: component:'@ serverless/tencent-website' # inputs is the input of @ serverless/tencent-website component # specific configuration instructions refer to: https://github.com/serverless-components/tencent-website/blob/master/docs/configure.md inputs: code: src: dist root: frontend hook: npm run build env: # after the API service is deployed Get the corresponding api request path apiUrl: ${api.url} api: component:'@ serverless/tencent-express' # inputs is the input of @ serverless/tencent-express component # specific configuration instructions refer to: https://github.com/serverless-components/tencent-express/blob/master/docs/configure.md inputs: code:. / api functionName: fullstack-vue-api apigatewayConf: protocol: https
A brief introduction to the configuration: first, the file defines two modules, frontend and api, which specify the dependent Serverless Component through the component attribute, respectively. For a standard Serverless Component, an inputs attribute parameter is accepted, and then the component will be processed and deployed according to the configuration of the inputs. For more information on the configuration parameters, please refer to the official configuration instructions of the relevant components.
Deployment
After all the above steps are completed, it is time to deploy for the first time.
Why not directly co-ordinate development? Because the back-end service is a cloud function, but so far, all the code has been written locally, and the request link to the front-end page interface does not exist. Therefore, you need to deploy the cloud function to the cloud before debugging the front and back end. This is also the pain point I have encountered at present, because every time I modify the back-end service, I need to redeploy it, and then carry out front-end development and debugging. If you have any better suggestions, you are welcome to comment.
When deploying, you only need to run the serverless command. Of course, if you need to view the DEBUG information in the deployment, you also need to add the-- debug parameter, as follows:
$serverless# or$ serverless-debug
Then the balabalabala~, outputs a lot of DEBUG information, and all you need to do is see the green done:
Such a full-stack application based on Serverless Component is developed. Click on the link you have deployed and experience it.
Online Demo
Database connection
Since it is a full stack, how can there be less read and write to the database? Next, we will show you how to add read and write operations to the database.
Prepare for
If you want to operate a database, you must first have a database instance. Tencent Cloud MySQL Cloud Database is also very cheap. You can buy a basic postpaid one core and one gigabyte memory for less than 40 cents an hour. Isn't that a great deal? Initialize the configuration after purchase, and then add a new serverless database and a new users table:
CREATE TABLE if not exists `test` (`name` varchar (32) NOT NULL, `email` varchar (64) NOT NULL, `site` varchar (128NOT NULL) ENGINE = innodb DEFAULT CHARACTER SET = "utf8mb4" COLLATE = "utf8mb4_general_ci" frontend modification
First, modify the frontend entry file frontend/src/index.js and add related function operations:
Require ('.. / env') const Vue = require ('vue') const axios = require (' axios') module.exports = new Vue ({el:'# root', data: {/ /. Form: {name:', email:', site:',}, userList: [],}, methods: {/ /... / get the user list async getUsers () {const res = await axios.get (window.env.apiUrl + 'users') this.userList = (res.data & & res.data.data) | []} / / add a user async addUser () {const data = this.form const res = await axios.post (window.env.apiUrl + 'users', data) console.log (res) if (res.data) {this.getUsers ()},}, mounted () {/ / View is hung after Get user list this.getUsers ()},})
Of course, you also need to modify the view template file frontend/index.html to add a user list and user form to the page template:
Name: Email: Site: Submit
Name: {{item.name}} Email: {{item.email}} Site: {{item.site}}
No Data
Note: if you are not familiar with Vue.js syntax, please move to the official documentation, of course, if you want to get started with Vue.js development, you can also read this Vue tutorial from getting started to mastering it.
Backend modification
Here, use .env to configure the database connection parameters, add the .env file in the api directory, fill the previous database configuration into the file, and refer to the api/.env.example file. Then add and install dotenv dependencies, add mysql2 module to operate database, and body-parser module to parse body during POST request.
After that, the backend api is added to read and write the database. The modified api/app.js code is as follows:
'use strict'require (' dotenv'). Config () const express = require ('express') const cors = require (' cors') const mysql = require ('mysql2') const bodyParser = require (' body-parser') / / init mysql connectionfunction initMysqlPool () {const {DB_HOST, DB_PORT, DB_DATABASE, DB_USER, DB_PASSWORD} = process.env const promisePool = mysql .createPool ({host: DB_HOST, user: DB_USER, port: DB_PORT Password: DB_PASSWORD, database: DB_DATABASE, connectionLimit: 1,}). Const app = express () app.use (bodyParser.json ()) app.use (cors ()) if (! app.promisePool) {app.promisePool = initMysqlPool ()} app.get ('/', (req) Res) = > {res.send (JSON.stringify ({message: `Server time: ${new Date (). ToString ()}) / get user listapp.get ('/ users', async (req, res) = > {const [data] = await app.promisePool.query ('select * from users') res.send (JSON.stringify ({data: data,}))}) / add new userapp.post (' / users', async (req)) Res) = > {let result = 'try {const {name, email, site} = req.body const [res] = await app.promisePool.query (' INSERT into users SET?', {name: name, email: email, site: site,}) result = {data: res & & res.insertId, message: 'Insert Success',}} catch (e) {result = {data: e Message: 'Insert Fail',}} res.send (JSON.stringify (result))}) module.exports = app configuration modification
Here, the database needs to be accessed through Tencent Cloud VPC, so you also need to configure VPC for the cloud function, and you also need to configure roles that can operate the database (for role configuration, you can go directly to the role management page). Here, I have created a new role of QCS_SCFFull, which can be used to access the database. Then modify the configuration in serverless.yml:
#... api: component:'@ serverless/tencent-express' # more configuration for @ serverless/tencent-website, # refer to: https://github.com/serverless-components/tencent-express/blob/master/docs/configure.md inputs: code:. / api functionName: fullstack-vue-api role: QCS_SCFFull # this role must have access to the database functionConf: # this is used to access the VPC of the newly created database You can view vpcConfig: vpcId: vpc-6n5x55kb subnetId: subnet-4cvr91js apigatewayConf: protocol: https on your database instance management page.
Finally, just redeploy it.
After reading the above, do you have any further understanding of the full-stack solution based on Serverless Component? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.