Oracle清除数据库中长时间占用资源的非活动的会话
1、启动资源计划
alter system set resource_limit=true scope=spfile;
2、设置非活动回话十五分钟断开,释放资源
alter profile default limit idle_time 15;
3. 清楚非活动的进程 (没10分钟发送检测包)
$ORACLE_HOME/network/admin 添加 SQLNET.EXPIRE_TIME=10;
SELECT SID, SERIAL#,MODULE, STATUS
FROM V$SESSION S
WHERE S.USERNAME ISNOTNULL
ANDUPPER(S.PROGRAM) IN ('TOAD.EXE', 'W3WP.EXE')
AND S.LAST_CALL_ET >= 60*60*2
AND S.STATUS = 'INACTIVE'
ORDERBY SID DESC;
如果是RAC环境,那么最好使用下面SQL语句,使用全局视图GV$SESSION。
SELECT SID, SERIAL#, INST_ID, MODULE,STATUS
FROM gv$session S
WHERE S.USERNAME ISNOTNULL
ANDUPPER(S.PROGRAM) IN ('TOAD.EXE', 'W3WP.EXE')
AND S.LAST_CALL_ET >= 2 * 60*60
AND S.STATUS = 'INACTIVE'
ORDERBY INST_ID DESC
CREATE OR REPLACE PROCEDURE SYS.DB_KILL_IDLE_CLIENTS AUTHID DEFINER AS
job_no number;
num_of_kills number := 0;
BEGIN
FOR REC IN
(SELECT SID, SERIAL#, INST_ID, MODULE,STATUS
FROM gv$session S
WHERE S.USERNAME IS NOT NULL
AND UPPER(S.PROGRAM) IN ('xxx', 'xxx.EXE')
AND S.LAST_CALL_ET >= 2*60*60
AND S.STATUS= 'INACTIVE'
ORDER BY INST_ID ASC
) LOOP
---------------------------------------------------------------------------
-- kill inactive sessions immediately
---------------------------------------------------------------------------
DBMS_OUTPUT.PUT('LOCAL SID ' || rec.sid || '(' || rec.module || ')');
execute immediate 'alter system kill session ''' || rec.sid || ', ' ||
rec.serial# || '''immediate' ;
DBMS_OUTPUT.PUT_LINE('. killed locally ' || job_no);
num_of_kills := num_of_kills + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE ('Number of killed xxxx system sessions: ' || num_of_kills);
END DB_KILL_IDLE_CLIENTS;
/
然后,我们可以在作业(JOB)或Schedule里面定期调用该存储过程,也可以通过后台作业结合shell脚本实现定期清理空闲会话的功能。例如如下所示。
创建killSession.sh脚本,调用该存储过程SYS.DB_KILL_IDLE_CLIENTS
1:#!/bin/bash
2:
3:
4:
5: logfile=/home/oracle/cron/session/log/killSession.log
6:
7: echo " " >> $logfile 2>&1
8: echo "START ----`date`" >> $logfile 2>&1
9: sqlplus /nolog <<STATS
10: connect / as sysdba
11: exec sys.db_kill_idle_clients;
12: exit;
13: STATS
14:
15: echo "END ------`date`" >> $logfile 2>&1
在crontab里面配置后台作业,每隔15分钟运行一次,清理哪些满足条件的空闲会话。
0,15,30,45 * * * * /home/oracle/cron/session/bin/killSession.sh >/dev/null 2>&1
授人以鱼不如授人以渔...