ORACLE自动杀活动会话

近来发现因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),
createdate DATE default sysdate,
logon_time DATE
);

create table ACTIVESESSION_TMP1
(
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,
logon_time DATE
);

 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,sysdate,t.logon_time from v$session t where t.type != 'BACKGROUND' and t.status = 'ACTIVE' and t.username is not null;
        insert into activesession_tmp1 select t.username,t.status,t.osuser,t.machine,t.program,t.client_info,s.sql_text,sysdate,t.logon_time 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;

创建job没五分钟执行一次

begin
  sys.dbms_job.submit(job => :job,
                      what => 'KILL_SESSION;',
                      next_date => to_date('06-08-2021 10:20:16', 'dd-mm-yyyy hh24:mi:ss'),
                      interval => 'sysdate+5/(24*60)');
  commit;
end;
/

 

  

posted @ 2021-06-22 08:54  玄澈  阅读(237)  评论(0编辑  收藏  举报