コード例 #1
0
ファイル: StoreHelper.cs プロジェクト: rhw1111/DCEM
        /// <summary>
        /// 为通用队列消费终结点从DbDataReader中赋值
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="reader"></param>
        /// <param name="prefix"></param>
        public static void SetCommonQueueConsumeEndpointSelectFields(CommonQueueConsumeEndpoint endpoint, DbDataReader reader, string prefix)
        {
            endpoint.ID = (Guid)reader[string.Format("{0}id", prefix)];

            if (reader[string.Format("{0}name", prefix)] != DBNull.Value)
            {
                endpoint.Name = reader[string.Format("{0}name", prefix)].ToString();
            }

            if (reader[string.Format("{0}queuetype", prefix)] != DBNull.Value)
            {
                endpoint.QueueType = reader[string.Format("{0}queuetype", prefix)].ToString();
            }

            if (reader[string.Format("{0}queueconfiguration", prefix)] != DBNull.Value)
            {
                endpoint.QueueConfiguration = reader[string.Format("{0}queueconfiguration", prefix)].ToString();
            }


            if (reader[string.Format("{0}createtime", prefix)] != DBNull.Value)
            {
                endpoint.CreateTime = (DateTime)reader[string.Format("{0}createtime", prefix)];
            }

            if (reader[string.Format("{0}modifytime", prefix)] != DBNull.Value)
            {
                endpoint.ModifyTime = (DateTime)reader[string.Format("{0}modifytime", prefix)];
            }
        }
コード例 #2
0
        public async Task Update(CommonQueueConsumeEndpoint endpoint)
        {
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, false, false, _commonQueueConnectionFactory.CreateAllForCommonQueue(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }

                await using (SqlCommand commond = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran,
                    CommandText = @"update [CommonQueueConsumeEndpoint] set [name]=@name,[queuetype]=@queuetype,[queueconfiguration]=@queueconfiguration,[modifytime]=getutcdate() where [id]=@id"
                })
                {
                    var parameter = new SqlParameter("@id", SqlDbType.UniqueIdentifier)
                    {
                        Value = endpoint.ID
                    };
                    commond.Parameters.Add(parameter);

                    parameter = new SqlParameter("@name", SqlDbType.VarChar, 150)
                    {
                        Value = endpoint.Name
                    };
                    commond.Parameters.Add(parameter);

                    parameter = new SqlParameter("@queuetype", SqlDbType.VarChar, 150)
                    {
                        Value = endpoint.QueueType
                    };
                    commond.Parameters.Add(parameter);

                    parameter = new SqlParameter("@queueconfiguration", SqlDbType.NVarChar, endpoint.QueueConfiguration.Length)
                    {
                        Value = endpoint.QueueConfiguration
                    };
                    commond.Parameters.Add(parameter);

                    await commond.PrepareAsync();

                    await commond.ExecuteNonQueryAsync();
                }
            });
        }
コード例 #3
0
        public async Task <CommonQueueConsumeEndpoint> QueryByID(Guid id)
        {
            CommonQueueConsumeEndpoint endpoint = null;

            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, true, false, _commonQueueConnectionFactory.CreateReadForCommonQueue(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }

                await using (SqlCommand commond = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran,
                    CommandText = string.Format(@"select {0} from [CommonQueueConsumeEndpoint] where [id]=@id", StoreHelper.GetCommonQueueConsumeEndpointSelectFields(string.Empty))
                })
                {
                    var parameter = new SqlParameter("@id", SqlDbType.UniqueIdentifier)
                    {
                        Value = id
                    };
                    commond.Parameters.Add(parameter);

                    await commond.PrepareAsync();

                    SqlDataReader reader = null;

                    await using (reader = await commond.ExecuteReaderAsync())
                    {
                        if (await reader.ReadAsync())
                        {
                            endpoint = new CommonQueueConsumeEndpoint();
                            StoreHelper.SetCommonQueueConsumeEndpointSelectFields(endpoint, reader, string.Empty);
                        }

                        await reader.CloseAsync();
                    }
                }
            });

            return(endpoint);
        }
