Step | Description |
- | |
Use the Serverless Framework VPC component to create a VPC and subnet for communications between the function and the database. | |
Use the Serverless Framework TDSQL-C component to create a MySQL instance to provide database services for the function project. | |
Use the Serverless DB SDK to call the database. SCF allows you to directly call the Serverless DB SDK to connect to and manage a PostgreSQL database. | |
Use Serverless Framework to deploy the project in the cloud and test it in the SCF console. | |
You can use Serverless Framework to remove the project. |
test-MySQL
folder as an example.mkdir test-MySQL && cd test-MySQL
ap-beijing-3
, ap-guangzhou-4
, ap-shanghai-2
, and ap-nanjing-1
, so you need to create the .env
file in the project root directory and then configure the two environment variables REGION
and ZONE
:# .envREGION=xxxZONE=xxx
VPC
folder in the test-MySQL
directory.mkdir VPC && cd VPC
serverless.yml
file in VPC
and use the VPC component to create the VPC and subnet.
The sample content of serverless.yml
is as follows (for all configuration items, please see the product documentation):#serverless.ymlapp: mysql-appstage: devcomponent: vpc # (required) name of the component. In that case, it's vpc.name: mysql-app-vpc # (required) name of your vpc component instance.inputs:region: ${env:REGION}zone: ${env:ZONE}vpcName: serverless-mysqlsubnetName: serverless-mysql
DB
folder in test-MySQL
.serverless.yml
file in the DB
folder and enter the following content to use the Serverless Framework component to configure the TCB environment:
The sample content of serverless.yml
is as follows (for all configuration items, please see the product documentation):# serverless.ymlapp: mysql-appstage: devcomponent: cynosdbname: mysql-app-dbinputs:region: ${env:REGION}zone: ${env:ZONE}vpcConfig:vpcId: ${output:${stage}:${app}:mysql-app-vpc.vpcId}subnetId: ${output:${stage}:${app}:mysql-app-vpc.subnetId}
src
folder in test-MySQL
to store the business logic code and relevant dependencies.index.js
file in the src
folder and enter the following sample code, so that you can use the SDK to connect to the MySQL database through the function and call the database in the environment:exports.main_handler = async (event, context, callback) => {var mysql = require('mysql2');var connection = mysql.createConnection({host : process.env.HOST,user : 'root',password : process.env.PASSWORD});connection.connect();connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {if (error) throw error;console.log('The solution is: ', results[0].solution);});connection.end();}
npm install mysql2
serverless.yml
file as shown below:app: mysql-appstage: devcomponent: scfname: mysql-app-scfinputs:src: ./functionName: ${name}region: ${env:REGION}runtime: Nodejs10.15timeout: 30vpcConfig:vpcId: ${output:${stage}:${app}:mysql-app-vpc.vpcId}subnetId: ${output:${stage}:${app}:mysql-app-vpc.subnetId}environment:variables:HOST: ${output:${stage}:${app}:mysql-app-db.connection.ip}PASSWORD: ${output:${stage}:${app}:mysql-app-db.adminPassword}
./test-MySQL├── vpc│ └── serverless.yml # VPC configuration file├── db│ └── serverless.yml # Database configuration file├── src│ ├── serverless.yml # SCF component configuration file│ ├── node_modules # Project dependency file│ └── index.js # Entry function└── .env # Environment variable file
test-MySQL
on the command line:sls deploy
mysql-app-vpc:region: xxxzone: xxxvpcId: xxxx-xxx...mysql-app-db:dbMode: xxxxregion: xxxxzone: xxxx...mysql-app-scf:functionName: xxxxdescription: xxx...59s › test-MySQL › "deploy" ran for 3 apps successfully.
test-MySQL
directory to remove the project:sls remove
serverless ⚡ framework4s › test-MySQL › Success
# -*- coding: utf8 -*-from os import getenvimport pymysqlfrom pymysql.err import OperationalErrormysql_conn = Nonedef __get_cursor():try:return mysql_conn.cursor()except OperationalError:mysql_conn.ping(reconnect=True)return mysql_conn.cursor()def main_handler(event, context):global mysql_connif not mysql_conn:mysql_conn = pymysql.connect(host = getenv('DB_HOST', '<YOUR DB HOST>'),user = getenv('DB_USER','<YOUR DB USER>'),password = getenv('DB_PASSWORD','<YOUR DB PASSWORD>'),db = getenv('DB_DATABASE','<YOUR DB DATABASE>'),port = int(getenv('DB_PORT','<YOUR DB PORT>')),charset = 'utf8mb4',autocommit = True)with __get_cursor() as cursor:cursor.execute('select * from employee')myresult = cursor.fetchall()print(myresult)for x in myresult:print(x)
'use strict';const DB_HOST = process.env[`DB_HOST`]const DB_PORT = process.env[`DB_PORT`]const DB_DATABASE = process.env[`DB_DATABASE`]const DB_USER = process.env[`DB_USER`]const DB_PASSWORD = process.env[`DB_PASSWORD`]const promisePool = require('mysql2').createPool({host : DB_HOST,user : DB_USER,port : DB_PORT,password : DB_PASSWORD,database : DB_DATABASE,connectionLimit : 1}).promise();exports.main_handler = async (event, context, callback) => {let result = await promisePool.query('select * from employee');console.log(result);}
<?phpfunction handler($event, $context) {try{$pdo = new PDO('mysql:host= getenv("DB_HOST");dbname= getenv("DB_DATABASE"),getenv("DB_USER"),getenv("DB_PASSWORD")');$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch(PDOException $e){echo 'Databases connection failed: '.$e->getMessage();exit;}}
<?phpfunction main_handler($event, $context) {$host = "";$username = "";$password = "";// Create a connection$conn = mysqli_connect($servername, $username, $password);// Test the connectionif (!$conn) {die("Connection failed: " . mysqli_connect_error());}echo "Connected successfully";mysqli_close($conn);echo "Disconnected";}?>
<dependencies><dependency><groupId>com.tencentcloudapi</groupId><artifactId>scf-java-events</artifactId><version>0.0.2</version></dependency><dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId><version>3.2.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency></dependencies>
package example;import com.qcloud.scf.runtime.Context;import com.qcloud.services.scf.runtime.events.APIGatewayProxyRequestEvent;import com.qcloud.services.scf.runtime.events.APIGatewayProxyResponseEvent;import com.zaxxer.hikari.HikariConfig;import com.zaxxer.hikari.HikariDataSource;import javax.sql.DataSource;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.HashMap;import java.util.Map;public class Http {private DataSource dataSource;public Http() {HikariConfig config = new HikariConfig();config.setJdbcUrl("jdbc:mysql://" + System.getenv("DB_HOST") + ":"+ System.getenv("DB_PORT") + "/" + System.getenv("DB_DATABASE"));config.setUsername(System.getenv("DB_USER"));config.setPassword(System.getenv("DB_PASSWORD"));config.setDriverClassName("com.mysql.jdbc.Driver");config.setMaximumPoolSize(1);dataSource = new HikariDataSource(config);}public String mainHandler(APIGatewayProxyRequestEvent requestEvent, Context context) {System.out.println("start main handler");System.out.println("requestEvent: " + requestEvent);System.out.println("context: " + context);try (Connection conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM employee")) {ResultSet rs = ps.executeQuery();while (rs.next()) {System.out.println(rs.getInt("id"));System.out.println(rs.getString("first_name"));System.out.println(rs.getString("last_name"));System.out.println(rs.getString("address"));System.out.println(rs.getString("city"));}} catch (SQLException e) {e.printStackTrace();}APIGatewayProxyResponseEvent apiGatewayProxyResponseEvent = new APIGatewayProxyResponseEvent();apiGatewayProxyResponseEvent.setBody("API GW Test Success");apiGatewayProxyResponseEvent.setIsBase64Encoded(false);apiGatewayProxyResponseEvent.setStatusCode(200);Map<String, String> headers = new HashMap<>();headers.put("Content-Type", "text");headers.put("Access-Control-Allow-Origin", "*");apiGatewayProxyResponseEvent.setHeaders(headers);return apiGatewayProxyResponseEvent.toString();}}
'use strict';const database = require('scf-nodejs-serverlessdb-sdk').database;exports.main_handler = async (event, context, callback) => {let pool = await database('TESTDB2').pool()pool.query('select * from coffee',(err,results)=>{console.log('db2 callback query result:',results)})// no need to release poolconsole.log('db2 query result:',result)}
from serverless_db_sdk import databasedef main_handler(event, context):print('Start Serverlsess DB SDK function')connection = database().connection(autocommit=False)cursor = connection.cursor()cursor.execute('SELECT * FROM name')myresult = cursor.fetchall()for x in myresult:print(x)
Was this page helpful?