Function Compute: Function Compute is an event-driven, fully managed computing service. With functional computing, you don’t need to purchase and manage infrastructure such as servers; you just write and upload code. Functional computing prepares you for computing resources, runs tasks flexibly and reliably, and provides log query, performance monitoring, and alarm capabilities. With functional computing, you can quickly build any type of application or service and only pay for the resources that the task actually consumes.

Accessing the SQL Server database refers to the operation of inserting and querying the database through TCP protocol by writing code to call the database driver library in the function calculation. Generally, different function instances running in function calculation do not share state. For structured data, they can be persisted in the form of database to achieve state sharing. Since user functions run in the FUNCTIONAL computing VPC and user databases run in the VPC to which the user belongs, database access on the functional computing platform involves cross-VPC access. The following describes the working mechanism.

Working mechanism

The working mechanism of accessing the SQL Server is the same as that of accessing the Mysql database. This document does not repeat this description. For more details, see the working mechanism of Accessing the Mysql Database.

Configuration and function writing

Common configuration

Create a private network VPC

  1. Log in to the VPC console.
  2. See Configuring Private Networks in a VPC. Create a VPC and a switch.

Creating a Security Group

Create a security group on the security group console, click Create Security Group, set the security group name, set network type to private network, and select the created private network.

Create and configure an SQL Server instance

  1. For details about how to create cloud DATABASE SQL Server edition that meets service requirements, see Cloud Database SQL Server Edition.

Note: To create the SQL Server instance of the cloud database, you need to select the SAME VPC instance that is configured for functional computing. You can configure switches in different availability zones for the cloud database because the Intranet of switches in different availability zones in the same VPC instance can communicate with each other.

  1. After the creation, click Data Security in the navigation tree on the left of the instance information page.

  2. Click to add a whitelist group.

  3. In the dialog box that is displayed, set the network segment IP address of the VPC to the whitelist.

    1. Log in to the VPC console, locate the VPC to which the application belongs in the private network list, and click the VPC name. The private network details page is displayed.
    2. Of the VPC to which the application residesIPv4 network segment.
    3. inWhitelist of the groupThe VPC is pasted in the configuration boxIPv4 network segmentAddress and clickdetermine.
  4. Finally, access the SQL Server database host as the Intranet address of the instance. You can log in to the Ali Cloud console to view:

Function to calculate and configure a VPC

Note: The region of the function computing service is the same as the region of the resource created in the common configuration.

  1. inFunctional computing consoleCreate a service.
    • For details about how to create a service, see “Add, Delete, Modify, and Query services” in this article
  2. From Private Network Configuration, select the VPC network, switch, and security group created in Step 1.
  3. In the “Permission Configuration” option, select “Create a role” and click “Click Authorization”. In the “Quick Role Creation” page, click “Agree Authorization”.
    • This step grants the computing function the operation permission to ENI. For details about the computing function’s permission to access resources in the VPC, see Configuring computing Function to Access Resources in the VPC
  4. Click OK to create a service.

Python3 and PHP7.2 use python to access the SQL Server database.

Use Fun to install dependencies and project deployment in the create code and dependency module directory.

Python3

  1. Create a template.yml file in this directory, for example, / TMP /code/template.yml.
ROSTemplateFormatVersion: '2015-09-01'
Transform: 'Aliyun::Serverless-2018-04-03'
Resources:
  SQL-Server-test:
    Type: 'Aliyun::Serverless::Service'
    Properties:
  	Description: This is SQL-Server service
  	Role: 'acs:ram::xxxxx:role/fc-public-test'
  	LogConfig:
  	  Project: xxx
  	  Logstore: xxx
  	VpcConfig:
  	  VpcId: vpc-xxx
  	  VSwitchIds:
  		- vsw-xxx
  	  SecurityGroupId: sg-xxx
  	InternetAccess: true
    python-test:
  	Type: 'Aliyun::Serverless::Function'
  	Properties:
  	  Handler: 'index.handler'
  	  Runtime: python3
  	  Timeout: 10
  	  MemorySize: 128
  	  CodeUri: '/'
