1. 程式人生 > 實用技巧 >Oracle Advanced Queuing

Oracle Advanced Queuing

1.環境配置

[oracle@DB01 ~]$ sql sys/[email protected]:1521/MPTEST as sysdba

CREATE USER aq_admin IDENTIFIED BY aq_admin DEFAULT TABLESPACE TEST_UD;

GRANT connect TO aq_admin;
GRANT create type TO aq_admin;
GRANT aq_administrator_role TO aq_admin;
ALTER USER aq_admin QUOTA UNLIMITED ON TEST_UD;

CREATE USER aq_user IDENTIFIED BY aq_user DEFAULT TABLESPACE TEST_UD;
GRANT connect TO aq_user;
GRANT aq_user_role TO aq_user;

2.定義傳送的物件型別(event_msg_type)

CONNECT aq_admin/aq_admin

CREATE OR REPLACE TYPE event_msg_type AS OBJECT (
  name            VARCHAR2(10),
  current_status  NUMBER(5),
  next_status     NUMBER(5)
);
/

GRANT EXECUTE ON event_msg_type TO aq_user;

3.建立佇列及隊列表

CONNECT aq_admin/aq_admin

建立隊列表
EXECUTE DBMS_AQADM.create_queue_table (queue_table => 'aq_admin.event_queue_tab',queue_payload_type => 'aq_admin.event_msg_type');

建立佇列
EXECUTE DBMS_AQADM.create_queue (queue_name =>  'aq_admin.event_queue',queue_table => 'aq_admin.event_queue_tab');

啟動佇列
EXECUTE DBMS_AQADM.start_queue (queue_name => 'aq_admin.event_queue',enqueue => TRUE);

4.授權給 aq_user 使用者訪問 佇列

CONNECT aq_admin/aq_admin

EXECUTE DBMS_AQADM.grant_queue_privilege (privilege => 'ALL',queue_name => 'aq_admin.event_queue',grantee => 'aq_user',grant_option => FALSE);

5.入隊訊息

CONNECT aq_user/aq_user

DECLARE
  l_enqueue_options     DBMS_AQ.enqueue_options_t;
  l_message_properties  DBMS_AQ.message_properties_t;
  l_message_handle      RAW(16);
  l_event_msg           AQ_ADMIN.event_msg_type;
BEGIN
  l_event_msg := AQ_ADMIN.event_msg_type('REPORTER', 1, 2);

  DBMS_AQ.enqueue(queue_name => 'aq_admin.event_queue',enqueue_options => l_enqueue_options,message_properties  => l_message_properties,payload => l_event_msg,msgid => l_message_handle);
  COMMIT;
END;
/

6.出隊訊息

CONNECT aq_user/aq_user

SET SERVEROUTPUT ON

DECLARE
  l_dequeue_options     DBMS_AQ.dequeue_options_t;
  l_message_properties  DBMS_AQ.message_properties_t;
  l_message_handle      RAW(16);
  l_event_msg           AQ_ADMIN.event_msg_type;
BEGIN
  DBMS_AQ.dequeue(queue_name => 'aq_admin.event_queue',dequeue_options => l_dequeue_options,message_properties => l_message_properties,payload => l_event_msg,msgid => l_message_handle);

  DBMS_OUTPUT.put_line ('Event Name          : ' || l_event_msg.name);
  DBMS_OUTPUT.put_line ('Event Current Status: ' || l_event_msg.current_status);
  DBMS_OUTPUT.put_line ('Event Next Status   : ' || l_event_msg.next_status);
  COMMIT;
END;
/