之前發(fā)表了一篇事務(wù)的存儲(chǔ)過程,最近在做項(xiàng)目的時(shí)候遇到分布式事務(wù),所有總結(jié)一下,跟大家分享和交流一下經(jīng)驗(yàn)。首先說明為什么要分布式事務(wù)呢?先說說我在項(xiàng)目的哪里遇到分布式事務(wù)吧,我是在做網(wǎng)站后臺(tái)開發(fā)的時(shí)候,一般涉及到有圖片表的設(shè)計(jì)時(shí),數(shù)據(jù)庫存放的是圖片的路徑,圖片是存放在網(wǎng)站的文件夾下面,所以我們操作產(chǎn)品表時(shí),當(dāng)我要?jiǎng)h除數(shù)據(jù)庫產(chǎn)品圖片路徑,同時(shí)要把存在網(wǎng)站目錄下的圖片也刪掉,為了實(shí)現(xiàn)這功能,我就使用了分布式事務(wù)。
思路:
1、在項(xiàng)目中必須引用 System.Transactions 程序集
2、在需要進(jìn)行事務(wù)管控的代碼方法:System.Transactions.TransactionScope scop = new System.Transactions.TransactionScope()
3、必須啟動(dòng)服務(wù) Distributed Transaction Coordinator才能進(jìn)行分布式事務(wù)的正常運(yùn)行
下面是我寫的一個(gè)例子主要代碼:
1 //3.根據(jù)id將數(shù)據(jù)庫和文件夾的圖片一起刪掉 2 3 //3.0根據(jù)id得到實(shí)體對(duì)象 4 PRoductEntity entity = Product_BLLSub.Get_ProductEntity(int.Parse(id)); 5 //3.1創(chuàng)建一個(gè)事務(wù) 6 using (System.Transactions.TransactionScope scop = new System.Transactions.TransactionScope()) 7 { 8 //3.2刪除數(shù)據(jù)庫圖片的數(shù)據(jù) 9 Product_BLLSub.Create_ProductDelete(int.Parse(id));10 12 //3.3得到圖片的路徑13 string thumphyPath = context.Server.MapPath("/upload/thum/") + entity.img_url;14 string imgPhyPath = context.Server.MapPath("/upload/img/") + entity.img_url;15 //3.4刪除縮略圖16 if (System.IO.File.Exists(thumphyPath))17 {18 System.IO.File.Delete(thumphyPath);19 }20 //3.5刪除原圖21 if (System.IO.File.Exists(imgPhyPath))22 {23 System.IO.File.Delete(imgPhyPath);24 }25 //3.6提交事務(wù)26 scop.Complete();27 }28 35 //刪除成功36 Response.Write("刪除成功");
說明:我操作數(shù)據(jù)庫的方法是將數(shù)據(jù)庫數(shù)據(jù)取出來轉(zhuǎn)換成實(shí)體對(duì)象,然后通過操作實(shí)體對(duì)象來操作數(shù)據(jù)庫。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注