Skip to content

Commit

Permalink
新增转账sample
Browse files Browse the repository at this point in the history
  • Loading branch information
Godricm committed Mar 26, 2019
1 parent 4207d90 commit 646ad77
Show file tree
Hide file tree
Showing 11 changed files with 215 additions and 30 deletions.
20 changes: 20 additions & 0 deletions Olympic.Grains/ATMGrain.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Olympics.Interfaces;
using Orleans;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Olympics.Grains
{
public class ATMGrain : Grain, IATMGrain
{
public Task Transfer(Guid fromAccount, Guid toAccount, uint amountToTransfer)
{
return Task.WhenAll(
this.GrainFactory.GetGrain<IAccountGrain>(fromAccount).Withdraw(amountToTransfer),
this.GrainFactory.GetGrain<IAccountGrain>(toAccount).Deposit(amountToTransfer)
);
}
}
}
42 changes: 42 additions & 0 deletions Olympic.Grains/AccountGrain.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Olympics.Interfaces;
using Orleans;
using Orleans.CodeGeneration;
using Orleans.Transactions.Abstractions;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

[assembly: GenerateSerializer(typeof(Olympics.Grains.Balance))]
namespace Olympics.Grains
{
public class Balance
{
public uint Value { get; set; } = 1000;
}

public class AccountGrain : Grain, IAccountGrain
{
private readonly ITransactionalState<Balance> balance;

public AccountGrain([TransactionalState("balance")] ITransactionalState<Balance> balance)
{
this.balance = balance ?? throw new ArgumentNullException(nameof(balance));
}

public Task Deposit(uint amount)
{
return this.balance.PerformUpdate(x => x.Value += amount);
}

public Task<uint> GetBalance()
{
return this.balance.PerformRead(x => x.Value);
}

public Task Withdraw(uint amount)
{
return this.balance.PerformUpdate(x => x.Value -= amount);
}
}
}
28 changes: 13 additions & 15 deletions Olympics.BaseApi/OrleansClient/ClusterClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,21 @@ public Client()

private IClusterClient BuildClient()
{
return new ClientBuilder()

//与主简仓进行连接
.UseLocalhostClustering()
.Configure<ClusterOptions>(options =>
{
options.ClusterId = "dev";
options.ServiceId = "Server";
})

//配置刷新简仓的时间 一般来说不会这么短
//.Configure<GatewayOptions>(d => d.GatewayListRefreshPeriod = TimeSpan.FromSeconds(5))
.ConfigureLogging(logging => logging.AddConsole()).Build();
return new ClientBuilder()
//集群设置
.UseLocalhostClustering()
.Configure<ClusterOptions>(options =>
{
options.ClusterId = "dev";
options.ServiceId = "Server";
})
//配置刷新简仓的时间 一般来说不会这么短
//.Configure<GatewayOptions>(d => d.GatewayListRefreshPeriod = TimeSpan.FromSeconds(5))
.ConfigureLogging(logging => logging.AddConsole()).Build();

}

