首页 > 代码库 > 批量发送短信,并批量插入短信记录

批量发送短信,并批量插入短信记录

最近在项目中遇到了群发短信的需求。

需求点包括:

  1.给符合条件的人群发优惠券短信

  2.并对发送短信做记录,成功或者失败。(SqlServer)

短信接口:

  亿美,api中有群发短信的接口,一组最大为200条。

思路:

  1.发送的手机集合放进一个队列

  2.依次读取队列,放到待发送列表,当满足200(短信组个数可配置在web.config中)条时,调用接口发送,直到队列数据发完

  3.发送结果放进已发送短信结果集合

  4.把发送结果批量插入数据库

代码:

群发helper

技术分享
/// <summary>    /// 群发短信    /// </summary>    public class SmsGroupHelper    {        //每次发送短信数量        private readonly static int SmsCount = Globals.SafeInt(Utils.GetAppSettingByKey("SmsCount"), 0);        /// <summary>        /// 群发短信        /// </summary>        /// <param name="content">短信内容</param>        /// <param name="phones">手机号组</param>        /// <returns></returns>        public static SmsResult SendGroupSms(string content, List<string> phones)        {            var phoneQueue = new Queue<string>();            var unSendSmsList = new List<string>(); //待发送            var sendedSmsList = new List<Sms>(); //已发送数量            var sendFailed = new List<string>(); //发送失败数量            var sendSuccess = new List<string>(); //发送成功数量            var smsResult = new SmsResult();            smsResult.ErrMsg = "";            try            {                //1.先发送短信 ,根据短信发送情况,保存数据库记录                foreach (var phone in phones)                {                    phoneQueue.Enqueue(phone);                }                //是否发送短信                var isSendFlag = false;                while (true)                {                    if (phoneQueue.Count > 0)                    {                        var phoneNum = phoneQueue.Dequeue();                        unSendSmsList.Add(phoneNum);                        //如果达到一个发送短信包数量                        if (unSendSmsList.Count == SmsCount)                        {                            isSendFlag = true;                        }                    }                    else                    {                        //如果还有短信没发出去                        if (unSendSmsList.Count > 0)                        {                            isSendFlag = true;                        }                        else                        {                            isSendFlag = false;                            break;                        }                    }                    if (isSendFlag)                    {                        var phoneArr = unSendSmsList.ToArray();                        var resposeMsg = "";                        //发送短信短信接口                        var flag = SMSHelper.SendSms(content, phoneArr, out resposeMsg);                        var sendResult = "短信发送成功";                        if (flag)                        {                            sendSuccess.AddRange(unSendSmsList);                        }                        else                        {                            sendResult = "短信发送失败";                            sendFailed.AddRange(unSendSmsList);                        }                        //记录总发送数量                        sendedSmsList.AddRange(                                unSendSmsList.Select(                                    un =>                                        new Sms                                        {                                            Phone = un,                                            CreateTime = DateTime.Now,                                            MessageStatus = sendResult,                                            MessageRemarks = content                                        }));                        //清空未发送列表                        unSendSmsList = new List<string>();                        isSendFlag = false;                    }                }            }            catch (Exception ex)            {                smsResult.ErrMsg = ex.Message;                while (phoneQueue.Count > 0)                {                    var p = phoneQueue.Dequeue();                    sendFailed.Add(p);                    sendedSmsList.Add(new Sms()                    {                        Phone = p,                        CreateTime = DateTime.Now,                        MessageStatus = "短信发送失败",                        MessageRemarks = content                    });                }            }                       //批量插入短信结果到数据库            DapperHelper.BulkInsert("SmsRecord", sendedSmsList);            smsResult.Send = sendedSmsList.Count;            smsResult.Success = sendSuccess.Count;            smsResult.Failed = sendFailed.Count;            return smsResult;        }
SmsGroupHelper

批量插入数据