コード例 #4
0
        public async Task <ICommonQueueEndpointConsumeController> Consume(CommonQueueConsumeEndpoint endpoint, string configuration, Func <CommonMessage, Task> messageHandle)
        {
            var consumeConfiguration = JsonSerializerHelper.Deserialize <ConsumeQueueRealExecuteServiceForAzureServiceBusConfiguration>(configuration);

            List <SubscriptionClient> clients = new List <SubscriptionClient>();

            Dictionary <string, DateTime> loggerDatetimes = new Dictionary <string, DateTime>();

            foreach (var item in consumeConfiguration.Items)
            {
                var newClient = new SubscriptionClient(consumeConfiguration.ConnectionString, item.Topic, consumeConfiguration.Subscription);
                var tempItem  = item;
                loggerDatetimes[item.Topic] = DateTime.UtcNow;
                var messageHandlerOptions = new MessageHandlerOptions(async(args) =>
                {
                    if ((DateTime.UtcNow - loggerDatetimes[tempItem.Topic]).TotalSeconds > 300)
                    {
                        loggerDatetimes[tempItem.Topic] = DateTime.UtcNow;
                        LoggerHelper.LogError(ConsumeErrorLoggerCategoryName, $"Message:{args.Exception.Message},stack:{args.Exception.StackTrace},Endpoint: {args.ExceptionReceivedContext.Endpoint},Entity Path: {args.ExceptionReceivedContext.EntityPath},Executing Action: {args.ExceptionReceivedContext.Action}");
                    }
                })
                {
                    MaxConcurrentCalls   = 1,
                    MaxAutoRenewDuration = new TimeSpan(2, 0, 0),
                    AutoComplete         = false
                };

                newClient.RegisterMessageHandler(async(azureMessage, cancellation) =>
                {
                    bool isError    = false;
                    var fromService = getAzureServiceBusMessageConvertFromService(tempItem.ConvertFromServiceName);
                    var message     = await fromService.From(azureMessage);
                    if (message != null)
                    {
                        int retry = 0;
                        while (true)
                        {
                            try
                            {
                                await messageHandle(message);
                            }
                            catch (Exception ex)
                            {
                                if (ex is UtilityException || retry >= consumeConfiguration.MaxRetry)
                                {
                                    StringBuilder strError = new StringBuilder($"message:{ex.Message},stack:{ex.StackTrace}");
                                    var innerEx            = ex.InnerException;

                                    while (innerEx != null && innerEx.InnerException != null)
                                    {
                                        innerEx = innerEx.InnerException;
                                    }
                                    if (innerEx != null)
                                    {
                                        strError.Append($",innermessage:{innerEx.Message},innerstack:{innerEx.StackTrace}");
                                    }


                                    if (strError.Length > 5000)
                                    {
                                        strError = strError.Remove(4999, strError.Length - 5000);
                                    }

                                    var newAzureMessage = new Message(azureMessage.Body);
                                    newAzureMessage.UserProperties["Exception"]      = strError.ToString();
                                    newAzureMessage.UserProperties["ExceptionRetry"] = true;
                                    newAzureMessage.ScheduledEnqueueTimeUtc          = DateTime.UtcNow.AddSeconds(60);

                                    isError = true;

                                    var topicClient = new TopicClient(newClient.ServiceBusConnection, tempItem.Topic, null);


                                    using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                                    {
                                        await newClient.CompleteAsync(azureMessage.SystemProperties.LockToken);
                                        await topicClient.SendAsync(newAzureMessage).ConfigureAwait(false);

                                        ts.Complete();
                                    }

                                    break;
                                }
                                else
                                {
                                    retry++;
                                    await Task.Delay(100);
                                }
                            }
                        }
                    }

                    if (!isError)
                    {
                        await newClient.CompleteAsync(azureMessage.SystemProperties.LockToken);
                    }
                }, messageHandlerOptions);
                clients.Add(newClient);
            }

            CommonQueueEndpointConsumeControllerForServiceBus controller = new CommonQueueEndpointConsumeControllerForServiceBus(clients);

            return(controller);
        }
