分布式工具集-基于redis和zookeeper的分布式锁,分布式限速器等实现.
#基于Redis实现的分布式锁(可重入锁,仅限获得持有锁的jvm内重入)
public static void main(String[] args){ JedisPool jedisPool=new JedisPool("127.0.0.1",6379);//实际应用时可通过spring注入 final RedisDistributedLockTemplate template=new RedisDistributedLockTemplate(jedisPool);//本类多线程安全,可通过spring注入 template.execute("订单流水号", 5000, new Callback() { @Override public Object onGetLock() throws InterruptedException { //TODO 获得锁后要做的事 return null; }
@Override
public Object onTimeout() throws InterruptedException {
//TODO 获得锁超时后要做的事
return null;
}
});
}
public static void main(String[] args) throws Exception { JedisPool jedisPool=new JedisPool("127.0.0.1",6379);//实际应用时可通过spring注入 RedisReentrantLock lock=new RedisReentrantLock(jedisPool,"订单流水号"); try { if (lock.tryLock(5000L, TimeUnit.MILLISECONDS)) { //TODO 获得锁后要做的事 }else{ //TODO 获得锁超时后要做的事 } }finally { lock.unlock(); } }
#基于Zookeeper实现的分布式锁(可重入锁,仅限获得持有锁的jvm内重入)
public static void main(String[] args){ RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy); client.start();
final ZkDistributedLockTemplate template=new ZkDistributedLockTemplate(client);//本类多线程安全,可通过spring注入
template.execute("订单流水号", 5000, new Callback() {
@Override
public Object onGetLock() throws InterruptedException {
//TODO 获得锁后要做的事
return null;
}
@Override
public Object onTimeout() throws InterruptedException {
//TODO 获得锁超时后要做的事
return null;
}
});
}
#基于Redis实现的分布式速率限制器 public class AccessSpeedLimitTest { @Test public void test1() throws InterruptedException { JedisPool jp=new JedisPool("127.0.0.1",6379); AccessSpeedLimit accessSpeedLimit=new AccessSpeedLimit(jp); SimpleDateFormat sdf=new SimpleDateFormat(" mm:ss"); while(true){ //10.0.0.1这个ip每1秒钟最多访问5次本方法. if(accessSpeedLimit.tryAccess("10.0.0.1", 1,5)){ System.out.println("yes"+sdf.format(new Date())); }else{ System.out.println("no"+sdf.format(new Date())); } Thread.sleep(100); } }
@Test
public void test2() throws InterruptedException {
JedisPool jp=new JedisPool("127.0.0.1",6379);
final RedisDistributedLockTemplate template=new RedisDistributedLockTemplate(jp);
LimitRule limitRule=new LimitRule();
limitRule.setSeconds(1);
limitRule.setLimitCount(5);
limitRule.setLockCount(7);
limitRule.setLockTime(2);
AccessSpeedLimit accessSpeedLimit=new AccessSpeedLimit(jp);
SimpleDateFormat sdf=new SimpleDateFormat(" mm:ss");
while(true){
//10.0.0.1这个ip每1秒钟最多访问5次本方法.1秒超过10次后,锁定2秒.
if(accessSpeedLimit.tryAccess("10.0.0.1",limitRule)){
System.out.println("yes"+sdf.format(new Date()));
}else{
System.out.println("no"+sdf.format(new Date()));
}
Thread.sleep(100);
}
}
}