在应用中,总有一些业务操作可能会引起大数据量的查询,基于应用健壮性的考虑,需要对这些业务控制起来。
思路:外围业务每次请求时,应用每次申请一个资源,当超过限定的资源总数时,不允许业务继续进行.
try{
applyResource();
do业务();
}
finally{
releaseResource();
}
实现1:在数据库中,针对具体业务插入一条记录(sysName,sysCount),
synchronized void applyResource(){
count=selectCountFromDB();
if(count<limitCount){
updateCount(++count);
}else{
throw new RuntimeException();
}
}
synchronized void releaseResource(){
count=selectCountFromDB();
updateCount(--count);
}
实现2:在cache中,针对具体业务put一个对象(sysName,sysCount)
synchronized void applyResource(){
count=selectCountFromCache();
if(count<limitCount){
updateCount(++count);
}else{
throw new RuntimeException();
}
}
synchronized void releaseResource(){
count=selectCountFromCache();
updateCount(--count);
}
继续扩展:
try{
applyResource();
do业务();
}
finally{
releaseResource();
}
基于此模式,可以利用AOP拦截器的模式,来一个配一个,来一对配一双,将申请资源和具体业务解耦合