在windows azure中,我们托管了两个asp.net webapi项目作为app服务。我们需要在这里启用分布式事务。我们在一个api内启动交易。然后在该事务范围内,我们获取该事务的传播令牌,并在另一个api调用期间将其作为头发送。代码就像波纹管。
[HttpGet]
[Route("api/Test/Transaction/Commit")]
public async Task<string> Commit()
{
using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions
{
IsolationLevel = IsolationLevel.ReadCommitted
},
TransactionScopeAsyncFlowOption.Enabled))
{
// cross app domain call
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get, ConfigurationManager.AppSettings["IdentityServerUri"] + "api/Test/Transaction/NoCommit"))
{
// forward transaction token
request.AddTransactionPropagationToken();
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
}
}
this.Repository.Insert(new Currency { Ccy = "x", IsoCode = "XIS", Name = "XYZ", CurrencyId = 9 });
await this.Repository.SaveChangesAsync();
scope.Complete();
return "value";
}
}
public static class HttpRequestMessageExtension
{
public static void AddTransactionPropagationToken(this HttpRequestMessage request)
{
if (Transaction.Current != null)
{
var token = TransactionInterop.GetTransmitterPropagationToken(Transaction.Current);
request.Headers.Add("TransactionToken", Convert.ToBase64String(token));
}
}
}
在我们在事务范围内进行调用的api(... api / Test / Transaction / NoCommit)内部,从头部获取该事务的封送传播令牌并使用它创建该事务的实例并实例化TransactionScope使用该交易。稍后我们使用此事务范围来完成该事务。我们引入了一个动作过滤器来应用它,并将该过滤器添加到负责该api调用的动作中。该api和动作过滤器的代码类似于下面的内容。
[HttpGet]
[EnlistToDistributedTransactionActionFilter]
[Route("api/Test/Transaction/NoCommit")]
public async Task<string> NoCommit()
{
this.Repository.Insert(new Client
{
Name = "Test",
AllowedOrigin = "*",
Active = true,
ClientGuid = Guid.NewGuid(),
RefreshTokenLifeTime = 0,
ApplicationType = ApplicationTypes.JavaScript,
Secret = "ffff",
Id = "Test"
}
);
await this.Repository.SaveChangesAsync();
return "value";
}
public class EnlistToDistributedTransactionActionFilter : ActionFilterAttribute
{
private const string TransactionId = "TransactionToken";
/// <summary>
/// Retrieve a transaction propagation token, create a transaction scope and promote the current transaction to a distributed transaction.
/// </summary>
/// <param name="actionContext">The action context.</param>
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Contains(TransactionId))
{
var values = actionContext.Request.Headers.GetValues(TransactionId);
if (values != null && values.Any())
{
byte[] transactionToken = Convert.FromBase64String(values.FirstOrDefault());
var transaction = TransactionInterop.GetTransactionFromTransmitterPropagationToken(transactionToken);
var transactionScope = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled);
actionContext.Request.Properties.Add(TransactionId, transactionScope);
}
}
}
/// <summary>
/// Rollback or commit transaction.
/// </summary>
/// <param name="actionExecutedContext">The action executed context.</param>
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Request.Properties.Keys.Contains(TransactionId))
{
var transactionScope = actionExecutedContext.Request.Properties[TransactionId] as TransactionScope;
if (transactionScope != null)
{
if (actionExecutedContext.Exception != null)
{
Transaction.Current.Rollback();
}
else
{
transactionScope.Complete();
}
transactionScope.Dispose();
actionExecutedContext.Request.Properties[TransactionId] = null;
}
}
}
}
因此,如果在该事务范围内(在firt api或第二个api中)此调用(api / Test / Transaction / Commit)期间发生任何异常,则将回滚由两个api完成的所有数据库更改。这在当地工作正常。在本地,我们得到了MSDTC的支持。但在Azure中,没有MSDTC支持。在azure中,我们获得了Elastic交易的支持。因此,当我们尝试从第一台服务器获取事务的传播令牌时,我们会遇到异常。所以当我们尝试执行波纹管代码时 var transaction = TransactionInterop.GetTransactionFromTransmitterPropagationToken(transactionToken); 消息&#34;消息不在预期范围内&#34; 。 This post说这种方法需要通过System.Transactions升级到MSDTC,但对于弹性交易我们如何才能使其工作? 对于弹性交易,我们需要将交易编组到传播令牌中。如何做到这一点?寻找解决方案。
答案 0 :(得分:0)
弹性事务旨在允许从 Azure 中的单个 .net 应用程序跨 Azure SQL 数据库和 Azure SQL 托管实例进行事务。
它不是为跨客户端分发交易而构建的。
“仅支持来自 a .NET 应用程序的客户端协调事务”