public async Task Connect(int retries=0,TimeSpan? delay = null)
public async Task Connect(int retries = 0, TimeSpan? delay = null)
{
if (ClusterClient.IsInitialized)
{
Expand Down Expand Up @@ -74,6 +72,6 @@ public async Task Connect(int retries=0,TimeSpan? delay = null)
}
}
}

}
}
2 changes: 1 addition & 1 deletion Olympics.Client/Olympics.Client.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
Expand Down
17 changes: 17 additions & 0 deletions Olympics.Entities/Account.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace Olympics.Entities
{
/// <summary>
/// 账户
/// </summary>
public class Account
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Amount { get; set; }

}
}
24 changes: 24 additions & 0 deletions Olympics.Entities/AccountBalanceRecord.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace Olympics.Entities
{
/// <summary>
/// 结算记录表
/// </summary>
public class AccountBalanceRecord
{
public int Id { get; set; }

public int FromAccountId { get; set; }

public int ToAccountId { get; set; }

public string AccountType { get; set; }

public decimal Amount { get; set; }

public DateTime CreateTime { get; set; }
}
}
23 changes: 23 additions & 0 deletions Olympics.Entities/AccountRequestRecord.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace Olympics.Entities
{
public class AccountRequestRecord
{
public int Id { get; set; }

public int FromAccountId { get; set; }

public int ToAccountId { get; set; }

public string AccountType { get; set; }

public decimal Amount { get; set; }

public int Status { get; set; }

public DateTime CreateTime { get; set; }
}
}
14 changes: 14 additions & 0 deletions Olympics.Interfaces/IATMGrain.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Orleans;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Olympics.Interfaces
{
public interface IATMGrain:IGrainWithIntegerKey
{
[Transaction(TransactionOption.Create)]
Task Transfer(Guid fromAccount, Guid toAccount, uint amountToTransfer);
}
}
20 changes: 20 additions & 0 deletions Olympics.Interfaces/IAccountGrain.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using Orleans;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Olympics.Interfaces
{
public interface IAccountGrain : IGrainWithGuidKey
{
[Transaction(TransactionOption.Join)]
Task Withdraw(uint amount);

[Transaction(TransactionOption.Join)]
Task Deposit(uint amount);

[Transaction(TransactionOption.CreateOrJoin)]
Task<uint> GetBalance();
}
}
7 changes: 4 additions & 3 deletions Olympics.Server/Olympics.Server.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
Expand All @@ -7,8 +7,9 @@

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.0" />
<PackageReference Include="Microsoft.Orleans.OrleansProviders" Version="2.2.4" />
<PackageReference Include="Microsoft.Orleans.OrleansRuntime" Version="2.2.4" />
<PackageReference Include="Microsoft.Orleans.OrleansProviders" Version="2.3.0" />
<PackageReference Include="Microsoft.Orleans.OrleansRuntime" Version="2.3.0" />
<PackageReference Include="Microsoft.Orleans.Transactions" Version="2.3.0" />
</ItemGroup>

<ItemGroup>
Expand Down
48 changes: 37 additions & 11 deletions Olympics.Server/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,16 @@ class Program
{
static void Main(string[] args)
{
RunMainAsync();
string clientId = args[0];
string serverId = args[1];
RunMainAsync(clientId, serverId);
}

private static void RunMainAsync()
private static void RunMainAsync(string clientId,string serverId)
{
try
{
var host = StartSilo();
var host = StartSilo(clientId, serverId);
bool isExit = true;
while (isExit)
{
Expand All @@ -31,16 +33,16 @@ private static void RunMainAsync()
isExit = false;
host.Result.StopAsync();
}
}
}
}
catch (Exception ex)
{

}
}


private static async Task<ISiloHost> StartSilo()
private static async Task<ISiloHost> StartSilo(string clientId, string serverId)
{
// define the cluster configuration
var builder = new SiloHostBuilder()
Expand All @@ -49,13 +51,37 @@ private static async Task<ISiloHost> StartSilo()
//集群属性配置
.Configure<ClusterOptions>(options =>
{
options.ClusterId = "dev";
options.ServiceId = "Server";
options.ClusterId = clientId;
options.ServiceId = serverId;
})
//端口配置
.Configure<EndpointOptions>(options => options.AdvertisedIPAddress = IPAddress.Loopback)
.Configure<EndpointOptions>(
options =>
{
// Port to use for Silo-to-Silo
//options.SiloPort = 11111;
// Port to use for the gateway
//options.GatewayPort = 30000;
// IP Address to advertise in the cluster
options.AdvertisedIPAddress = IPAddress.Loopback;//IPAddress.Parse("172.16.0.42");
// The socket used for silo-to-silo will bind to this endpoint
//options.GatewayListeningEndpoint = new IPEndPoint(IPAddress.Any, 40000);
// The socket used by the gateway will bind to this endpoint
//options.SiloListeningEndpoint = new IPEndPoint(IPAddress.Any, 50000);

}
//options => options.AdvertisedIPAddress = IPAddress.Loopback
)
//配置端口
//.ConfigureEndpoints(siloPort: 11111, gatewayPort: 30000)
//应用设置
.ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(UserBiz).Assembly).WithReferences())
.ConfigureApplicationParts(parts =>
{
parts.AddApplicationPart(typeof(UserBiz).Assembly).WithReferences();
parts.AddApplicationPart(typeof(AccountGrain).Assembly).WithReferences();
}).
//增加内存的持久化
AddMemoryGrainStorageAsDefault()
//配置日志
.ConfigureLogging(logging => logging.AddConsole());

Expand All @@ -79,7 +105,7 @@ private static async Task<ISiloHost> StartAgentHost()
.ConfigureLogging(logging => logging.AddConsole());

var host = builder.Build();
await host.StartAsync();
await host.StartAsync();
Console.WriteLine("代理网关启动成功");
return host;
}
Expand Down

0 comments on commit 646ad77

Please sign in to comment.