MySQL 參數autoReconnect=true 解決8小時串連失效

來源:互聯網
上載者:User

1. 即使在建立Mysql時url中加入了autoReconnect=true參數,一但這個串連兩次訪問資料庫的時間超出了伺服器端wait_timeout的時間限制,還是會CommunicationsException: The last packet successfully received from the server was xxx milliseconds ago.
2. 伺服器端的參數可以用
  show global variables like 'wait_timeout';
  set global wait_timeout=10;
  來進行設定,但是wait_timeout值不應該設的太高.
3. 較好的策略是對處於idle狀態的connection定時發送一個sql,來重新整理伺服器上的時間戳記.這可以使用c3p0r的串連池.http://bzhang.iteye.com/blog/321832
4. 對於tomcat的server.xml中使用的串連池,http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html,http://commons.apache.org/dbcp/configuration.html使用DBCP的串連池可以採用
<Resource name="jdbc/test" auth="Container" 
              type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8" 
              username="root" password="test" maxActive="500" maxIdle="10" 
              maxWait="-1" timeBetweenEvictionRunsMillis="10000" minEvictableIdleTimeMillis="10000" />
  4.1 設定validationQuery,這樣每次borrow(預設為開啟)時會通過這個sql校正串連的有效性,但是增加了時間.
  4.2 設定timeBetweenEvictionRunsMillis="10000" minEvictableIdleTimeMillis="10000" 依賴evictor thread線程來把逾時的串連關閉.
  4.3 設定testWhileIdle="true" timeBetweenEvictionRunsMillis="10000" validationQuery="select 1" 使得定時去用query檢測處於idle狀態的串連,也就重新整理了伺服器端的時間.

5.每次提交的最大packet大小
show global variables like 'max_allowed_packet';
set global max_allowed_packet=1024*1024;

6. SQLyog 中串連參數的設定
  6.1 在SQLyog中的設定 set autocommit=0,這樣當前串連的自動認可為false,可以控制事務了.
  6.2 begin; 事務開始
  6.3 select * from test where 1=1 and id =1 for update;這樣就把選到的記錄行鎖上了,再開一個SQLyog,也執行以上相同的操作,就會一直wait在那裡.
  6.4 commit; 提交
  6.5 rollback; 復原
  6.6 set autocommit=0;後應該加上
      set transaction isolation level read committed;
      這樣其它用戶端就能看到commit的資料,
  疑問:
      如果不設定set transaction isolation level read committed;如果兩個用戶端都select 相同的資料,一個用戶端修改然後提交,另一個用戶端不提交當前事務的前提下,去執行select ,取不到另一用戶端提交的資料,不知道SQLyog預設的事務層級是什麼樣的.

7. SQLyog中查看mysql的狀態,show global variables like '%lock%'; 是個好方法.對於事務鎖(例如for update)報Lock wait timeout exceeded ,只能通過修改my.ini檔案innodb_lock_wait_timeout = 100;才會生效.

8. linux下修改使用者密碼 mysqladmin -u root password "new_pass"

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.