Grails连MySQL - 连接池超时问题

本文探讨了一款Grails应用在部署后首次登录时遇到的密码错误问题,并深入分析了其原因在于数据库连接超时。文章详细介绍了如何通过日志记录定位问题所在,并提供了三种解决方案:调整MySQL超时设置、修改Hibernate连接池配置或使用更高级的c3p0连接池。
[b]问题表象[/b]
上线后的Grails应用,第二天,第一次登陆总是提示密码错误,再登陆一下就能成功。

[b]推测倒是很准确[/b]
肯定是Tomcat或MySQL的某处超时设置导致的

[b]准确诊断[/b]
因为无法在开发环境下模拟问题,先想办法在服务器端记录日志
Grails集成了[color=blue]log4j[/color],用起来超级简单,而且还支持“环境”选项。

log4j = {
appenders {
environments {
production {
file name: 'file', file: '/home/jcat/myoalog/myoa.log'
}
development {
file name: 'file', file: 'c:\\myoa.log'
}
}
}

root {
info 'stdout', 'file'
}

info 'grails.app', 'myoa.StaticFilter'
}


[color=red]然后在日志中发现了问题(这个log并不是我设计的,而是Shiro框架源码里的,可见人家是专业的)[/color]
2013-05-20 16:12:45,582 [http-bio-8080-exec-40] ERROR util.JDBCExceptionReporter - The last packet successfully received from the server was [color=red]282,966,727 milliseconds [/color]ago. The last packet sent successfully to the server was 282,966,728 milliseconds ago. is longer than the server configured value of [color=red]'wait_timeout'[/color]. 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.

2013-05-20 16:12:45,601 [http-bio-8080-exec-40] INFO app.realm - Unable to authenticate with myoa.DbRealm - could not execute query; nested exception is org.hibernate.exception.JDBCConnectionException: could not execute query

[b]模拟错误[/b]
mysql> show global variables like 'wait_timeout';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout | 28800 |
+---------------+-------+
1 row in set (0.00 sec)


--重启后失效
set global wait_timeout=60; --60秒

--需要停机配置
cat /etc/my.cnf
[mysqld]
wait_timeout=60

有趣的是,连接池超时后,登录后的浏览器会话并不会超时,所以第一次刷新会报错,再刷新(并不需要登录)就正常工作了。

[b]最终解决[/b]
有3个途径
1. 调大MySQL的timout时间,网上说,最大到21天左右
2. 修改Hibernate的连接池组件,采用更高级的c3p0 http://blog.youkuaiyun.com/nethibernate/article/details/6658855
3. 修改默认的DBCP连接池的配置
[color=red]http://www.netingcn.com/dbcp-config.html[/color]
http://sacharya.com/grails-dbcp-stale-connections

【法1-推荐】
        dataSource {   
//解决数据库连接池长期不用超时的问题
properties {
timeBetweenEvictionRunsMillis = 1000 * 60 * 60 * 3 //每3小时检查一次
minEvictableIdleTimeMillis = 1000 * 60 * 60 * 3 //把超过3小时的空闲连接激活一次
//这样最差的情况,一个连接最多空闲6小时,而MySQL配置的是8小时断开
}
}


【法2-这会导致从连接池拿连接之前都会执行一次select 1语句】
                testOnBorrow = true
