近来发现因WEB前端异常导致oracle服务器active session过多,load average增高,系统卡死,故写一个自动杀活动会话的存储过程
1.创建临时表
create table ACTIVESESSION_TMP ( username VARCHAR2(30), status VARCHAR2(8), osuser VARCHAR2(30), machine VARCHAR2(64), program VARCHAR2(48), client_info VARCHAR2(64), sql_text varchar2(4000), createdate date default SYSDATE )
2.使用存储过程每五分钟执行一次,当active session大于50时记录active session信息并杀掉
CREATE OR REPLACE PROCEDURE "KILL_SESSION" AS v_sid number; v_serial number; v_count number; killer varchar2(4000); begin select count(*) into v_count from v$session where type != 'BACKGROUND' and status = 'ACTIVE' and username not like '%SYS%'; if v_count > 50 then declare CURSOR cursor_session_info is select sid, serial# from v$session where type != 'BACKGROUND' and status = 'ACTIVE' and username not like '%SYS%'; begin insert into activesession_tmp select t.username,t.status,t.osuser,t.machine,t.program,t.client_info,s.sql_text,sysdate from v$session t,v$sqlarea s where t.type != 'BACKGROUND' and t.status = 'ACTIVE' and t.username is not null and t.SQL_ID=s.SQL_ID; commit; open cursor_session_info; loop fetch cursor_session_info into v_sid, v_serial; exit when cursor_session_info%notfound; killer := 'alter system kill session ''' || v_sid || ',' || v_serial || '''immediate'; execute immediate killer; end loop; dbms_output.PUT_LINE(cursor_session_info%rowcount || 'active users with count>50 have been killed!'); close cursor_session_info; end; END if; end;