1

我刚刚实现了一个原型解决方案,通过将 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 崩溃或其他可能引起关注的领域,我想对这种方法的“缺点”有一些专家/经验丰富的看法。

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

4

0 回答 0