少年阿賓

          那些青春的歲月

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks

          #

           CREATE OR REPLACE PROCEDURE INSERTAMOUNTTEST
          (
          ST_NUM        IN     NUMBER,
          ED_NUM        IN     NUMBER
          )
          IS
          BEGIN
          declare
                 i   number;
          begin
          FOR i IN ST_NUM..ED_NUM LOOP
          INSERT INTO tb values(i,i,'3','3','3',100,'0');
          END LOOP;
          end;
          END;

          運行:
          sql>execute INSERTAMOUNTTEST(1,45000)   -- 一次插入45000條測試數據

          2、從存儲過程中返回值
          create or replace procedure spaddflowdate
          (
          varAppTypeId               in varchar2,
          varFlowId                  in varchar2,
          DateLength                 in number,
          ReturnValue                out number    --返回值
          )
          is
          begin
          insert into td values(varAppTypeId,varFlowId,DateLength)
          returning 1 into ReturnValue;   --返回值
          commit;
          exception
          when others then
          rollback;
          end;

          存儲過程的執行
          sql>variable testvalue  number;
          sql>execute spaddflowdate('v','v',2,:testvalue);
          sql>print
          就可以看到執行結果

           

          3、用包實現存儲過程返回游標:
          create  or  replace  package  test_p 
          as 
           
          type  outList  is  ref  cursor; 
           
          PROCEDURE  getinfor(taxpayerList  out  outList); 
           
          end  test_p; 


          create  or  replace  package  body  test_p  as  PROCEDURE  getinfor(taxpayerList out  outList)  is  begin 
                OPEN  taxpayerList    FOR  select  *  from
                                  td where tag='0'; 
           
          end  getinfor; 
           
          end  test_p; 

           
           
           
          運行:
           
          set  serverout  on;    --將輸出工具打開
           
          variable  x  refcursor; 
           
          execute test_p.getinfor(:x);

          exec  test_p.getinfor(:x);
           
          print  x; 


          drop package test_p;

           

           

           

          /*procedural language/sql*/
          --1、過程、函數、觸發器是pl/sql編寫的
          --2、過程、函數、觸發器是在oracle中的
          --3、pl/sql是非常強大的數據庫過程語言
          --4、過程、函數可以在java程序中調用

          --提高效率:優化sql語句或寫存儲過程
          --pl/sql移植性不好

          --IDE(Integration Develop Environment)集成開發環境

          --命令規則:
          --變量(variable)           v_
          --常量(constant)           c_
          --指針、游標(cursor)         _cursor
          --例外、異常(exception)    e_

          --可定義的變量和常量:
            --標量類型:scalar
            --復合類型:composite    --存放記錄、表、嵌套表、varray
            --參照類型:reference
            --lob(large object)
           


          《PL/SQL 基本語法》

          --例:創建存儲過程
          create or replace procedure pro_add
          is
          begin
            insert into mytest values('韓xx','123');
          end;
          exec pro_add; --調用

          --查看錯誤信息
          show error;
          --調用過程
          exec 過程(c1,c2,...);
          call 過程(c1,c2,...);
          --打開/關閉輸出選項
          set serveroutput on/off
          --輸入
          &

          --塊結構示意圖
          declare   --定義部分,定義常量、變量、游標、例外、復雜數據類型
          begin     --執行部分,執行pl/sql語句和sql語句
          exception --例外處理部分,處理運行的各種錯誤
          end;      --結束


          --《實例演示》
          declare
            v_ival number(4) :=100; --聲明并初始化變量
            --v_dtm date;
            v_dtm syslogs.dtm%type; --取表字段類型
            v_content varchar(512);
          begin
            v_ival := v_ival * 90;  --賦值運算
            insert into syslogs values(seq_syslogs.nextval,10,sysdate,'v_ival='||v_ival,user);--數據庫存儲
            dbms_output.put_line('v_ival'||v_ival);
           
            select count(*) into v_ival from syslogs;--使用select查詢賦值
          --select ename,sal into v_name,v_sal from emp where empno=&aa;
            insert into syslogs values (seq_syslogs.nextval,10,sysdate,'日志條數='||v_ival,user);
            dbms_output.put_line('日志條數'||v_ival);
            
            --獲取日志序號==11的日志時間和日志內容
            select dtm , content
            into v_dtm,v_content
            from syslogs
            where logid=14;
           
            insert into syslogs values (seq_syslogs.nextval,'10',sysdate,'v_dtm='||v_dtm||'v_content='||v_content,user);
            dbms_output.put_line('v_dtm='||v_dtm||'v_content='||v_content);
            --修改日志序號=11的日志記錄人
            update syslogs
            set whois='PL/SQL.'||v_ival
            where logid = 14;
           
            --delete syslogs where logid=15;
           
            --分支流程控制
            if v_ival>50 then
              dbms_output.put_line('日志需要清理了~');
            else
              dbms_output.put_line('日志空間正常!');
            end if;
           
            --Loop循環
            v_ival :=0;
            loop
                exit when v_ival>3;
                     --循環體
                     v_ival := v_ival+1;
                     dbms_output.put_line('loop循環:'||v_ival);
            end loop;
           
            --While循環
            v_ival := 0;
            while v_ival < 4
            loop
               --循環體
               v_ival := v_ival+1;
               dbms_output.put_line('while循環:'||v_ival);
            end loop;
           
            --For循環
            for v_count in reverse 0..4 loop  --reverse遞減
                dbms_output.put_line('for循環:'||v_count);  
            end loop;
            commit;--提交事物
          end;

          select * from syslogs;

           

           

          《PL/SQL 異常處理》

          --PL/SQL異常處理:oracle內置異常,oracle用戶自定義異常
          declare
             v_title logtypes.tid%type;
             v_ival number(9,2);
             --自定義的異常
             ex_lesszero exception ;
          begin
            --select title into v_title
            --from logtypes     --;  too_many_rows
            --where tid = 30 ;  --NO_DATA_FOUND 異常
           
            v_ival := 12/-3;
           
            if v_ival < 0 then
              --直接拋出異常
              --raise ex_lesszero ;
              --使用系統存儲過程拋出異常
              raise_application_error(/*錯誤代碼,-20000~-20999*/-20003,/*異常描述*/'參數不能小于0!');
            end if; 
            commit;
          exception
            --異常處理代碼塊
            when no_data_found then
              dbms_output.put_line('發生系統異常:未找到有效的數據!');
            when too_many_rows then
              dbms_output.put_line('發生系統異常:查詢結果超出預期的一行!');
            when ex_lesszero then
              dbms_output.put_line('發生用戶異常:數值不能為負!'||sqlcode||'異常描述:'||sqlerrm);
            when others then --other例如Exception
              rollback;
              dbms_output.put_line('發生異常!'||sqlcode||'異常的描述:'||sqlerrm);
          end;

           

           

          《PL/SQL 游標的使用》


          declare
              --游標的聲明
              cursor myCur is
                     select tid,title from logtypes ;
              --定義接收游標中的數據變量
              v_tid   logtypes.tid%type;
              v_title logtypes.title%type;
              --通過記錄來接受數據
              v_typercd myCur%rowtype ;
          begin
              --打開游標
              open myCur ;
              --取游標中的數據
              loop
                --遍歷游標中的下一行數據
                fetch myCur into v_tid,v_title ;
                --檢測是否已經達到最后一行
                exit when myCur%notfound ;
                --輸出游標中的數據
                dbms_output.put_line('讀取tid='||v_tid||' title='||v_title);
              end loop;
              --關閉游標
              close myCur;
             
              --打開游標
              open myCur ;
              loop
                fetch myCur into v_typercd ;
                exit when myCur%notfound ;
                dbms_output.put_line('--//讀取tid='||v_typercd.tid||' title='||v_typercd.title);
              end loop;
              --關閉游標
              close myCur ;
             
              --for循環游標
              for tmp_record in myCur loop
                dbms_output.put_line('++//讀取tid='||tmp_record.tid||' title='||tmp_record.title);
              end loop;

          end;


           

           

          《PL/SQL 存儲過程★》


          --            可以聲明入參in,out表示出參,但是無返回值。
          create or replace procedure prc_writelog(/*日志類型*/ tid in number ,
                                        /*日志內容*/ content in varchar2 ,
                                        /*錯誤碼  */ i_ret out number ,
                                        /*錯誤描述*/ s_ret out varchar2 )
          is

          begin
                insert into syslogs values (seq_syslogs.nextval , tid ,sysdate ,content ,user);
                commit;
                i_ret := 1 ;
                s_ret := '記錄日志成功!' ;
          exception
              when others then
                   rollback ;
                   i_ret := -1 ;
                   s_ret := '記錄日志失敗:'||sqlerrm ; 
          end;

          --測試
          declare
            iRet number(4) ;
            sRet varchar2(128) ;
          begin
            prc_writelog(10,'測試存儲過程',iRet,sRet);
            dbms_output.put_line('iRet:'||iRet||'sRet'||sRet);
          end;

          select * from syslogs;

           

           

          《PL/SQL 觸發器》

           

          --觸發器 是一種基于數據庫特定事件的 由數據庫自動執行的pl/sql塊
          --觸發的事件源:database 【啟動、停止、用戶聯機...】
          --              表名【insert/update/delete】
          --觸發時機 before/after
          --語句級、行級(需要知道數據,對數據庫運行速度有影響)
          create or replace trigger tri_logtypes
          after insert or update or delete --在所有的表的事件發生后執行
          on logtypes
          for each row --行級 (:new , :old)
          declare
              iret number(4);
              sret varchar2(128);
          begin
              --不要有事物的管理
              --:new 新數據 記錄型
              --:old 原有的數據 記錄型
              --prc_writelog(10,'觸發器執行了!',iret,sret);
              if inserting then
                  insert into syslogs values(seq_syslogs.nextval,10,sysdate,'觸發器執行添加數據!',user);
              elsif updating then
                  if :new.title <> :old.title then
                     raise_application_error(-20001,'不允許修改日志類型名稱數據!');    --拋出異常
                  end if;
                  insert into syslogs values(seq_syslogs.nextval,10,sysdate,'觸發器執行更新數據!',user);
              elsif deleting then
                  raise_application_error(-20001,'不允許刪除表中的數據!');
                  insert into syslogs values(seq_syslogs.nextval,10,sysdate,'觸發器執行刪除數據!',user);
              end if;
          end ;

          --test!
          insert into logtypes values(30,'test log');
          delete from logtypes where tid = 30;
          update logtypes set title = 'test log' where tid = 30;

          select * from syslogs order by dtm desc;
          select * from logtypes ;

           

           

          《案例》

           

          --創建表
          create table emp2 (
            name varchar2(30),
            sal number(8,2)
          );
          insert into emp2 values('simple',99999);
          insert into emp2 values(&a,&b);

          --存儲過程案例:
          --修改員工工資
          create or replace procedure pro_input(t_name in varchar2,
                                     t_sal in number)
          is
          begin
            update emp2 set sal = t_sal where name=t_name;
          end;
          --Test!
          declare
          begin
            pro_input('simple',2000);
          end;
          select * from emp2;

          --函數案例:
          create or replace function fun_test(t_name varchar2)
          return number is yearSal number(7,2);
          begin
            select sal*12 into yearSal from emp2 where name = t_name;
            return yearSal;
          end;

          --包案例:
          create package pac_test
          is                           --創建一個包pac_test
            procedure pro_input(t_name varchar2,t_sal number); --聲明該包有一個過程 pro_input
            function fun_test(t_name varchar2) return number;  --聲明該包有一個函數 fun_test
          end;

          --包體案例:
          create package body pac_test
          is
            procedure pro_input(t_name in varchar2,t_sal in number)
            is
            begin
              update emp2 set sal = t_sal where name=t_name;
            end;
           
            function fun_test(t_name varchar2)
            return number is yearSal number(7,2);
            begin
              select sal*12 into yearSal from emp2 where name = t_name;
              return yearSal;
            end;
          end ;
          --調用包中的函數或過程
          call pac_test.pro_input('summer',1000);
          call pac_test.fun_test
          select pac_test.fun_test('simple') from dual;

          --案例:
          select * from emp2;
          --下面以輸入員工工號,顯示雇員姓名、工資、個人所得稅
          --稅率(0.03)。
          declare
            c_tax_rate number(3,2):=0.03;  --常量,稅率
            --v_name varchar2(30);
            v_name emp2.name%type;
            --v_sal number(8,2);
            v_sal emp2.sal%type;
            v_tax_sal number(8,2);
          begin
            --執行
            select name,sal into v_name,v_sal from emp2 where name = &na;
            --計算所得稅
            v_tax_sal:=v_sal*c_tax_rate;
            --輸出
            dbms_output.put_line('姓名:'||v_name||' 工資'||v_sal||' 交稅'||v_tax_sal); 
          end;

          --pl/sql記錄實例
          declare
            --定義一個pl/sql記錄類型 emp_record_type ,類型包含2個數據,t_name,t_sal
            type emp_record_type is record(t_name emp2.name%type,t_sal emp2.sal%type);
            --定義一個 record_test 變量,類型是 emp_record_type
            record_test emp_record_type;
          begin
            select name,sal into record_test from emp2 where name = 'simple';
            dbms_output.put_line('員工工資:'||record_test.t_sal);
          end;

          --pl/sql表實例
          declare
            --定義了一個pl/sql表類型 emp_table_type 該類型是用于存放 emp.name%type元素類型 的數組
            -- index by binary_integer 下標是整數
            type emp_table_type is table of emp2.name%type index by binary_integer;
            --定義一個 table_test 變量
            table_test emp_table_type;
          begin
            --table_test(0)下標為0的元素
            select name into table_test(0) from emp2 where name='summer';
            dbms_output.put_line('員工:'||table_test(0));
          end;


          --案例
          --顯示該部門的所有員工和工資
          declare
            --定義游標類型 emp_cursor
            type emp_cursor is ref cursor;
            --定義一個游標變量
            cursor_test emp_cursor;
            --定義變量
            v_name emp2.name%type;
            v_sal emp2.sal%type;
          begin
            --執行
            --把cursor_test 和一個select結合
            open cursor_test for
            select name,sal from emp2;
            --循環取出
            loop
              --fetch取出 游標 給 v_name,v_sal
              fetch cursor_test into v_name,v_sal;
              --判斷工資
              if v_sal<1000 then
                update emp2 set sal = v_sal+1000 where sal=v_sal;
              end if;
              --判斷cursor_test是否為空
              exit when cursor_test%notfound;
              dbms_output.put_line('姓名:'||v_name||' 薪水:'||v_sal);
            end loop;
          end;

          select * from emp2;


          --《分頁》案例:
          --建表
          drop table book;
          create table book(
            bookId number(5),
            bookName varchar2(50),
            publishHouse varchar2(50)
          );
          --編寫過程
          create or replace procedure pro_pagination( t_bookId in number,
                                      t_bookName in varchar2,
                                      t_publishHouse in varchar2)
          is
          begin
            insert into book values(t_bookId,t_bookName,t_publishHouse);
          end;
          --在java中調用
          --select * from book;
          --insert into book values(11,'流星','蝴蝶');
          --commit;
          --有輸入和輸出的存儲過程
          create or replace procedure pro_pagination2( i_id in number,
                                                       o_name out varchar2,
                                                       o_publishHouse out varchar2
                                                       )
          is
          begin
            select bookName,publishHouse into o_name,o_publishHouse from book where bookId = i_id;
          end;
          --Test!
          declare
            err book.bookname%type;
            err2 book.publishhouse%type;
          begin
            pro_pagination2(10,err,err2);
            dbms_output.put_line(err||' '||err2);
          end;
          --返回結果集的過程
          --1、創建一個包
          create or replace package testpackage
          as
            type cursor_test is ref cursor;
          end testpackage;
          --2、建立存儲過程
          create or replace procedure pro_pagination3(
                                                      o_cursor out testpackage.cursor_test)
          is
          begin
            open o_cursor for
            select * from book;
          end;
          --3、如何在java中調用

          --Test!
          declare
            err testpackage.cursor;
          begin
            pro_pagination2(10,err);
            dbms_output.put_line(err);
          end;


          <Oracle的分頁>

           

          select t1.*,rownum rn from (select * from emp) t1;

          select t1.*,rownum rn from (select * from emp) t1 where rownum<=10;
          --在分頁的時候,可以把下面的sql語句當做一個模板使用
          select * from (select t1.*,rownum rn from (select * from emp) t1 where rownum<=10) where rn>=6;

          --開發一個包
          --1、創建一個包
          create or replace package testpackage
          as
            type cursor_test is ref cursor;
          end testpackage;
          --開始編寫分頁的過程
          create or replace procedure fenye(tableName in varchar2,
                                            pageSize in number, --每頁顯示記錄數
                                            pageNow in number,
                                            myRows out number,--總記錄數
                                            myPageCount out number,--總頁數
                                            p_cursor out testpackage.cursor_test)
          is
            --定義sql語句 字符串
            v_sql varchar2(1000);
            --定義2個整數
            v_begin number:=(pageNow-1)*pageSize+1;
            v_end number:=pageNow*pageSize;
          begin
            v_sql:='select * from (select t1.*,rownum rn from (select * from '||tableName||' order by sal) t1 where rownum<='||v_end||') where rn>='||v_begin||'';
            --把游標和sql關聯
            open p_cursor for v_sql;
            --計算myRows和myPageCount
            --組織一個sql
            v_sql:='select count(*) from '||tableName||'';
            --執行sql,并把返回的值,賦給myRows
            execute immediate v_sql into myRows;
            --計算myPageCount
            if mod(myRows,pageSize)=0 then
              myPageCount:=myRows/pageSize;
            else
              myPageCount:=myRows/pageSize+1;
            end if;
            --關閉游標
            --close p_cursor;
          end;
          --使用java測試

          具體寫發 http://qindingsky.blog.163.com/blog/static/3122336200977111045401/

          posted @ 2012-08-12 20:41 abin 閱讀(644) | 評論 (0)編輯 收藏

          根據網上的資料做些整理

          Java NIO API詳解

          http://www.aygfsteel.com/19851985lili/articles/93524.html

          這篇文章對nio的api講解比較全,可以幫助在宏觀上把握nio。

          BIO 方式使得整個處理過程和連接是綁定的,只要連接建立,無論客戶端是否有消息發送,都要進行等待處理,一定程度上浪費了服務器端的硬件資源,因此就有了NIO 方式。Java 對于 NIO 方式的支持是通過 Channel和 Selector 方式來實現,采用的方法為向 Channel注冊感興趣的事件,然后通過 Selector 來獲取到發生了事件的 key,如發生了相應的事件,則進行相應的處理,否則則不做任何處理,是典型的Reactor 模式,按照這樣的方式,就不用像 BIO 方式一樣,即使在沒有消息的情況下也需要占據一個線程來阻塞讀取消息,從而提升服務器的使用效率, 為實現 TCP/IP+NIO 方式的系統間通訊, Java 提供了 SocketChannel和 ServerSocketChannel兩個關鍵的類,網絡 IO 的操作則改為通過ByteBuffer 來實現,具體的基于 java實現TCP/IP+NIO 方式的通訊的方法如下所示。

          服務器端:

          package com.flyoung;

          import java.io.IOException;
          import java.net.InetSocketAddress;
          import java.net.ServerSocket;
          import java.nio.ByteBuffer;
          import java.nio.channels.SelectionKey;
          import java.nio.channels.Selector;
          import java.nio.channels.ServerSocketChannel;
          import java.util.Iterator;
          import java.util.Set;
          import java.nio.channels.SocketChannel;

          public class NIOServer {
              
          /*標志數字*/
              
          private static int flag = 0;
              
          /*定義緩沖區大小*/
              
          private static int block = 4096;
              
          /*接收緩沖區*/
              
          private static ByteBuffer receiveBuffer = ByteBuffer.allocate(block);
              
          /*發送緩沖區*/
              
          private static ByteBuffer sendBuffer = ByteBuffer.allocate(block);
              
          /*定義Selector*/
              
          private Selector selector;
              
              
          public NIOServer(int port) throws IOException{
                  
          //打開服務器套接字通道
                  ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                  
          //服務器配置為非阻塞
                  serverSocketChannel.configureBlocking(false);
                  
          //檢索與此服務器套接字通道關聯的套接字
                  ServerSocket serverSocket = serverSocketChannel.socket();
                  
          //進行服務的綁定
                  serverSocket.bind(new InetSocketAddress(port));
                  
          //通過open()方法找到Selector
                  selector = Selector.open();
                  
          //注冊到selector
                  serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                  System.out.println(
          "Server Start -----8888:");
              }
              
          //監聽
              public void listen() throws IOException{
                  
          while(true){
                      
          //監控所有注冊的 channel ,當其中有注冊的 IO 操作可以進行時,該函數返回,并將對應的 SelectionKey 加入 selected-key set
                      selector.select();
                      
          //Selected-key set 代表了所有通過 select() 方法監測到可以進行 IO 操作的 channel ,這個集合可以通過 selectedKeys() 拿到
                      Set<SelectionKey> selectionKeys = selector.selectedKeys();
                      Iterator
          <SelectionKey> iterator = selectionKeys.iterator();
                      
          while(iterator.hasNext()){
                          SelectionKey selectionKey 
          = iterator.next();
                          handleKey(selectionKey);
                          iterator.remove();
                      }
                  }
                  
              }
              
          //處理請求
              public void handleKey(SelectionKey selectionKey) throws IOException{
                  
          //接受請求
                  ServerSocketChannel serverSocketChannel = null;
                  SocketChannel socketChannel 
          = null;
                  String receiveText;
                  String sendText;
                  
          int count;
                  
          //測試此鍵的通道是否準備好接受新的套接字連接
                  if(selectionKey.isAcceptable()){
                      
          //返回創建此鍵的通道
                      serverSocketChannel = (ServerSocketChannel)selectionKey.channel();
                      
          //接受客戶端建立連接的請求,并返回 SocketChannel 對象
                      socketChannel = serverSocketChannel.accept();
                      
          //配置為非阻塞
                      socketChannel.configureBlocking(false);
                      
          //注冊到selector
                      socketChannel.register(selector, SelectionKey.OP_READ);
                  }
          else if(selectionKey.isReadable()){
                      
          //返回為之創建此鍵的通道
                      socketChannel = (SocketChannel)selectionKey.channel();
                      
          //將緩沖區清空,以備下次讀取
                      receiveBuffer.clear();
                      
          //將發送來的數據讀取到緩沖區
                      
                      count 
          = socketChannel.read(receiveBuffer);
                  
                      
                      
          if(count>0){
                          receiveText 
          = new String(receiveBuffer.array(),0,count);
                          System.out.println(
          "服務器端接受到的數據---"+receiveText);
                          socketChannel.register(selector, SelectionKey.OP_WRITE);
                      }
                  }
          else if (selectionKey.isWritable()) {  
                      
          //將緩沖區清空以備下次寫入  
                      sendBuffer.clear();  
                      
          // 返回為之創建此鍵的通道。  
                      socketChannel = (SocketChannel) selectionKey.channel();  
                      sendText
          ="message from server--" + flag++;  
                      
          //向緩沖區中輸入數據  
                      sendBuffer.put(sendText.getBytes());  
                       
          //將緩沖區各標志復位,因為向里面put了數據標志被改變要想從中讀取數據發向服務器,就要復位  
                      sendBuffer.flip();  
                      
          //輸出到通道  
                      socketChannel.write(sendBuffer);  
                      System.out.println(
          "服務器端向客戶端發送數據--:"+sendText);  
                      socketChannel.register(selector, SelectionKey.OP_READ);  
                  }  
                  
              }
              
          public static void main(String[] args) throws IOException {
                  
          int port = 8888
                  NIOServer server 
          = new NIOServer(port);
                  server.listen();
              }

          }

           

          客戶端

          package com.flyoung;

          import java.io.IOException;
          import java.net.InetSocketAddress;
          import java.nio.ByteBuffer;
          import java.nio.channels.SelectionKey;
          import java.nio.channels.Selector;
          import java.nio.channels.SocketChannel;
          import java.util.Set;

          public class NIOClient {
              
          /*標識數字*/  
              
          private static int flag = 0;  
              
          /*緩沖區大小*/  
              
          private static int BLOCK = 4096;  
              
          /*接受數據緩沖區*/  
              
          private static ByteBuffer sendBuffer = ByteBuffer.allocate(BLOCK);  
              
          /*發送數據緩沖區*/  
              
          private static ByteBuffer receiveBuffer = ByteBuffer.allocate(BLOCK);  
              
          /*服務器端地址*/  
              
          private final static InetSocketAddress SERVER_ADDRESS = new InetSocketAddress(  
                      
          "localhost"8888);  
            
              
          public static void main(String[] args) throws IOException {  
                  
          // 打開socket通道  
                  SocketChannel clientChannel = SocketChannel.open();  
                  
          // 設置為非阻塞方式  
                  clientChannel.configureBlocking(false);  
                  
          // 打開選擇器  
                  Selector selector = Selector.open();  
                  
          // 注冊連接服務端socket動作  
                  clientChannel.register(selector, SelectionKey.OP_CONNECT);  
                  
          // 連接  
                  clientChannel.connect(SERVER_ADDRESS);  
              
                  SocketChannel socketChannel;
                  Set
          <SelectionKey> selectionKeys;    
                  String receiveText;  
                  String sendText;  
                  
          int count=0;  
            
                  
          while (true) {  
                      
          //選擇一組鍵,其相應的通道已為 I/O 操作準備就緒。  
                      
          //監控所有注冊的 channel ,當其中有注冊的 IO 操作可以進行時,該函數返回,并將對應的 SelectionKey 加入 selected-key set 
                      selector.select();  
                      
          //返回此選擇器的已選擇鍵集。  
                      selectionKeys = selector.selectedKeys();  
                      
          //System.out.println(selectionKeys.size());  
                      for(SelectionKey selectionKey:selectionKeys){ 
                          
          //判斷是否為建立連接的事件
                          if (selectionKey.isConnectable()) {  
                              System.out.println(
          "client connect");  
                              socketChannel 
          = (SocketChannel) selectionKey.channel();  //
                              
          // 判斷此通道上是否正在進行連接操作。  
                              
          // 完成套接字通道的連接過程。  
                              if (socketChannel.isConnectionPending()) { 
                                  
          //完成連接的建立(TCP三次握手)
                                  socketChannel.finishConnect();  
                                  System.out.println(
          "完成連接!");  
                                  sendBuffer.clear();  
                                  sendBuffer.put(
          "Hello,Server".getBytes());  
                                  sendBuffer.flip();  
                                  socketChannel.write(sendBuffer);  
                              }  
                              socketChannel.register(selector, SelectionKey.OP_READ);  
                          } 
          else if (selectionKey.isReadable()) {  
                              socketChannel 
          = (SocketChannel) selectionKey.channel();  
                              
          //將緩沖區清空以備下次讀取  
                              receiveBuffer.clear();  
                              
          //讀取服務器發送來的數據到緩沖區中  
                              count=socketChannel.read(receiveBuffer);  
                              
          if(count>0){  
                                  receiveText 
          = new String( receiveBuffer.array(),0,count);  
                                  System.out.println(
          "客戶端接受服務器端數據--:"+receiveText);  
                                  socketChannel.register(selector, SelectionKey.OP_WRITE);  
                              }  
            
                          } 
          else if (selectionKey.isWritable()) {  
                              sendBuffer.clear();  
                              socketChannel 
          = (SocketChannel) selectionKey.channel();  
                              sendText 
          = "message from client--" + (flag++);  
                              sendBuffer.put(sendText.getBytes());  
                               
          //將緩沖區各標志復位,因為向里面put了數據標志被改變要想從中讀取數據發向服務器,就要復位  
                              sendBuffer.flip();  
                              socketChannel.write(sendBuffer);  
                              System.out.println(
          "客戶端向服務器端發送數據--:"+sendText);  
                              socketChannel.register(selector, SelectionKey.OP_READ);  
                          }  
                      }  
                      selectionKeys.clear();  
                  }  
              }  
          }




          posted @ 2012-08-09 12:59 abin 閱讀(652) | 評論 (0)編輯 收藏

          public boolean equals(Object other) {
            if ((this == other))
             return true;
            if ((other == null))
             return false;
            if (!(other instanceof BtsfSysAlipayNotifyJournal))
             return false;
            BtsfSysAlipayNotifyJournal castOther = (BtsfSysAlipayNotifyJournal) other;

            return ((this.getId() == castOther.getId()) || (this.getId() != null
              && castOther.getId() != null && this.getId().equals(
              castOther.getId())))
              && ((this.getPartner() == castOther.getPartner()) || (this
                .getPartner() != null
                && castOther.getPartner() != null && this.getPartner()
                .equals(castOther.getPartner())))
              && ((this.getDiscount() == castOther.getDiscount()) || (this
                .getDiscount() != null
                && castOther.getDiscount() != null && this
                .getDiscount().equals(castOther.getDiscount())))
              && ((this.getPaymentType() == castOther.getPaymentType()) || (this
                .getPaymentType() != null
                && castOther.getPaymentType() != null && this
                .getPaymentType().equals(castOther.getPaymentType())))
              && ((this.getSubject() == castOther.getSubject()) || (this
                .getSubject() != null
                && castOther.getSubject() != null && this.getSubject()
                .equals(castOther.getSubject())))
              && ((this.getTradeNo() == castOther.getTradeNo()) || (this
                .getTradeNo() != null
                && castOther.getTradeNo() != null && this.getTradeNo()
                .equals(castOther.getTradeNo())))
              && ((this.getBuyerEmail() == castOther.getBuyerEmail()) || (this
                .getBuyerEmail() != null
                && castOther.getBuyerEmail() != null && this
                .getBuyerEmail().equals(castOther.getBuyerEmail())))
              && ((this.getGmtCreate() == castOther.getGmtCreate()) || (this
                .getGmtCreate() != null
                && castOther.getGmtCreate() != null && this
                .getGmtCreate().equals(castOther.getGmtCreate())))
              && ((this.getQuantity() == castOther.getQuantity()) || (this
                .getQuantity() != null
                && castOther.getQuantity() != null && this
                .getQuantity().equals(castOther.getQuantity())))
              && ((this.getOutTradeNo() == castOther.getOutTradeNo()) || (this
                .getOutTradeNo() != null
                && castOther.getOutTradeNo() != null && this
                .getOutTradeNo().equals(castOther.getOutTradeNo())))
              && ((this.getSellerId() == castOther.getSellerId()) || (this
                .getSellerId() != null
                && castOther.getSellerId() != null && this
                .getSellerId().equals(castOther.getSellerId())))
              && ((this.getTradeStatus() == castOther.getTradeStatus()) || (this
                .getTradeStatus() != null
                && castOther.getTradeStatus() != null && this
                .getTradeStatus().equals(castOther.getTradeStatus())))
              && ((this.getIsTotalFeeAdjust() == castOther
                .getIsTotalFeeAdjust()) || (this.getIsTotalFeeAdjust() != null
                && castOther.getIsTotalFeeAdjust() != null && this
                .getIsTotalFeeAdjust().equals(
                  castOther.getIsTotalFeeAdjust())))
              && ((this.getTotalFee() == castOther.getTotalFee()) || (this
                .getTotalFee() != null
                && castOther.getTotalFee() != null && this
                .getTotalFee().equals(castOther.getTotalFee())))
              && ((this.getGmtPayment() == castOther.getGmtPayment()) || (this
                .getGmtPayment() != null
                && castOther.getGmtPayment() != null && this
                .getGmtPayment().equals(castOther.getGmtPayment())))
              && ((this.getSellerEmail() == castOther.getSellerEmail()) || (this
                .getSellerEmail() != null
                && castOther.getSellerEmail() != null && this
                .getSellerEmail().equals(castOther.getSellerEmail())))
              && ((this.getGmtClose() == castOther.getGmtClose()) || (this
                .getGmtClose() != null
                && castOther.getGmtClose() != null && this
                .getGmtClose().equals(castOther.getGmtClose())))
              && ((this.getPrice() == castOther.getPrice()) || (this
                .getPrice() != null
                && castOther.getPrice() != null && this.getPrice()
                .equals(castOther.getPrice())))
              && ((this.getBuyerId() == castOther.getBuyerId()) || (this
                .getBuyerId() != null
                && castOther.getBuyerId() != null && this.getBuyerId()
                .equals(castOther.getBuyerId())))
              && ((this.getUseCoupon() == castOther.getUseCoupon()) || (this
                .getUseCoupon() != null
                && castOther.getUseCoupon() != null && this
                .getUseCoupon().equals(castOther.getUseCoupon())))
              && ((this.getCreateTime() == castOther.getCreateTime()) || (this
                .getCreateTime() != null
                && castOther.getCreateTime() != null && this
                .getCreateTime().equals(castOther.getCreateTime())))
              && ((this.getLastUpdateTime() == castOther.getLastUpdateTime()) || (this
                .getLastUpdateTime() != null
                && castOther.getLastUpdateTime() != null && this
                .getLastUpdateTime().equals(
                  castOther.getLastUpdateTime())))
              && ((this.getPaymentMethod() == castOther.getPaymentMethod()) || (this
                .getPaymentMethod() != null
                && castOther.getPaymentMethod() != null && this
                .getPaymentMethod()
                .equals(castOther.getPaymentMethod())));
           }

           public int hashCode() {
            int result = 17;

            result = 37 * result + (getId() == null ? 0 : this.getId().hashCode());
            result = 37 * result
              + (getPartner() == null ? 0 : this.getPartner().hashCode());
            result = 37 * result
              + (getDiscount() == null ? 0 : this.getDiscount().hashCode());
            result = 37
              * result
              + (getPaymentType() == null ? 0 : this.getPaymentType()
                .hashCode());
            result = 37 * result
              + (getSubject() == null ? 0 : this.getSubject().hashCode());
            result = 37 * result
              + (getTradeNo() == null ? 0 : this.getTradeNo().hashCode());
            result = 37
              * result
              + (getBuyerEmail() == null ? 0 : this.getBuyerEmail()
                .hashCode());
            result = 37 * result
              + (getGmtCreate() == null ? 0 : this.getGmtCreate().hashCode());
            result = 37 * result
              + (getQuantity() == null ? 0 : this.getQuantity().hashCode());
            result = 37
              * result
              + (getOutTradeNo() == null ? 0 : this.getOutTradeNo()
                .hashCode());
            result = 37 * result
              + (getSellerId() == null ? 0 : this.getSellerId().hashCode());
            result = 37
              * result
              + (getTradeStatus() == null ? 0 : this.getTradeStatus()
                .hashCode());
            result = 37
              * result
              + (getIsTotalFeeAdjust() == null ? 0 : this
                .getIsTotalFeeAdjust().hashCode());
            result = 37 * result
              + (getTotalFee() == null ? 0 : this.getTotalFee().hashCode());
            result = 37
              * result
              + (getGmtPayment() == null ? 0 : this.getGmtPayment()
                .hashCode());
            result = 37
              * result
              + (getSellerEmail() == null ? 0 : this.getSellerEmail()
                .hashCode());
            result = 37 * result
              + (getGmtClose() == null ? 0 : this.getGmtClose().hashCode());
            result = 37 * result
              + (getPrice() == null ? 0 : this.getPrice().hashCode());
            result = 37 * result
              + (getBuyerId() == null ? 0 : this.getBuyerId().hashCode());
            result = 37 * result
              + (getUseCoupon() == null ? 0 : this.getUseCoupon().hashCode());
            result = 37
              * result
              + (getCreateTime() == null ? 0 : this.getCreateTime()
                .hashCode());
            result = 37
              * result
              + (getLastUpdateTime() == null ? 0 : this.getLastUpdateTime()
                .hashCode());
            result = 37
              * result
              + (getPaymentMethod() == null ? 0 : this.getPaymentMethod()
                .hashCode());
            return result;
           }

          posted @ 2012-08-08 16:30 abin 閱讀(419) | 評論 (0)編輯 收藏

          1. Schema

          MySQL: 需事先設計
          Memcached: 無需設計
          Redis: 小型系統可以不用,但是如果要合理的規劃及使用Redis,需要事先進行類似如下一些規劃

          數據項: value保存的內容是什么,如用戶資料Redis數據類型: 如String, List數據大小: 如100字節記錄數: 如100萬條(決定是否需要拆分)……

          上面的規劃就是一種schema,為什么Redis在大型項目需要事先設計schema?因為Redis服務器有容量限制,數據容量不能超出物理內存大小,同時考慮到業務數據的可擴充性,記錄數會持續增多、單條記錄的內容也都會增長,因此需要提前規劃好容量,數據架構師就是通過schema來判斷當前業務的Redis是否需要“分庫分表”以滿足可擴展需求。

          2. 容量及帶寬規劃

          容量規劃
          MySQL: < 硬盤大小
          Memcached: < RAM
          Redis: < RAM

          帶寬規劃
          由于Redis比MySQL快10倍以上,因此帶寬也是需要事先規劃,避免帶寬跑滿而出現瓶頸。

          3. 性能規劃(QPS)

          當系統讀寫出現瓶頸,通常如何解決?
          MySQL
          寫: 拆分到多服務器
          讀: (1) 拆分 (2) 寫少也可以通過增加Slave來解決

          Memcached
          讀寫: 都通過hash拆分到更多節點。

          Redis:
          寫:拆分
          讀: (1) 拆分 (2) 寫少也可以通過增加Slave來解決

          4. 可擴展性

          MySQL: 分庫分表
          Memcached: hash分布
          Redis:也可以分庫,也可以hash分布

          小結

          通過以上分析,Redis在很多方面同時具備MySQL及Memcached使用特征,在某些方面則更像MySQL。
          由于Redis數據不能超過內存大小,一方面需要進行事先容量規劃,保證容量足夠;另外一方面設計上需要防止數據規模無限制增加,進而導致Redis不可擴展。
          Redis需要象MySQL一樣預先設計好拆分方案。

          posted @ 2012-08-03 13:06 abin 閱讀(5419) | 評論 (0)編輯 收藏

          package org.abin.lee.activemq;

          import javax.jms.Connection;
          import javax.jms.ConnectionFactory;
          import javax.jms.DeliveryMode;
          import javax.jms.Destination;
          import javax.jms.MapMessage;
          import javax.jms.MessageProducer;
          import javax.jms.Session;

          import org.apache.activemq.ActiveMQConnection;
          import org.apache.activemq.ActiveMQConnectionFactory;

          public class MapSender {

           private static final int SEND_NUMBER = 5;

           public static void main(String[] args) {
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
              ActiveMQConnection.DEFAULT_USER,
              ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616");
            Connection connection = null;
            Session session;
            Destination destination = null;
            MessageProducer messageProducer;
            try {
             connection=connectionFactory.createConnection();
             connection.start();
             session=connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
             destination=session.createQueue("FirstQueue");
             messageProducer=session.createProducer(destination);
             messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
             
             MapMessage map=session.createMapMessage();
             map.setBoolean("flag", true);
             map.setDouble("dou", 1.01);
             map.setInt("zx", 88);
             map.setString("zifu", "zzzzzz");
             messageProducer.send(map);
             session.commit();
            } catch (Exception e) {
             e.printStackTrace();
            }
           }


          }






          package org.abin.lee.activemq;

          import javax.jms.Connection;
          import javax.jms.ConnectionFactory;
          import javax.jms.Destination;
          import javax.jms.MapMessage;
          import javax.jms.MessageConsumer;
          import javax.jms.Session;

          import org.apache.activemq.ActiveMQConnection;
          import org.apache.activemq.ActiveMQConnectionFactory;

          public class MapReceiver {public static void main(String[] args) {
           ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
             ActiveMQConnection.DEFAULT_USER,
             ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616");
           Connection connection = null;
           Session session;
           Destination destination;
           MessageConsumer consumer;
           try {
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(Boolean.FALSE,
              Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue("FirstQueue");
            consumer = session.createConsumer(destination);
            while(true){
             MapMessage map=(MapMessage)consumer.receive(500000);
             if (null != map) {
              boolean flag=map.getBoolean("falg");
              System.out.println("AcitveMQ 接收到的消息  flag="+flag);
              double dou=map.getDouble("dou");
              System.out.println("AcitveMQ 接收到的消息  dou="+dou);
              int zx=map.getInt("zx");
              System.out.println("AcitveMQ 接收到的消息  zx="+zx);
              String zifu=map.getString("zifu");
              System.out.println("AcitveMQ 接收到的消息  zifu="+zifu);
             }else
              break;

            }
            
             

           } catch (Exception e) {
            e.printStackTrace();
           }

          }
          }

          posted @ 2012-08-02 16:35 abin 閱讀(876) | 評論 (0)編輯 收藏

           

          問題解決2——加入等待與喚醒


          package edu.sjtu.erplab.thread;

          class Info{
              private String name="name";
              private String content="content";
              private boolean flag=true;
              public  synchronized void set(String name,String content)
              {
                  if(!flag)//標志位為false,不可以生產
                  {
                      try {
                          super.wait();
                      } catch (InterruptedException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }
                  }
                  this.setName(name);
                  try {
                      Thread.sleep(30);
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
                  this.setContent(content);
                  flag=false;//修改標志位為false,表示生產者已經完成資源,消費者可以消費。
                  super.notify();//喚醒消費者進程
              }
             
              public synchronized void get()
              {
                  if(flag)
                  {
                      try {
                          super.wait();
                      } catch (InterruptedException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }
                  }
                  try {
                      Thread.sleep(30);
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
                  System.out.println(this.getName()+":-->"+this.getContent());
                  flag=true;//修改標志位為true,表示消費者拿走資源,生產者可以生產。
                  super.notify();//喚醒生產者進程。
              }
             
             
              public String getName() {
                  return name;
              }
              public void setName(String name) {
                  this.name = name;
              }
              public String getContent() {
                  return content;
              }
              public void setContent(String content) {
                  this.content = content;
              }
             
          }

          class Producer implements Runnable{
              private Info info=null;
              public Producer(Info info)
              {
                  this.info=info;
              }
             

              @Override
              public void run() {
                  boolean flag=false;
                  for(int i=0;i<10;i++)
                      if(flag)
                      {
                          this.info.set("name+"+i, "content+"+i);
                          flag=false;
                      }
                      else
                      {
                          this.info.set("name-"+i, "content-"+i);
                          flag=true;
                      }
              }
          }

          class Consumer implements Runnable{
              private Info info=null;
              public Consumer(Info info)
              {
                  this.info=info;
              }
              @Override
              public void run() {
                  for(int i=0;i<10;i++)
                  {
                      try {
                          Thread.sleep(10);
                      } catch (InterruptedException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }
                      this.info.get();
                  }
                 
              }
          }

          public class ThreadDeadLock {
              public static void main(String args[])
              {
                  Info info=new Info();
                  Producer pro=new Producer(info);
                  Consumer con=new Consumer(info);
                  new Thread(pro).start();
                  new Thread(con).start();
              }
             
          }




          http://www.cnblogs.com/xwdreamer/archive/2011/11/20/2296931.html#2397397

          posted @ 2012-08-02 15:30 abin 閱讀(470) | 評論 (0)編輯 收藏

          企業中各項目中相互協作的時候可能用得到消息通知機制。比如有東西更新了,可以通知做索引。

          在 Java 里有 JMS 的多個實現。其中 apache 下的 ActiveMQ 就是不錯的選擇。ActiveMQ 是Apache出品,最流行的,能力強勁的開源消息總線。ActiveMQ 是一個完全支持JMS1.1和J2EE 1.4規范的 JMS Provider實現。這里示例下使用 ActiveMQ

          用 ActiveMQ 最好還是了解下 JMS

          JMS 公共 點對點域 發布/訂閱域
          ConnectionFactory QueueConnectionFactory TopicConnectionFactory
          Connection QueueConnection TopicConnection
          Destination Queue Topic
          Session QueueSession TopicSession
          MessageProducer QueueSender TopicPublisher
          MessageConsumer QueueReceiver TopicSubscriber

          JMS 定義了兩種方式:Quere(點對點);Topic(發布/訂閱)。

          ConnectionFactory 是連接工廠,負責創建Connection。

          Connection 負責創建 Session。

          Session 創建 MessageProducer(用來發消息) 和 MessageConsumer(用來接收消息)。

          Destination 是消息的目的地。

          詳細的可以網上找些 JMS 規范(有中文版)。

          下載 apache-activemq-5.3.0。http://activemq.apache.org/download.html ,解壓,然后雙擊 bin/activemq.bat。運行后,可以在 http://localhost:8161/admin 觀察。也有 demo, http://localhost:8161/demo 。把 activemq-all-5.3.0.jar 加入 classpath。

          Jms 發送 代碼:

          public static void main(String[] args) throws Exception {   
              ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();   
            
              Connection connection = connectionFactory.createConnection();   
              connection.start();   
            
              Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);   
              Destination destination = session.createQueue("my-queue");   
            
              MessageProducer producer = session.createProducer(destination);   
              for(int i=0; i<3; i++) {   
                  MapMessage message = session.createMapMessage();   
                  message.setLong("count", new Date().getTime());   
                  Thread.sleep(1000);   
                  //通過消息生產者發出消息   
                  producer.send(message);   
              }   
              session.commit();   
              session.close();   
              connection.close();   
          }



          Jms 接收代碼:


          public static void main(String[] args) throws Exception {   
              ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();   
            
              Connection connection = connectionFactory.createConnection();   
              connection.start();   
            
              final Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);   
              Destination destination = session.createQueue("my-queue");   
            
              MessageConsumer consumer = session.createConsumer(destination);   
              int i=0;   
              while(i<3) {   
                  i++;   
                  MapMessage message = (MapMessage) consumer.receive();   
                  session.commit();   
            
                  //TODO something....   
                  System.out.println("收到消息:" + new Date(message.getLong("count")));   
              }   
            
              session.close();   
              connection.close();   
          }



          JMS五種消息的發送/接收的例子

          轉自:http://chenjumin.javaeye.com/blog/687124  

          1、消息發送

          //連接工廠  
          ConnectionFactory connFactory = new ActiveMQConnectionFactory(  
                  ActiveMQConnection.DEFAULT_USER,  
                  ActiveMQConnection.DEFAULT_PASSWORD,  
                  "tcp://localhost:61616");  
           
          //連接到JMS提供者  
          Connection conn = connFactory.createConnection();  
          conn.start();  
           
          //事務性會話,自動確認消息  
          Session session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);  
           
          //消息的目的地  
          Destination destination = session.createQueue("queue.hello");  
           
          //消息生產者  
          MessageProducer producer = session.createProducer(destination);  
          producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); //不持久化  
           
           
          //文本消息  
          TextMessage textMessage = session.createTextMessage("文本消息");  
          producer.send(textMessage);  
           
          //鍵值對消息  
          MapMessage mapMessage = session.createMapMessage();  
          mapMessage.setLong("age", new Long(32));  
          mapMessage.setDouble("sarray", new Double(5867.15));  
          mapMessage.setString("username", "鍵值對消息");  
          producer.send(mapMessage);  
           
          //流消息  
          StreamMessage streamMessage = session.createStreamMessage();  
          streamMessage.writeString("streamMessage流消息");  
          streamMessage.writeLong(55);  
          producer.send(streamMessage);  
           
          //字節消息  
          String s = "BytesMessage字節消息";  
          BytesMessage bytesMessage = session.createBytesMessage();  
          bytesMessage.writeBytes(s.getBytes());  
          producer.send(bytesMessage);  
           
          //對象消息  
          User user = new User("cjm", "對象消息"); //User對象必須實現Serializable接口  
          ObjectMessage objectMessage = session.createObjectMessage();  
          objectMessage.setObject(user);  
          producer.send(objectMessage);  
           
           
          session.commit(); //在事務性會話中,只有commit之后,消息才會真正到達目的地  
          producer.close();  
          session.close();  
          conn.close(); 



          2、消息接收:通過消息監聽器的方式接收消息


          public class Receiver implements MessageListener{  
              private boolean stop = false;  
                
              public void execute() throws Exception {  
                  //連接工廠  
                  ConnectionFactory connFactory = new ActiveMQConnectionFactory(  
                          ActiveMQConnection.DEFAULT_USER,  
                          ActiveMQConnection.DEFAULT_PASSWORD,  
                          "tcp://localhost:61616");  
                    
                  //連接到JMS提供者  
                  Connection conn = connFactory.createConnection();  
                  conn.start();  
                    
                  //事務性會話,自動確認消息  
                  Session session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);  
                    
                  //消息的來源地  
                  Destination destination = session.createQueue("queue.hello");  
                    
                  //消息消費者  
                  MessageConsumer consumer = session.createConsumer(destination);  
                  consumer.setMessageListener(this);  
                    
                  //等待接收消息  
                  while(!stop){  
                      Thread.sleep(5000);  
                  }  
                    
                  session.commit();  
                    
                  consumer.close();  
                  session.close();  
                  conn.close();  
              }  
           
              public void onMessage(Message m) {  
                  try{  
                      if(m instanceof TextMessage){ //接收文本消息  
                          TextMessage message = (TextMessage)m;  
                          System.out.println(message.getText());  
                      }else if(m instanceof MapMessage){ //接收鍵值對消息  
                          MapMessage message = (MapMessage)m;  
                          System.out.println(message.getLong("age"));  
                          System.out.println(message.getDouble("sarray"));  
                          System.out.println(message.getString("username"));  
                      }else if(m instanceof StreamMessage){ //接收流消息  
                          StreamMessage message = (StreamMessage)m;  
                          System.out.println(message.readString());  
                          System.out.println(message.readLong());  
                      }else if(m instanceof BytesMessage){ //接收字節消息  
                          byte[] b = new byte[1024];  
                          int len = -1;  
                          BytesMessage message = (BytesMessage)m;  
                          while((len=message.readBytes(b))!=-1){  
                              System.out.println(new String(b, 0, len));  
                          }  
                      }else if(m instanceof ObjectMessage){ //接收對象消息  
                          ObjectMessage message = (ObjectMessage)m;  
                          User user = (User)message.getObject();  
                          System.out.println(user.getUsername() + " _ " + user.getPassword());  
                      }else{  
                          System.out.println(m);  
                      }  
                        
                      stop = true;  
                  }catch(JMSException e){  
                      stop = true;  
                      e.printStackTrace();  
                  }  
              }  





          http://blog.csdn.net/caihaijiang/article/details/5903296
          posted @ 2012-08-02 14:59 abin 閱讀(1765) | 評論 (0)編輯 收藏

          廢話少說,首先建表:
          -- Create table
          create table ABIN4
          (
            ID1         NUMBER,
            NAME1       NVARCHAR2(100),
            CREATETIME1 DATE
          )
          tablespace SYSTEM
            pctfree 10
            pctused 40
            initrans 1
            maxtrans 255
            storage
            (
              initial 64K
              next 1M
              minextents 1
              maxextents unlimited
            );



          -- Create table
          create table ABIN5
          (
            ID1         NUMBER,
            NAME1       NVARCHAR2(100),
            CREATETIME1 DATE
          )
          tablespace SYSTEM
            pctfree 10
            pctused 40
            initrans 1
            maxtrans 255
            storage
            (
              initial 64K
              next 1M
              minextents 1
              maxextents unlimited
            );



          建立表遷移存儲過程(如果表abin5里面已經存在abin4里面遷移過來的記錄,那么就不再執行插入操作):

          create or replace procedure abing
          is
          begin
          declare
          cursor mycur is select t.id1,t.name1,t.createtime1 from abin4 t;
          sid abin4.id1%type;
          sname abin4.name1%type;
          screatetime abin4.createtime1%type;
          num number;
          begin
          open mycur;
          loop
          fetch mycur into sid,sname,screatetime;
          select count(*) into num from abin5 t where t.id1=sid and t.name1=sname and t.createtime1=screatetime;
          if(num=0) then
          insert into abin5 (id1,name1,createtime1) values (sid,sname,screatetime);
          end if;
          exit when mycur%NOTFOUND;
          commit;

          end loop;
          close mycur;
          end;
          end;



          建立Oracle定時器Job,讓系統定時的去執行操作:
          declare
          myjob1 number;
          begin
          sys.dbms_job.submit(myjob1,'abing;',sysdate,'sysdate+1/2880');
          commit;
          end;
          posted @ 2012-08-02 12:23 abin 閱讀(1076) | 評論 (0)編輯 收藏

          首先建表:
          -- Create table
          create table ABIN1
          (
            ID1         NUMBER,
            NAME1       NVARCHAR2(100),
            CREATETIME1 DATE default sysdate
          )
          tablespace SYSTEM
            pctfree 10
            pctused 40
            initrans 1
            maxtrans 255
            storage
            (
              initial 64K
              next 1M
              minextents 1
              maxextents unlimited
            );



          -- Create table
          create table ABIN2
          (
            ID2         NUMBER,
            NAME2       NVARCHAR2(100),
            CREATETIME2 DATE default sysdate
          )
          tablespace SYSTEM
            pctfree 10
            pctused 40
            initrans 1
            maxtrans 255
            storage
            (
              initial 64K
              next 1M
              minextents 1
              maxextents unlimited
            );



          -- Create table
          create table ABIN3
          (
            ID          NUMBER,
            NAME1       NVARCHAR2(100),
            NAME2       NVARCHAR2(100),
            CREATETIME1 DATE,
            CREATETIME2 DATE
          )
          tablespace SYSTEM
            pctfree 10
            pctused 40
            initrans 1
            maxtrans 255
            storage
            (
              initial 64K
              next 1M
              minextents 1
              maxextents unlimited
            );



          建立oracle存儲過程:

          create or replace procedure enforcesome
          is
          begin
          declare
          cursor mycur is  select t.id1,t.name1,t.createtime1,s.name2,s.createtime2 from abin1 t,abin2 s where t.id1=s.id2;
          sid abin1.id1%type;
          sname1 abin1.name1%type;
          sname2 abin2.name2%type;
          screatetime1 abin1.createtime1%type;
          screatetime2 abin2.createtime2%type;
          mysql varchar2(2000);
          begin
          open mycur;
          loop
          fetch mycur into sid,sname1,screatetime1,sname2,screatetime2;
          exit when mycur%NOTFOUND;
          mysql:='insert into abin3 (id,name1,name2,createtime1,createtime2) values ('||''''||sid||''''||','||''''||sname1||''''||','||''''||sname2||''''||','||''''||screatetime1||''''||','||''''||screatetime2||''''||')';
          execute immediate mysql;
          commit;
          end loop;
          close mycur;
          end;
          end;

           

           

           編寫oracle  Job定時器:
          declare
          myjob number;
          begin
          SYS.dbms_job.submit(myjob,'enforcesome;',sysdate,'sysdate+1/2880');
          commit;
          end;


          執行Job定時器代碼:

          posted @ 2012-08-02 09:35 abin 閱讀(445) | 評論 (0)編輯 收藏

          一、設置初始化參數 job_queue_processes
            sql> alter system set job_queue_processes=n;(n>0)
            job_queue_processes最大值為1000
            
            查看job queue 后臺進程
            sql>select name,description from v$bgprocess;
            
            二,dbms_job package 用法介紹
            包含以下子過程:
            
            Broken()過程。
            change()過程。
            Interval()過程。
            Isubmit()過程。
            Next_Date()過程。
            Remove()過程。
            Run()過程。
            Submit()過程。
            User_Export()過程。
            What()過程。
            
            1、Broken()過程更新一個已提交的工作的狀態,典型地是用來把一個已破工作標記為未破工作。
            這個過程有三個參數:job 、broken與next_date。
            
            PROCEDURE Broken (job    IN binary_integer,
                     Broken  IN boolean,
                     next_date IN date :=SYSDATE)
            
            job參數是工作號,它在問題中唯一標識工作。
            broken參數指示此工作是否將標記為破——TRUE說明此工作將標記為破,而FLASE說明此工作將標記為未破。
            next_date參數指示在什么時候此工作將再次運行。此參數缺省值為當前日期和時間。
            job如果由于某種原因未能成功之行,oracle將重試16次后,還未能成功執行,將被標記為broken重新啟動狀態為broken的job,有如下兩種方式;
            a、利用dbms_job.run()立即執行該job
              sql>begin
              sql>dbms_job.run(:jobno) 該jobno為submit過程提交時返回的job number
              sql>end;
              sql>/
            b、利用dbms_job.broken()重新將broken標記為false
              sql>begin
              sql>dbms_job.broken (:job,false,next_date)
              sql>end;
              sql>/
            2、Change()過程用來改變指定工作的設置。
            這個過程有四個參數:job、what 、next_date與interval。
            
            PROCEDURE Change (job    IN binary_integer,
                     What    IN varchar2,
                     next_date IN date,
                     interval  IN varchar2)
            
            此job參數是一個整數值,它唯一標識此工作。
            What參數是由此工作運行的一塊PL/SQL代碼塊。
            next_date參數指示何時此工作將被執行。
            interval參數指示一個工作重執行的頻度。
            
            3、Interval()過程用來顯式地設置重執行一個工作之間的時間間隔數。這個過程有兩個參數:job與interval。
            
            PROCEDURE Interval (job   IN binary_integer,
                      Interval IN varchar2)
            
            job參數標識一個特定的工作。interval參數指示一個工作重執行的頻度。
            
            4、ISubmit()過程用來用特定的工作號提交一個工作。這個過程有五個參數:job、what、next_date、interval與no_parse。
            
            PROCEDURE ISubmit (job    IN binary_ineger,
                      What   IN varchar2,
                      next_date IN date,
                      interval IN varchar2,
                      no_parse IN booean:=FALSE)
            
            這個過程與Submit()過程的唯一區別在于此job參數作為IN型參數傳遞且包括一個由開發者提供的工作號。如果提供的工作號已被使用,將產生一個錯誤。
            
            5、Next_Date()過程用來顯式地設定一個工作的執行時間。這個過程接收兩個參數:job與next_date。
            
            PROCEDURE Next_Date(job     IN binary_ineger,
                      next_date  IN date)
            job標識一個已存在的工作。next_date參數指示了此工作應被執行的日期與時間。
            
            6、Remove()過程來刪除一個已計劃運行的工作。這個過程接收一個參數:
            
            PROCEDURE Remove(job IN binary_ineger);
            
            job參數唯一地標識一個工作。這個參數的值是由為此工作調用Submit()過程返回的job參數的值。已正在運行的工作不能由調用過程序刪除。
            
            7、Run()過程用來立即執行一個指定的工作。這個過程只接收一個參數:
            
            PROCEDURE Run(job IN binary_ineger)
            
            job參數標識將被立即執行的工作。
            
            8、使用Submit()過程,工作被正常地計劃好。
            這個過程有五個參數:job、what、next_date、interval與no_parse。
            
            PROCEDURE Submit ( job    OUT binary_ineger,
                      What   IN varchar2,
                      next_date IN date,
                      interval IN varchar2,
                      no_parse IN booean:=FALSE)
            
            job參數是由Submit()過程返回的binary_ineger。這個值用來唯一標識一個工作。
            what參數是將被執行的PL/SQL代碼塊。
            next_date參數指識何時將運行這個工作。
            interval參數何時這個工作將被重執行。
            no_parse參數指示此工作在提交時或執行時是否應進行語法分析——TRUE指示此PL/SQL代碼在它第一次執行時應進行語法分析,而FALSE指示本PL/SQL代碼應立即進行語法分析。
            
            9、User_Export()過程返回一個命令,此命令用來安排一個存在的工作以便此工作能重新提交。
            此程序有兩個參數:job與my_call。
            
            PROCEDURE User_Export(job    IN binary_ineger,
                       my_call  IN OUT varchar2)
            
            job參數標識一個安排了的工作。my_call參數包含在它的當前狀態重新提交此工作所需要的正文。
            
            10、What()過程應許在工作執行時重新設置此正在運行的命令。這個過程接收兩個參數:job與what。
            
            PROCEDURE What (job IN binary_ineger,
                    What IN OUT varchar2)
            job參數標識一個存在的工作。what參數指示將被執行的新的PL/SQL代碼。
            
            三、查看相關job信息
            1、相關視圖
            dba_jobs
            all_jobs
            user_jobs
            dba_jobs_running 包含正在運行job相關信息
            
            2、查看相關信息
            
            SQL>SELECT JOB, NEXT_DATE, NEXT_SEC, FAILURES, BROKEN
            SQL>FROM DBA_JOBS;
            
            JOB NEXT_DATE NEXT_SEC FAILURES B
            ------- --------- -------- -------- -
            9125 01-JUN-01 00:00:00 4 N
            14144 24-OCT-01 16:35:35 0 N
            9127 01-JUN-01 00:00:00 16 Y
            3 rows selected.
            
            正在運行的JOB相關信息
            
            SELECT SID, r.JOB, LOG_USER, r.THIS_DATE, r.THIS_SEC
            FROM DBA_JOBS_RUNNING r, DBA_JOBS j
            WHERE r.JOB = j.JOB;
            
            SID JOB LOG_USER THIS_DATE THIS_SEC
            ----- ---------- ------------- --------- --------
            12 14144 HR 24-OCT-94 17:21:24
            25 8536 QS 24-OCT-94 16:45:12
            2 rows selected.
             
            JOB QUEUE LOCK相關信息
            
            SELECT SID, TYPE, ID1, ID2
            FROM V$LOCK
            WHERE TYPE = 'JQ';
            
            SID TY ID1 ID2
            --------- -- --------- ---------
            12 JQ 0 14144
            1 row selected.
            
            四、簡單例子
            一個簡單例子:
            
            創建測試表
            SQL> create table TEST(a date);
            
            表已創建。
            
            創建一個自定義過程
            SQL> create or replace procedure MYPROC as
             2 begin
             3 insert into TEST values(sysdate);
             4 end;
             5 /
            
            過程已創建。
            
            創建JOB
            SQL> variable job1 number;
            SQL>
            SQL> begin
             2 dbms_job.submit(:job1,'MYPROC;',sysdate,'sysdate+1/1440');  --每天1440分鐘,即一分鐘運行test過程一次
             3 end;
             4 /
            
            PL/SQL 過程已成功完成。
            
            運行JOB
            SQL> begin
             2 dbms_job.run(:job1);
             3 end;
             4 /
            
            PL/SQL 過程已成功完成。
            
            SQL> select to_char(a,'yyyy/mm/dd hh24:mi:ss') 時間 from TEST;
            
            時間
            -------------------
            2001/01/07 23:51:21
            2001/01/07 23:52:22
            2001/01/07 23:53:24
            
            刪除JOB
            SQL> begin
             2 dbms_job.remove(:job1);
             3 end;
             4 /
            
            PL/SQL 過程已成功完成。
          posted @ 2012-08-02 09:13 abin 閱讀(298) | 評論 (0)編輯 收藏

          僅列出標題
          共50頁: First 上一頁 34 35 36 37 38 39 40 41 42 下一頁 Last 
          主站蜘蛛池模板: 徐水县| 清新县| 友谊县| 怀远县| 吉林省| 天津市| 赤壁市| 策勒县| 唐河县| 宣威市| 广河县| 通化县| 肥西县| 南昌市| 阳信县| 集贤县| 遵化市| 曲麻莱县| 吴忠市| 筠连县| 寻乌县| 赤城县| 蒙自县| 洞口县| 无极县| 桃园市| 佛冈县| 陵水| 加查县| 信丰县| 宁夏| 酉阳| 松溪县| 桐梓县| 离岛区| 寿阳县| 邵东县| 凯里市| 洛隆县| 毕节市| 那曲县|