从CLR触发器中提交WebRequest

时间:2012-07-09 12:31:06

标签: sql-server-2008-r2 real-time sqlclr data-caching

我刚刚实现了一个原型解决方案,通过为表分配CLR触发器来实时更新我的​​缓存服务器,这样每当更新某个列时,从触发器调用的URL将使用正确的数据更新缓存服务器。

工作正常,代码如下:

[Microsoft.SqlServer.Server.SqlTrigger(Name = "AdStatusChanged", Target = "Ads", Event = "FOR UPDATE")]
public static void AdStatusChanged()
{
    SqlTriggerContext triggContext = SqlContext.TriggerContext;
    int adID = 0, adStatusID_Old = 0, adStatusID_New = 0;

if (triggContext.TriggerAction == TriggerAction.Update)
{
    using (SqlConnection conn = new SqlConnection("context connection=true"))
    {
        conn.Open();
        SqlCommand sqlComm = new SqlCommand();
        SqlPipe sqlP = SqlContext.Pipe;

        sqlComm.Connection = conn;
        sqlComm.CommandText = "SELECT AdID, AdStatusID from INSERTED";

        SqlDataReader reader = sqlComm.ExecuteReader();

        if (reader.Read())
        {
            adID = reader.GetInt32(0);
            adStatusID_New = reader.GetInt32(1);
        }

        reader.Close();

        sqlComm.CommandText = "SELECT AdID, AdStatusID from DELETED WHERE AdID = " + adID;

        reader = sqlComm.ExecuteReader();

        if (reader.Read())
        {
            adID = reader.GetInt32(0);
            adStatusID_Old = reader.GetInt32(1);
        }
    }

    if (adID == 0 || adStatusID_New == adStatusID_Old)
    {
        // Check could be more thorough !
        return;
    }

    WebResponse httpResponse = null;

    try
    {
        string apiURL = string.Format("{0}/{1}", "http://localhost:14003/Home", "UpdateAdStatus?adID=" + adID + "&adStatusID=" + adStatusID_New);

        var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiURL);
        httpWebRequest.Method = "GET";

        httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        // check for successful response
    }
    catch (Exception ex)
    {
        Log("WebRequest from within SQL Server failed ! " + ex.Message);
    }
    finally
    {
        if (httpResponse != null)
        {
            httpResponse.Close();
        }
    }
}

}

我想对这种方法的“缺点”有一些专家/经验丰富的观点,包括性能,死锁,sql崩溃或其他可能引起关注的领域。

有没有人试过这个(我相信很多人必须有)并且结果如何?一个成功的实现还是你还原到其他方法或实时更新缓存?

0 个答案:

没有答案