今天的案例,需求来自公众号的网友留言,需求如下:
将原来部署在VM里的定时服务迁移到Server less 的Azure Functions,
执行的主要操作为定时处理Azure SQL 数据库。
示意图如下:
本案例对该需求进行了简化,最终如下所示:
每一分钟,从Azure SQL数据库查询一次数据;
开发环境:开发工具VS2019 + C#;
完整的操作视频如下:
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);
}
}
}
}
步骤中的注意事项:
- System.Data.SqlClient版本要使用4.5.1版本及以下的;
2.NCRONTAB表达式(定时)请参照如下链接:
- Azure SQL db防火墙设置,需将部署后的Functions IP 加入到允许列表
关于Azure Functions 的开发及部署,请参见如下文章:
《设备数据通过Azure Functions 推送到 Power BI 数据大屏进行展示(1.准备工作)》
《设备数据通过Azure Functions 推送到 Power BI 数据大屏进行展示(2.Azure Functions实战)》
《使用VS code 创建 Azure Functions,从blob触发,解析,发送至Service Bus》