testWhileIdle = false
testOnReturn = false
validationQuery = "SELECT 1"
/** * Created by RoWe on 2025/04/29 * 创建关联关系接口 */ package com.elite.groovy.callback import com.elite.groovy.util.EliteBean import com.elite.groovy.util.Util import net.sf.json.JSONObject import org.apache.commons.logging.Log import org.apache.commons.logging.LogFactory import org.apache.http.HttpHost import org.apache.http.auth.AuthScope import org.apache.http.auth.UsernamePasswordCredentials import org.apache.http.client.config.RequestConfig import org.apache.http.conn.ssl.NoopHostnameVerifier import org.apache.http.impl.client.BasicCredentialsProvider import org.apache.http.impl.client.CloseableHttpClient import org.apache.http.impl.client.HttpClients import org.apache.http.ssl.SSLContexts import org.apache.http.util.EntityUtils import javax.net.ssl.SSLContext import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse //在工单页面选择手机选项并进行外呼时, CRM系统根据当前工单对应归属机构信息, 传入已经报备好的主叫号调用创建关联关系接口,获取隐私号telX,记录当前创建关联关系信息并将获取的隐私号telX连同调用接口的主叫号一起传给CC平台实现外呼 public class OCNAssociationAdd implements ServiceBackInvoke { private static final Log log = LogFactory.getLog(OCNAssociationAdd.class); otherUtil otherUtil = new otherUtil(); // 代理配置常量 private static final String PROXY_HOST = "wsproxy-dsu.sssit.com" private static final int PROXY_PORT = 8080 private static final String PROXY_USER = "cc-groovy" private static final String PROXY_PASS = "" // 替换为实际密码 public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=UTF-8"); String requestBody = Util.getRequestBody(request, "UTF-8"); String appCode = ""; String appMessage = ""; String dataSource = "dataSource"; JSONObject responseJson = new JSONObject(); JSONObject dataJson = new JSONObject(); CloseableHttpClient httpClient = null; try { JSONObject requestJson = JSONObject.fromObject(requestBody); // 必须每次请求的唯一标识 String requestId = UUID.randomUUID(); List appList = eliteBean.chaxun_sql("SELECT appId,appKey,telA FROM OCNApp WHERE method ='OCNAdd'", dataSource); String appId = appList[0].getAt("appId"); String appKey = appList[0].getAt("appKey"); //主叫号 4008333000 String telA = appList[0].getAt("telA"); //客户号码 String telB = requestJson.getString("telB"); //指定地区 String areaCode = requestJson.getInt("areaCode"); // log.debug("telB",telB); // log.debug("areaCode",areaCode); List AreaInfoList = eliteBean.chaxun_sql("SELECT CCCityCode FROM AreaInfo WHERE areaCode='$areaCode'", dataSource); String CCCityCode = AreaInfoList[0].getAt("CCCityCode"); //是否严格匹配 经过三星老师定版为 0 int areaMatchMode = 0; //创建时间戳 long creTimeStemp = System.currentTimeMillis(); //有效时间 暂定5分钟,单位为毫秒 和后续删除关联关系有关 int expiration = 300000; //long tempStemp=System.currentTimeMillis(); //seqId string(32) 必须绑定关系的序列号 String seqId = ""; //telX string(20) 条件X 号码管理方式为Random 时,系统随机分配的号码 String telX = ""; int InsertOCNAssociation = eliteBean.update( "INSERT INTO OCNAssociation (requestId,telA,telB,areaCode,areaMatchMode,creTimeStemp,expiration) VALUES('${requestId}','${telA}','${telB}','${areaCode}','${areaMatchMode}','${creTimeStemp}','${expiration}') ", dataSource); JSONObject req = new JSONObject(); req.put("requestId", requestId); req.put("telA", telA); req.put("telB", telB); req.put("CCCityCode", CCCityCode); req.put("areaMatchMode", areaMatchMode); req.put("expiration", expiration); OCNRUtils OCNRUtils = new OCNRUtils(); // sm4密钥:将appKey转成md5再取中间16位 String sm4Key = OCNRUtils.get16MD5(appKey); // sm4加密 OCNRUtils.sign(req, appId, appKey); // 设置加密后的member //req.put("member", membersEncrypted); Map headMap = new HashMap(); headMap.put("Content-Type", "application/json"); headMap.put("charset", "utf-8"); List urlSql = eliteBean.chaxun_sql("select url,method from sysc_interface where method ='OCNAdd'", "dataSource"); if (urlSql != null && !urlSql.empty) { // 创建带代理的HTTP客户端 httpClient = createProxyHttpClient(); // 执行POST请求 String webService = "https://ystx.wo.com.cn:19090/privateapi/axb/create"; String responseInfo = doProxyPost(httpClient, webService, req.toString()); // 处理响应 responseJson = JSONObject.fromObject(responseInfo); appCode = responseJson.getString("code"); appMessage = responseJson.getString("msg"); dataJson = responseJson.getJSONObject("data"); responseJson.put('appCode', appCode); responseJson.put('appMessage', appMessage); return responseJson.toString(); } else { appCode = "222"; appMessage = "接口地址维护异常"; } appCode = "222"; appMessage = "测试成功"; responseJson.put('appCode', appCode); responseJson.put('appMessage', appMessage); responseJson.put('requestId', requestId); //responseJson.put('telX', telX); return responseJson; } catch (Exception e) { log.error("e:", e); appCode = "999"; appMessage = "系统异常,请稍后重试"; responseJson.put('appCode', appCode); responseJson.put('appMessage', appMessage); responseJson.put('e', e); return responseJson; } finally { try { if (httpClient != null) httpClient.close(); } catch (Exception e) { log.error("关闭HTTP客户端失败:", e); } } } /** * 创建带代理的HTTP客户端 */ private CloseableHttpClient createProxyHttpClient() { // 代理凭证提供器 def credsProvider = new BasicCredentialsProvider() credsProvider.setCredentials( new AuthScope(PROXY_HOST, PROXY_PORT), new UsernamePasswordCredentials(PROXY_USER, PROXY_PASS) ) // SSL上下文(信任所有证书 - 仅测试环境使用) SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, { certs, authType -> true }) .build() // 请求配置 def requestConfig = RequestConfig.custom() .setProxy(new HttpHost(PROXY_HOST, PROXY_PORT)) .setConnectTimeout(30000) // 30秒连接超时 .setSocketTimeout(60000) // 60秒数据传输超时 .build() // 创建HTTP客户端 return HttpClients.custom() .setDefaultCredentialsProvider(credsProvider) .setSSLContext(sslContext) .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setDefaultRequestConfig(requestConfig) .build() } /** * 通过代理执行POST请求 * @param client HTTP客户端 * @param url 目标URL * @param body 请求体JSON字符串 */ private String doProxyPost(CloseableHttpClient client, String url, String body) { def httpPost = new org.apache.http.client.methods.HttpPost(url) // 设置请求头 httpPost.setHeader("Content-Type", "application/json") httpPost.setHeader("charset", "utf-8") // 设置请求体 httpPost.setEntity(new org.apache.http.entity.StringEntity(body, "UTF-8")) // 执行请求 def response = client.execute(httpPost) def entity = response.getEntity() try { return EntityUtils.toString(entity, "UTF-8") } finally { EntityUtils.consume(entity) } } }代码报错500的原哟
最新发布
07-10
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值