ぶろぐ

日記です

validation query入れてみた


アプリを長時間放置した後にDBアクセスをするとエラーが出た。

play.api.Application$$anon$1: Execution exception[[CommunicationsException: The last packet successfully received from the server was 55,535,223 milliseconds ago.  The last packet sent successfully to the server was 55,535,224 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.]]

どうやらデフォルトで8時間放置するとmysqlのコネクションが切断されるようで。
autoReconnect=trueをjdbcのurlに加えるといいらしいが、色々と不都合があるらしいのでアプリ側で対応することがベターっぽい。
queryを投げる前にダミーのqueryを投げてコネクションが生きているかどうかを確かめる、という方法が一般的らしい。
ORM側でサポートされていることが多いみたいで、今使用しているscalikejdbcだと以下の設定を入れればおkだった。play2使っているのでconf/application.confに追記しました。

db.default.poolValidationQuery="select 1 as one"
参考
http://scalikejdbc.org/documentation/connection-pool.html

mysqlのquery logを見てみると…

 107 Query	select 1 as one
 107 Query	SET autocommit=1
 107 Query	select * from hoge_table;

毎回、目的のqueryを発行する前に投げていることを確認。ちょっとだけオーバーヘッドありそうだけど、pingみたいなものだと思えばいいかなー