프로덕션 서버가 비활성 연결을 종료하므로 API가 필요할 때이를 복원해야합니다. 다음 코드는 작동하지만 매우 반복적입니다.연결을 다시 여는 코드를 다시 사용하는 방법은 무엇입니까?
private const int MaxRetryCount = 3;
public static SqlDataReader RestoreConnectionAndExecuteReader(SqlCommand command)
{
int retryCount = 0;
while (retryCount++ < MaxRetryCount)
{
try
{
if (command.Connection.State == ConnectionState.Closed)
command.Connection.Open();
return command.ExecuteReader();
}
catch(Exception e)
{
if(!e.Message.ToLower().Contains("transport-level error has occurred"))
{
throw;
}
}
}
throw new Exception("Failed to restore connection for command:"+command.CommandText);
}
public static void RestoreConnectionAndExecuteNonQuery(SqlCommand command)
{
var retryCount = 0;
while(retryCount++ < MaxRetryCount)
{
try
{
if (command.Connection.State == ConnectionState.Closed)
command.Connection.Open();
command.ExecuteNonQuery();
return;
}
catch(Exception e)
{
if (!e.Message.ToLower().Contains("transport-level error has occurred"))
{
throw;
}
}
}
throw new Exception("Failed to restore connection for command:" + command.CommandText);
}
어떻게하면 내 코드를 리팩토링하고 중복을 제거 할 수 있습니까? 시스템의 모든 곳에서 사용되므로이 메소드의 서명을 유지해야합니다.
인터페이스에 메서드를 추출하는 것에 대해 생각해 보셨습니까? 또한 복제가 없으므로 하나의 메서드를 사용할 수 없습니다. 다른 하나는 SQLReader를 반환하는 반면, 하나의 메서드를 사용하고 params를 사용하여이 문제를 해결할 수 있습니다. – MethodMan
@DJKRAZE : 예, 했었습니다. 그러나 첫 번째 메서드는 SqlDataReader를 반환하고 두 번째 메서드는 void입니다. –
중복 로직을 기존의 모든 메소드에서 호출하여 bool 또는 SqlCommand 객체 자체를 다시 연결 한 다음 다시 조작 할 수있는 다른 메소드로 나눌 수 있습니다 ... NonQuery, ExecuteReader etc. –