-- ---------------------------- -- Records of seqno -- ---------------------------- BEGIN; INSERT INTO `seqno` VALUES ('order', 1); COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
4、在 VS2019 中创建两个控制台项目和一个类库项目,如下图:
单机测试
1、在 SeqNo 类中添加 GetSeqByNoLock 方法
1 2 3 4 5 6 7 8 9 10 11
public static string GetSeqNoByNoLock() { string connectionStr = "server = localhost; user id = oec2003; password = 123456; database = seqno_test"; string getSeqNosql = "select num from seqno where code='order'"; string updateSeqNoSql = "update seqno set num=num+1 where code='order'";
var seqNo = MySQLHelper.ExecuteScalar(connectionStr, System.Data.CommandType.Text, getSeqNosql); MySQLHelper.ExecuteNonQuery(connectionStr, System.Data.CommandType.Text, updateSeqNoSql);
class Program { static void Main(string[] args) { Task.Run(() => { for (int i = 0; i < 50; i++) { Console.WriteLine($"Thread1:SeqNo:{SeqNo.GetSeqNoByNoLock()}"); } });
Task.Run(() => { for (int i = 0; i < 50; i++) { Console.WriteLine($"Thread2:SeqNo:{SeqNo.GetSeqNoByNoLock()}"); } }); Console.ReadLine(); } }
public static string GetSeqNoByRedisLock() { string connectionStr = "server = localhost; user id = oec2003; password = 123456; database = seqno_test"; string getSeqNosql = "select num from seqno where code='order'"; string updateSeqNoSql = "update seqno set num=num+1 where code='order'";
var seqNo=string.Empty; using (_redisClient.Lock("test", 5000)) { seqNo = MySQLHelper.ExecuteScalar(connectionStr, System.Data.CommandType.Text, getSeqNosql).ToString();