判断 Mysql服务端是否在线

在操作MySQL时候需要判断Connection连接是否可用。
本人试验2种方式:
   1.Socket(直连通过MySQL服务端IP、port来连接)
   2.使用查询是否可用,否则抛异常来判断

本人选择第二种方式来判断

第一种:Socket
(直连通过MySQL服务端IP、port来连接)
Socket s_client = null;
	try {
	    SocketAddress sa_add = new InetSocketAddress(cbd_obj.getUser_Ip().trim(),Integer.parseInt(cbd_obj.getUser_Port().trim()));
	    s_client = new Socket();
	    s_client.connect(sa_add,1000);//连接超过1秒则,抛SocketTimeoutException 异常
	}  catch (UnknownHostException e) {
	    System.out.println(e.getMessage());
	    return true;
	} catch (SocketTimeoutException e) {
	    System.out.println(e.getMessage());
	    return true;
	} catch (IOException e) {
	    System.out.println(e.getMessage());
	    return true;
	}finally{
	    try {
		if(s_client != null)
		s_client.close();
	    } catch (IOException e) {
	    }
	}


Socket频率过高会导致,多次建立连接会报 Host is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts' 同一个ip在短时间内产生太多(超过mysql数据库max_connection_errors的最大值)中断的数据库连接而导致的阻塞;, 所以不可行


第二种 查询抛异常
 Statement pingStatement = null;
	    try
	    {
	      pingStatement = cbd_obj.getC_Connection().createStatement();

	      pingStatement.executeQuery("/* ping */ SELECT 1").close();

	      return false;
	    }catch(CommunicationsException ce_sql){
		try {
		    cbd_obj.getC_Connection().close();
		} catch (SQLException e) {
		}
		return true;
	    } catch (SQLException e) {
		return false;
	    }finally {
	      if (pingStatement != null)
	        try {
	          pingStatement.close();
	        }
	        catch (SQLException sqlEx)
	        {
	        }
	    }

使用正常

猜你喜欢

转载自dajian0822.iteye.com/blog/2185232