コード例 #5
0
        public async Task Add(CommonQueueConsumeEndpoint endpoint)
        {
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, false, false, _commonQueueConnectionFactory.CreateAllForCommonQueue(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }

                await using (SqlCommand commond = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran
                })
                {
                    if (endpoint.ID == Guid.Empty)
                    {
                        commond.CommandText = @"insert into CommonQueueConsumeEndpoint([id],[name],[queuetype],[queueconfiguration],[createtime],[modifytime])
                                    values(default,@name,@queuetype,@queueconfiguration,getutcdate(),getutcdate());
                                    select @newid=[id] from CommonQueueConsumeEndpoint where [sequence]=SCOPE_IDENTITY()";
                    }
                    else
                    {
                        commond.CommandText = @"insert into CommonQueueConsumeEndpoint([id],[name],[queuetype],[queueconfiguration],[createtime],[modifytime])
                                    values(@id,@name,@queuetype,@queueconfiguration,getutcdate(),getutcdate())";
                    }

                    SqlParameter parameter;
                    if (endpoint.ID != Guid.Empty)
                    {
                        parameter = new SqlParameter("@id", SqlDbType.UniqueIdentifier)
                        {
                            Value = endpoint.ID
                        };
                        commond.Parameters.Add(parameter);
                    }
                    else
                    {
                        parameter = new SqlParameter("@newid", SqlDbType.UniqueIdentifier)
                        {
                            Direction = ParameterDirection.Output
                        };
                        commond.Parameters.Add(parameter);
                    }

                    parameter = new SqlParameter("@name", SqlDbType.VarChar, 150)
                    {
                        Value = endpoint.Name
                    };
                    commond.Parameters.Add(parameter);

                    parameter = new SqlParameter("@queuetype", SqlDbType.VarChar, 150)
                    {
                        Value = endpoint.QueueType
                    };
                    commond.Parameters.Add(parameter);

                    parameter = new SqlParameter("@queueconfiguration", SqlDbType.NVarChar, endpoint.QueueConfiguration.Length)
                    {
                        Value = endpoint.QueueConfiguration
                    };
                    commond.Parameters.Add(parameter);

                    await commond.PrepareAsync();

                    await commond.ExecuteNonQueryAsync();

                    if (endpoint.ID == Guid.Empty)
                    {
                        endpoint.ID = (Guid)commond.Parameters["@newid"].Value;
                    }
                }
            });
        }
コード例 #6
0
        public async Task <QueryResult <CommonQueueConsumeEndpoint> > QueryByPage(string name, int page, int pageSize)
        {
            QueryResult <CommonQueueConsumeEndpoint> result = new QueryResult <CommonQueueConsumeEndpoint>();

            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, true, false, _commonQueueConnectionFactory.CreateReadForCommonQueue(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }

                await using (SqlCommand commond = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran,
                    CommandText = string.Format(@"
		                           select @count= count(*) from [CommonQueueConsumeEndpoint] where [name] like @name
	
                                    select {0} from [CommonQueueConsumeEndpoint] where [name] like @name
                                    order by [sequence]
		                            offset (@pagesize * (@page - 1)) rows 
		                            fetch next @pagesize rows only;"        , StoreHelper.GetCommonQueueConsumeEndpointSelectFields(string.Empty))
                })
                {
                    var parameter = new SqlParameter("@page", SqlDbType.Int)
                    {
                        Value = page
                    };
                    commond.Parameters.Add(parameter);

                    parameter = new SqlParameter("@pagesize", SqlDbType.Int)
                    {
                        Value = pageSize
                    };
                    commond.Parameters.Add(parameter);

                    parameter = new SqlParameter("@name", SqlDbType.VarChar, 200)
                    {
                        Value = $"{name.ToSqlLike()}%"
                    };
                    commond.Parameters.Add(parameter);

                    parameter = new SqlParameter("@count", SqlDbType.Int)
                    {
                        Direction = ParameterDirection.Output
                    };
                    commond.Parameters.Add(parameter);

                    await commond.PrepareAsync();

                    SqlDataReader reader = null;

                    await using (reader = await commond.ExecuteReaderAsync())
                    {
                        while (await reader.ReadAsync())
                        {
                            var endpoint = new CommonQueueConsumeEndpoint();
                            StoreHelper.SetCommonQueueConsumeEndpointSelectFields(endpoint, reader, string.Empty);
                            result.Results.Add(endpoint);
                        }

                        await reader.CloseAsync();

                        result.TotalCount  = (int)commond.Parameters["@count"].Value;
                        result.CurrentPage = page;
                    }
                }
            });

            return(result);
        }