今天的案例,需求来自公众号的网友留言,需求如下:

 

将原来部署在VM里的定时服务迁移到Server less 的Azure Functions,

执行的主要操作为定时处理Azure SQL 数据库。

 

示意图如下:

本案例对该需求进行了简化,最终如下所示:

每一分钟,从Azure SQL数据库查询一次数据;

开发环境:开发工具VS2019 + C#;

完整的操作视频如下:

B站视频:  https://www.bilibili.com/video/av89405896/

或在本站观看:

 

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using System.Data;
using System.Data.SqlClient;
​
namespace FunctionAppForSql
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static void Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log)
{
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
​
            try
            {
                string strCon = @"your db connection string";
                using (SqlConnection con = new SqlConnection(strCon))
                {
                    con.Open();
                    if (con.State == ConnectionState.Open)
                    {
                        string strCmd = "select * from SalesLT.Customer";
​
                        SqlCommand com = new SqlCommand();
                        com.Connection = con;
                        com.CommandType = CommandType.Text;
                        com.CommandText = strCmd;
                        SqlDataReader dr = com.ExecuteReader();
​
                        while (dr.Read())
                        {
                            log.LogInformation(dr[0].ToString() + "," + dr[1].ToString());
                        }
                        dr.Close();
​
​
                    }
                    con.Close();
                }
            }
            catch (Exception ex)
            {
​
                log.LogInformation(ex.Message);
            }
​
        }
    }
}

 

步骤中的注意事项:

如下图使用Visual studio 进行开发:

  1. System.Data.SqlClient版本要使用4.5.1版本及以下的;

 

如果使用VS Code开发,package manager 则可能遇到找不到system.data.sqlclient的情况,在这样的情况下,需要科学上网才行;

或者可以直接编辑项目文件:

添加:

<PackageReference Include="System.Data.SqlClient" Version="4.5.1"/>

 

 

 

 

NCRONTAB表达式(定时)请参照如下链接:

 

https://docs.azure.cn/zh-cn/azure-functions/functions-bindings-timer?tabs=csharp#ncrontab-expressions

Azure SQL db防火墙设置,需将部署后的Functions IP 加入到允许列表