少年阿宾

那些青春的岁月

  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 阅读(642) | 评论 (0)编辑 收藏

根据网上的资料做些整理

Java NIO API详解

http://www.blogjava.net/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 阅读(648) | 评论 (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 阅读(416) | 评论 (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 阅读(5417) | 评论 (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 阅读(871) | 评论 (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 阅读(467) | 评论 (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 阅读(1759) | 评论 (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 阅读(1071) | 评论 (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 阅读(443) | 评论 (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 阅读(296) | 评论 (0)编辑 收藏

仅列出标题
共50页: First 上一页 34 35 36 37 38 39 40 41 42 下一页 Last