项目背景:
分布式应用服务器,单点数据库
思路:
在数据库上做控制,保证事务串行化控制
给请求的资源分配一个唯一的锁,竞争到锁的线程开始执行业务
通过把请求锁的SQL写成SP,在代码执行的开始处调用
SP:
create or replace
PACKAGE BODY UTIL_LOCK IS
PROCEDURE request_lock(v_lockname in VARCHAR2, p_retval OUT INTEGER, p_lockhandle OUT VARCHAR2) IS
v_lockhandle LONG;
BEGIN
DBMS_LOCK.allocate_unique(v_lockname, v_lockhandle);
p_retval := dbms_lock.request(v_lockhandle,dbms_lock.x_mode,30000);
p_lockhandle :=v_lockhandle;
END request_lock;
------------------------------------------------------------
PROCEDURE release_lock(p_lockhandle IN VARCHAR2) IS
p_out NUMBER;
BEGIN
p_out := dbms_lock.release(p_lockhandle);
END release_lock;
------------------------------------------------------------
END UTIL_LOCK;
JAVA代码:
private boolean lock(Connection conn, String resource)
{
CallableStatement cs;
try
{
String lStrSP = "{call UTIL_LOCK.request_lock(?,?,?)}";
cs = conn.prepareCall(lStrSP);
cs.setString(1, resource);
cs.registerOutParameter(2, OracleTypes.NUMBER);
cs.registerOutParameter(3, OracleTypes.VARCHAR);
cs.execute();
int ret = cs.getInt(2);
this.handle = cs.getString(3);
cs.close();
return ret == 0;
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
调用:
if(lockutil.lock(conn,"resource")){
//place your code here
...
lockutil.release();
}
分布式应用服务器,单点数据库
思路:
在数据库上做控制,保证事务串行化控制
给请求的资源分配一个唯一的锁,竞争到锁的线程开始执行业务
通过把请求锁的SQL写成SP,在代码执行的开始处调用
SP:
create or replace
PACKAGE BODY UTIL_LOCK IS
PROCEDURE request_lock(v_lockname in VARCHAR2, p_retval OUT INTEGER, p_lockhandle OUT VARCHAR2) IS
v_lockhandle LONG;
BEGIN
DBMS_LOCK.allocate_unique(v_lockname, v_lockhandle);
p_retval := dbms_lock.request(v_lockhandle,dbms_lock.x_mode,30000);
p_lockhandle :=v_lockhandle;
END request_lock;
------------------------------------------------------------
PROCEDURE release_lock(p_lockhandle IN VARCHAR2) IS
p_out NUMBER;
BEGIN
p_out := dbms_lock.release(p_lockhandle);
END release_lock;
------------------------------------------------------------
END UTIL_LOCK;
JAVA代码:
private boolean lock(Connection conn, String resource)
{
CallableStatement cs;
try
{
String lStrSP = "{call UTIL_LOCK.request_lock(?,?,?)}";
cs = conn.prepareCall(lStrSP);
cs.setString(1, resource);
cs.registerOutParameter(2, OracleTypes.NUMBER);
cs.registerOutParameter(3, OracleTypes.VARCHAR);
cs.execute();
int ret = cs.getInt(2);
this.handle = cs.getString(3);
cs.close();
return ret == 0;
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
调用:
if(lockutil.lock(conn,"resource")){
//place your code here
...
lockutil.release();
}