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

    将原来部署在VM里的定时服务迁移到Server less 的Azure Functions,
    执行的主要操作为定时处理Azure SQL 数据库。

    示意图如下:

    使用Azure Functions定时清理Azure SQL数据库 - 图1

    本案例对该需求进行了简化,最终如下所示:
    每一分钟,从Azure SQL数据库查询一次数据;
    开发环境:开发工具VS2019 + C#;

    完整的操作视频如下:

    整理数据库.mp4 (55.96MB)

    1. using System;
    2. using Microsoft.Azure.WebJobs;
    3. using Microsoft.Azure.WebJobs.Host;
    4. using Microsoft.Extensions.Logging;
    5. using System.Data;
    6. using System.Data.SqlClient;
    7. namespace FunctionAppForSql
    8. {
    9. public static class Function1
    10. {
    11. [FunctionName("Function1")]
    12. public static void Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log)
    13. {
    14. log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    15. try
    16. {
    17. string strCon = @"your db connection string";
    18. using (SqlConnection con = new SqlConnection(strCon))
    19. {
    20. con.Open();
    21. if (con.State == ConnectionState.Open)
    22. {
    23. string strCmd = "select * from SalesLT.Customer";
    24. SqlCommand com = new SqlCommand();
    25. com.Connection = con;
    26. com.CommandType = CommandType.Text;
    27. com.CommandText = strCmd;
    28. SqlDataReader dr = com.ExecuteReader();
    29. while (dr.Read())
    30. {
    31. log.LogInformation(dr[0].ToString() + "," + dr[1].ToString());
    32. }
    33. dr.Close();
    34. }
    35. con.Close();
    36. }
    37. }
    38. catch (Exception ex)
    39. {
    40. log.LogInformation(ex.Message);
    41. }
    42. }
    43. }
    44. }

    步骤中的注意事项:

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

    使用Azure Functions定时清理Azure SQL数据库 - 图3

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

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

    使用Azure Functions定时清理Azure SQL数据库 - 图4

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

    使用Azure Functions定时清理Azure SQL数据库 - 图5

    关于Azure Functions 的开发及部署,请参见如下文章:

    设备数据通过Azure Functions 推送到 Power BI 数据大屏进行展示(1.准备工作)

    设备数据通过Azure Functions 推送到 Power BI 数据大屏进行展示(2.Azure Functions实战)

    使用VS code 创建 Azure Functions,从blob触发,解析,发送至Service Bus

    image.png