技术分享
public class TableColumn    {        public string COLUMN_NAME { get; set; }        public string DATA_TYPE { get; set; }    }
View Code
技术分享
#region Bulk批量插入        public static Type MapCommonType(string dbtype)        {            if (string.IsNullOrEmpty(dbtype)) return Type.Missing.GetType();            dbtype = dbtype.ToLower();            Type commonType = typeof(object);            switch (dbtype)            {                case "bigint": commonType = typeof(long); break;                case "binary": commonType = typeof(byte[]); break;                case "bit": commonType = typeof(bool); break;                case "char": commonType = typeof(string); break;                case "date": commonType = typeof(DateTime); break;                case "datetime": commonType = typeof(DateTime); break;                case "datetime2": commonType = typeof(DateTime); break;                case "datetimeoffset": commonType = typeof(DateTimeOffset); break;                case "decimal": commonType = typeof(decimal); break;                case "float": commonType = typeof(double); break;                case "image": commonType = typeof(byte[]); break;                case "int": commonType = typeof(int); break;                case "money": commonType = typeof(decimal); break;                case "nchar": commonType = typeof(string); break;                case "ntext": commonType = typeof(string); break;                case "numeric": commonType = typeof(decimal); break;                case "nvarchar": commonType = typeof(string); break;                case "real": commonType = typeof(Single); break;                case "smalldatetime": commonType = typeof(DateTime); break;                case "smallint": commonType = typeof(short); break;                case "smallmoney": commonType = typeof(decimal); break;                case "sql_variant": commonType = typeof(object); break;                case "sysname": commonType = typeof(object); break;                case "text": commonType = typeof(string); break;                case "time": commonType = typeof(TimeSpan); break;                case "timestamp": commonType = typeof(byte[]); break;                case "tinyint": commonType = typeof(byte); break;                case "uniqueidentifier": commonType = typeof(Guid); break;                case "varbinary": commonType = typeof(byte[]); break;                case "varchar": commonType = typeof(string); break;                case "xml": commonType = typeof(string); break;                default: commonType = typeof(object); break;            }            return commonType;        }     //获取表结构        public static List<TableColumn> GetTableColumns(string tableName)        {            var columns =                DapperHelper.GetList<TableColumn>(                    string.Format(                        "select COLUMN_NAME,DATA_TYPE from INFORMATION_SCHEMA.COLUMNS t where t.TABLE_NAME = ‘{0}‘",                        tableName), null);            return columns;        }        /// <summary>        /// 获取表数据        /// </summary>        /// <param name="tableName">数据表名称</param>        /// <param name="lists">数据集合</param>        /// <returns></returns>        public static void BulkInsert<T>(string tableName, List<T> lists)        {            var type = typeof (T);            var fields = type.GetProperties();            var columns = GetTableColumns(tableName);            DataTable dt = new DataTable();            foreach (var column in columns)            {                dt.Columns.Add(new DataColumn(column.COLUMN_NAME, MapCommonType(column.DATA_TYPE)));            }            foreach (var l in lists)            {                var row = dt.NewRow();                foreach (var column in columns)                {                    var column1 = column;                    foreach (var field in fields.Where(field => String.Equals(column1.COLUMN_NAME, field.Name, StringComparison.CurrentCultureIgnoreCase)))                    {                        row[column.COLUMN_NAME] = field.GetValue(l) ?? DBNull.Value;                        break;                    }                }                dt.Rows.Add(row);            }            BulkToDB(dt, tableName);        }            //批量插入数据             public static void BulkToDB(DataTable dt, string tableName)        {            SqlConnection con = DapperConnection.CreateCon(Temp_dbtype, Temp_dbConKey) as SqlConnection;            SqlBulkCopy bulkCopy = new SqlBulkCopy(con);            bulkCopy.DestinationTableName = tableName;            bulkCopy.BatchSize = dt.Rows.Count;            try            {                con.Open();                if (dt != null && dt.Rows.Count != 0)                    bulkCopy.WriteToServer(dt);            }            catch (Exception ex)            {                throw ex;            }            finally            {                con.Close();                if (bulkCopy != null)                    bulkCopy.Close();            }        }        #endregion
Bulk insert

 

批量发送短信,并批量插入短信记录