现在的位置: 首页 > 综合 > 正文

【转载】解决JDBC 连接 SQL Azure 超时问题

2012年10月31日 ⁄ 综合 ⁄ 共 2499字 ⁄ 字号 评论关闭

最近在做一个Azure云项目,前台是Java代码,Java代码里使用JDBC驱动访问SQL Azure。

用了JDBC 连接串后,发现2分钟左右连接就超时timeout,原来在SQL Server上是能正常工作的。

jdbc:sqlserver://XXXX.database.windows.net:1433;database=miap;user=username@XXXX;password=myPassword;encrypt=true;hostNameInCertificate=*.database.windows.net

 

理论上SQL Azure会在30分钟后把idle connection自动踢掉,如下面文档所记载:

http://msdn.microsoft.com/en-us/library/windowsazure/ee336245.aspx

Maximumallowable durations are subject to change depending on the resource usage.A logged-in session that hasbeen idle for 30 minutes will be terminated automatically. We stronglyrecommend that you use the connection pooling and always close the connectionwhen you are finished using it so that the unused connection will be returnedto the pool.

目前ado.net 连接是符合上述文档的。但是,JDBC连接还需要一些额外设置,如下面的论坛网址中所描述:

http://social.msdn.microsoft.com/Forums/en-US/ssdsgetstarted/thread/69f2de2f-389b-4c4e-9497-471b8094b029/

I rewrote the Java program in C Sharp, and predictably that worksfine and DOES NOT exhibit the connection drop problems.

I used Wireshark to compare the Java and .NET implementations at theTCP level and the problem becomes clear:

TCP Keep-Alivemessages are sent to SQL Azure every 30 seconds from the .NET code, but thereare no such messages from JDBC, hence the JDBC connection times out at betweenabout 61 to 63 seconds.

针对这个问题的解决方案在这里http://msdn.microsoft.com/en-us/library/hh290696(v=SQL.110).aspx


 

Registry Setting

Recommended Value

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\KeepAliveTime

30000

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\KeepAliveInterval

1000

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\TcpMaxDataRetransmission

10

 

You must then restart the computer for the registry settings to take effect.

To accomplish this when running in Windows Azure create a startup task to add the registry keys. For example, add the following Startup task to the service definition file:

<Startup>
    <Task commandLine="AddKeepAlive.cmd" executionContext="elevated" taskType="simple">
    </Task>
</Startup>

Then add a AddKeepAlive.cmd file to your project. Set the "Copy to Output Directory" setting to Copy always. The following is a sample AddKeepAlive.cmd file:

if exist keepalive.txt goto done
time /t > keepalive.txt
REM Workaround for JDBC keep alive on SQL Azure
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters /v KeepAliveTime /t REG_DWORD /d 30000 >> keepalive.txt
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters /v KeepAliveInterval /t REG_DWORD /d 1000 >> keepalive.txt
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters /v TcpMaxDataRetransmission /t REG_DWORD /d 10 >> keepalive.txt
shutdown /r /t 1
:done

抱歉!评论已关闭.