Copy the code
  1. Create a Funfile in this directory with the following contents:

    RUNTIME python3
    RUN fun-install pip install pymssql
    Copy the code
  2. Run the fun install command to install dependencies:

    $ fun install
    using template: template.yml
    start installing functionDependencies without Docker Dependencies without Docker Install SuccessCopy the code
  3. Create a new code file in the function root directory, such as/TMP /code/index.py:

    # -*- coding: utf-8 -*-
    import pymssql
    def handler(event, context):
    
    	conn = pymssql.connect(host='rm-xxx.sqlserver.rds.aliyuncs.com',
    								user='xxx, password='xxx', database='xxx', charset='utf8') cursor = conn.cursor() cursor.execute('SELECT * FROM inventory WHERE quantity > 152') result = '' for row in cursor: result += 'row = %r\n' % (row,) conn.close() return resultCopy the code
  4. Deploy with fun:

    $ fun deploy using template: template.yml using region: cn-hangzhou using accountId: ***********3743 using accessKeyId: ***********Ptgk using timeout: 60 Deployment process...function python-test deploy success
    service SQL-Server-test deploy success
    Copy the code

Log in to the console, and you can see that the related services and functions have been created successfully, and the triggered execution returns the correct results.

PHP7.2

  1. Create a template.yml file in this directory, for example, / TMP /code/template.yml.

    ROSTemplateFormatVersion: '2015-09-01'
    Transform: 'Aliyun::Serverless-2018-04-03'
    Resources:
      SQL-Server-test:
    	Type: 'Aliyun::Serverless::Service'
    	Properties:
    	  Description: This is SQL-Server service
    	  Role: 'acs:ram::xxx:role/fc-public-test'
    	  LogConfig:
    		Project: xxx
    		Logstore: xxx
    	  VpcConfig:
    		VpcId: vpc-xxx
    		VSwitchIds:
    		  - vsw-x'x'x'x SecurityGroupId: sg-xxx InternetAccess: true php-test: Type: 'Aliyun::Serverless::Function' Properties: Handler: 'index.handler'Runtime: php7.2 Timeout: 10 MemorySize: 128 CodeUri:'. /' EnvironmentVariables: ODBCINI: /code/.fun/root/etc/odbc.ini ODBCSYSINI: /code/.fun/root/opt/microsoft/msodbcsql17/etcCopy the code
  2. Create a Funfile in this directory with the following contents:

    RUNTIME php7.2 RUN apt-get update && apt-get install -y apt-transport- HTTPS apt-utils RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - RUN curl https://packages.microsoft.com/config/debian/8/prod.list > /etc/apt/sources.list.d/mssql-release.list RUN fun-install apt-get install unixodbc-dev RUN fun-install apt-get install msodbcsql17Copy the code
  3. Run the fun install command to install dependencies:

    $ fun install
    using template: template.yml
    start installing functionDependencies without Docker Dependencies without Docker Install SuccessCopy the code
  4. Create a new code file in the function root directory, for example, / TMP /code/index.php:

    <? phpfunction handler($event.$context)
    {
    	try {
    		$conn = new PDO("sqlsrv:Server=rm-xxx.sqlserver.rds.aliyuncs.com; Database=xxx"."xxx"."xxx");
    		// set the PDO error mode to exception
    		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    		$conn->query("set names utf-8");
    		$sql="SELECT * FROM inventory WHERE quantity > 152";
    		$result = $conn->prepare($sql);
    		$result->execute();
    		print($result);
    		return ("Connection successed.");
    	} catch (PDOException $e) {
    		return ("Connection failed: " . $e->getMessage()); }}Copy the code
  5. Deploy with fun:

    $ fun deploy using template: template.yml using region: cn-hangzhou using accountId: ***********3743 using accessKeyId: ***********Ptgk using timeout: 60 Deployment process...function php-test deploy success
    service SQL-Server-test deploy success
    Copy the code

Log in to the console, and you can see that the related services and functions have been created successfully, and the triggered execution returns the correct results.

  1. Matters needing attention
    1. Create the function you need to set up two environment variables: ODBCINI: / code/fun/root/etc/odbc.ini ODBCSYSINI: / code/fun/root/opt/Microsoft/msodbcsql17 / etc
    2. performfun installCommands rely on after installation, modification, fun/root/etc/odbc Driver in the ini file points to. Fun/root/opt/Microsoft/msodbcsql17 / lib64 / files in the directory, as shown in figure!
    3. The pdo_SQLSRV extension can be compiled in PHP environments by referring to the functions used to calculate PHP Runtime.

conclusion

Through this article, you can quickly realize the function calculation access SQL Server database.

Advantages of using functions:

  1. No need to purchase and manage servers and other infrastructure, just focus on the development of business logic, can greatly shorten the project delivery time and labor costs;
  2. Provides log query, performance monitoring, and alarm functions to quickly rectify faults.
  3. O&m free, elastic expansion at millisecond level, rapid expansion at the bottom to cope with peak pressure, excellent performance;
  4. Cost competitive;

Join us

Team to introduce

Ali Cloud function service is a new computing service that supports event-driven programming mode. It helps users to focus on their own business logic, build applications in a Serverless way, and quickly achieve low-cost, scalable, and highly available systems without considering the management of the underlying infrastructure such as servers. Users can create prototypes quickly, and the same architecture can scale smoothly with business scale. Making computing more efficient, more economical, more flexible, more reliable. Both small startups and large companies benefit. Our team is expanding rapidly and looking for talent. We’re looking for guys with solid fundamentals. Can not only read papers to track industry trends, but also quickly code to solve practical problems. Rigorous and systematic thinking ability. It can not only consider the overall business opportunities, system architecture, operation and maintenance costs and many other factors, but also control the complete process of design/development/testing/release, predict and control risks. Curiosity and mission driven. Willing to explore the unknown, not only dreamers, but also doers. Tough, optimistic and confident. Can see the opportunity in the pressure and difficulties, make work fun! If you are passionate about cloud computing and want to build an influential computing platform and ecosystem, please join us and make your dreams come true!

The job description

Build a new generation of Serverless computing platform, including:

  1. Design and implement a complete and extensible front-end system, including authentication/permission management, metadata management, flow control, metering and billing, log monitoring, etc
  2. Design and implement resilient and reliable back-end systems, including resource scheduling, load balancing, fault tolerant processing, etc
  3. Easy to use SDK/Tools/CLI/ console
  4. Driven by user needs, we track industry trends and use technology to drive business growth

Job requirements

  1. Solid basic knowledge of algorithm/data structure/operating system, excellent logical thinking ability.
  2. Master at least one programming language. Such as Java/C # / Go/C/C + +.
  3. Experience in large-scale, highly available distributed system development is a plus.
  4. Experience in Web/Mobile Backends/Microservice development is preferred.
  5. Good communication skills and team work spirit, have certain organization and coordination ability.
  6. Bachelor degree or above
  7. More than 3 years working experience Through “alibaba coding standards” certification classmates preferences, certification address: edu.aliyun.com/certificati…

Resume submitted

yixian.dw AT alibaba-inc.com

“Alibaba cloud native technology circle pays attention to micro-service, Serverless, container, Service Mesh and other technical fields, focuses on cloud native popular technology trends, cloud native large-scale practice, and becomes the technology circle that knows most about cloud native developers.”