简体   繁体   中英

Connections in loop for SQL Server Symfony2

i´ve been trying to create a loop for different MSSQL Server in Symfony 2.3, but if some of the servers is off or the MSSQL service is down, the app don't make an exception and it breaks the function.

This is the main controller:

function pruebaconAction()
{
    $enlistaServers = new array (
                                 10.10.10.1, 
                                 10.10.10.2, 
                                 10.10.10.3, 
                                 ...
                                 10.10.10.19,
                                 10.10.10.20
                                );

    foreach($enlistaServers as $datosServer)
    {
        $direccionIPParaConexion = $datosServer->getDireccionIp ();
        $nombreLocalidad = $datosServer->getNombre();
        register_shutdown_function(array($this, 'conectaSrv'), $direccionIPParaConexion, $nombreLocalidad);
    }
    return $this->render("GastoEnlaceBundle:Default:pruebacon.html.twig");
}

This function create the conection:

function conectaSrv($direccionIpConexion, $nombreLocalidad)
{
    $pruebaDBAL = new \Doctrine\DBAL\Configuration();
    $parametrosConexion = array(
        'dbname' => 'MyDB',
        'user' => 'user',
        'password' => 'password',
        'host' => $direccionIpConexion,
        'driver' => 'pdo_sqlsrv'
    );
    $conexionDBAL = DriverManager::getConnection($parametrosConexion, $pruebaDBAL);
    if($conexionDBAL->connect())
        echo "Success<br />";
    else
        throw new Exception("Something is wrong :(<br />");
    echo "=======================================================================<br />";
}

I Always get the same result, for all the servers on line, the connection is sucessfully but if some of the servers is offline the function never send an exception and it breaks the loop.

I hope someone can help me or give an advice, thanks a lot.

register_shutdown_function Registers a callback to be executed after script execution finishes or exit() is called

So I think you can't operate new connection even if you get it. IMHO, the better approach will be creation of own service which handle DB connections and don't use this->getDoctrine(). In this service you can call for different entity managers (one for every ip) and check for exception. If exception rise you can use another entity manager to run query and maybe set it as default;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM