通过设置statement_timeout参数设置命令最大执行时间,单位为毫秒,超过时间将取消执行.
1. 配置文件 设置
.在postgresql.conf中配置statement_timeout参数(单位为毫秒),会影响所有会话,不建议使用.
2.在当前会话中设置
仅对当前会话生效(单位为毫秒)
set statement_timeout to 30000;
3.Npgsql通过连接字符串设置
connectionString="ApplicationName=xxx;Server=xxx;Database=xxx;Userid=xxx;Password=xxx;Pooling=true;MinPoolSize=1;MaxPoolSize=100;CommandTimeout=50;"
连接字符串建议按以下格式设置
ApplicationName:应该程序名,建议设置,以便在pg中查看那些程序使用的连接
Server:pg服务器名称或ip
Database:pg数据库名称
Userid:pg数据库用户名
Password:pg数据库密码
Pooling:是否使用连接池
MinPoolSize:连接池最小数量
MaxPoolSize:连接池最大数量
CommandTimeout:执行使命超时时间(单位为秒),执行sql超过此时间将取消,并返回一个错误
虽然设置了Pooling,便使用完成后连接仍要关闭
4.JAVA
其它语言连接成功后,立即执行的命令(单位为毫秒)
private PgConnection openDatabase(String appName, DBConfig pDBConf) throws SQLException {
//https://jdbc.postgresql.org/documentation/head/connect.html
String connString = String.format("jdbc:postgresql://%s:%d/%s",
pDBConf.getServer(), pDBConf.getPort(), pDBConf.getDBName());
Properties props = new Properties();
props.setProperty("ApplicationName", appName);
props.setProperty("user", pDBConf.getUser());
props.setProperty("password", pDBConf.getPassword());
props.setProperty("ssl", "false");
props.setProperty("connectTimeout", String.valueOf(pDBConf.getConnTimeout())); //设置连接超时时间
//props.setProperty("readOnly", "true"); //是否只读取,集群时使用从机需要设置
props.setProperty("options", String.format("-c statement_timeout=%d", pDBConf.getStatementTimeout())); //设置执行命令超时时间
props.setProperty("prepareThreshold", String.valueOf(pDBConf.getPrepareThreshold())); //同一sql执行至第几次开始使用预处理sql
props.setProperty("preparedStatementCacheQueries", String.valueOf(pDBConf.getPreparedStatementCacheQueries())); //每个连接中缓存的SQL数量
props.setProperty("preparedStatementCacheSizeMiB ", String.valueOf(pDBConf.getPreparedStatementCacheSizeMiB())); //预备语句查询缓存大小,单位为MB,0为禁用
Connection conn = DriverManager.getConnection(connString, props);
conn.setAutoCommit(false);
return (PgConnection) conn;
}
然后再做其它操作.