第31篇 实现数据同步的webapi接口

第31篇 实现数据同步的webapi接口 实现数据同步的 webapi 接口 31

调用接口实现数据同步demo讲解

1.demo整体架构如下

image

2.SynchronizeModel类库

这个类库是主要用于实体对象模型的转换,包括请求参数实体RequestModel,数据库实体DBEntity,响应数据实体ResponseModel等,

2.1 新建一个数据库实体:

/// <summary>
   /// 被测件(雷达)模块信息表
   /// </summary>
[SqlSugar.SugarTable("TestRecordModule")]
public class TestRecordModule:EntityBase
{
    /// <summary>
    /// 被测件
    /// </summary>
    public long TaskTestRecordID { get; set; }

    /// <summary>
    /// 模块编号
    /// </summary>
    public string ModuleNumber { get; set; }

    /// <summary>
    /// 映射位
    /// </summary>
    public int MapPosition { get; set; }

    /// <summary>
    /// 模块状态
    /// </summary>
    public int Status { get; set; }

    /// <summary>
    /// 创建时间
    /// </summary>
    public DateTime CreatedTime { get; set; }

    /// <summary>
    /// 备注
    /// </summary>
    public string Comment { get; set; }

    /// <summary>
    /// 模块型号
    /// </summary>
    public string ModuleType { get; set; }

    /// <summary>
    /// 测试流程控制状态 
    /// </summary>
    public int TestFlowControlStatus { get; set; }

    /// <summary>
    /// 批次数
    /// </summary>
    public int BatchCount { get; set; }

    /// <summary>
    /// 扫码编号
    /// </summary>
    public string ScanCodeNumber { get; set; }

    /// <summary>
    /// 用户ID
    /// </summary>
    public long UserID { get; set; }

    /// <summary>
    /// 是否同步
    /// </summary>
    public SynchronizeStatus IsSynchronize { get; set; }

    /// <summary>
    /// 产线名称
    /// </summary>
    public string ProductLineName { get; set; }
}

2.2 新建响应数据实体:

public class ResultModel
	{
		public bool Success { get; set; }
		public string Message { get; set; }
	}

2.3 业务逻辑的同步状态枚举:

 public enum SynchronizeStatus
	{
		None = 0,
		Synchronizing = 1,
		Synchronized = 2,
	}

3.SynchronizeService类库

主要分几层:
3.1 接口层:IRepository,IService

public interface ISynchronizeRepository
	{
		Task<ResultModel> AddTestRecordModuleAsync(TestRecordModule entity);
		Task<ResultModel> BatchDataSynchronizeAsync(List<TestRecordModule> entities);
	}

public interface ISynchronizeService
	{
		Task<ResultModel> AddTestRecordModuleAsync(TestRecordModule entity);
		Task<ResultModel> BatchDataSynchronizeAsync(List<TestRecordModule> entities);
	}

3.2 业务逻辑实现层:RepositoryImpl,ServiceImpl

 public class BaseRepository<T>
	{
		protected SqlSugarClient db;
		public BaseRepository()
		{
			//string conStr = ConfigurationManager.ConnectionStrings["SQLiteConnectionString"].ConnectionString.ToString();
			string conStr = @"E:\\定时服务\\WebApiService\\WebApiService\\DB\\RDS.DCDC.db3";
			SqliteConnectionStringBuilder stringBuilder = new SqliteConnectionStringBuilder { DataSource = conStr };
			db = new SqlSugarClient(new ConnectionConfig()
			{
				ConnectionString = stringBuilder.ToString(),
				DbType = DbType.Sqlite,
				IsAutoCloseConnection = true,//自动释放
				InitKeyType = InitKeyType.Attribute,
			});
		}
   }


public class SynchronizeRepositoryImpl : BaseRepository<TestRecordModule>, ISynchronizeRepository
	{
		public async Task<ResultModel> AddTestRecordModuleAsync(TestRecordModule entity)
		{
			try
			{
				//先查询是否已同步过,排除同步重复的数据;
				var items = this.db.Queryable<TestRecordModule>().Where(t => t.ScanCodeNumber == entity.ScanCodeNumber && t.IsSynchronize == SynchronizeStatus.Synchronized);
				if (items.Count() > 0)
				{
					return new ResultModel { Success = false, Message = "数据已同步过" };
				}

				//开启事务
				await this.db.BeginTranAsync();
				ResultModel responseModel = new ResultModel();    
				entity.IsSynchronize = SynchronizeStatus.Synchronized;
				if (db.Insertable(entity).ExecuteReturnBigIdentity() > 0)
				{
					responseModel.Success = true;
					responseModel.Message = "成功";
				}
				else
				{
					responseModel.Success = false;
					responseModel.Message = "失败";
				}

				//数据同步完,没有报错,更新IsSynchronize状态

				//entity.IsSynchronize = Entities.SynchronizeStatus.Synchronized;
				//await this.db.Updateable(entity).UpdateColumns(t=>t.IsSynchronize == Entities.SynchronizeStatus.Synchronized)
				//    .WhereColumns(t => t.ScanCodeNumber == entity.ScanCodeNumber).ExecuteCommandAsync();

				// 提交事务
				await this.db.Ado.CommitTranAsync();
				return await Task.FromResult(responseModel);
			}
			catch (Exception ex)
			{
				//事务回滚
				await this.db.Ado.RollbackTranAsync();
				return new ResultModel() { Success = false, Message = "同步失败" };
			}
		}

		public async Task<ResultModel> BatchDataSynchronizeAsync(List<TestRecordModule> entities)
		{
			try
			{
				ResultModel responseModel = new ResultModel();
				foreach (var entity in entities)
				{
					//先查询是否已同步过,排除同步重复的数据;
					var items = this.db.Queryable<TestRecordModule>().Where(t => t.ScanCodeNumber == entity.ScanCodeNumber && t.IsSynchronize == SynchronizeStatus.Synchronized);
					if (items.Count() > 0)
					{
						return new ResultModel { Success = false, Message = "数据已同步过" };
					}

					//开启事务
					await this.db.BeginTranAsync();                   
					entity.IsSynchronize = SynchronizeStatus.Synchronized;
					if (db.Insertable(entity).ExecuteReturnBigIdentity() > 0)
					{
						responseModel.Success = true;
						responseModel.Message = "成功";
					}
					else
					{
						responseModel.Success = false;
						responseModel.Message = "失败";
					}
				}

				//数据同步完,没有报错,更新IsSynchronize状态
				//entity.IsSynchronize = Entities.SynchronizeStatus.Synchronized;
				//await this.db.Updateable(entity).UpdateColumns(t=>t.IsSynchronize == Entities.SynchronizeStatus.Synchronized)
				//    .WhereColumns(t => t.ScanCodeNumber == entity.ScanCodeNumber).ExecuteCommandAsync();

				// 提交事务
				await this.db.Ado.CommitTranAsync();
				return await Task.FromResult(responseModel);
			}
			catch (Exception ex)
			{
				//事务回滚
				await this.db.Ado.RollbackTranAsync();
				return new ResultModel() { Success = false, Message = "同步失败" };
			}
		}
	}


public class SynchronizeServiceImpl : ISynchronizeService
	{
		private readonly ISynchronizeRepository _testRecordModuleRepository;
		public SynchronizeServiceImpl(ISynchronizeRepository testRecordModuleRepository) 
		{
			_testRecordModuleRepository = testRecordModuleRepository;
		}
		public async Task<ResultModel> AddTestRecordModuleAsync(TestRecordModule entity)
		{
			return await _testRecordModuleRepository.AddTestRecordModuleAsync(entity);
		}

		public async Task<ResultModel> BatchDataSynchronizeAsync(List<TestRecordModule> entities)
		{
			return await _testRecordModuleRepository.BatchDataSynchronizeAsync(entities);
		}
	}

4.WebApiService,表现层Controller

[Route("[controller]/[action]")]
	[ApiController]
	public class SynchronizeController : ControllerBase
	{
		private readonly ISynchronizeService _synchronizeService;
		public SynchronizeController(ISynchronizeService synchronizeService ) 
		{
			this._synchronizeService = synchronizeService;
		}

		/// <summary>
		/// 单个数据同步
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<ResultModel> DataSynchronize(TestRecordModule entity)
		{
			entity.IsSynchronize = SynchronizeStatus.Synchronizing;
			var result = this._synchronizeService.AddTestRecordModuleAsync(entity);
			return await result;
		}


		/// <summary>
		/// 批次数据同步
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<ResultModel> BatchDataSynchronize(List<TestRecordModule> entities)
		{
			var result = this._synchronizeService.BatchDataSynchronizeAsync(entities);
			return await result;
		}
	}

具体可以访问我的代码库:https://gitee.com/chenshibao/web-api-service.git

评论