分别 用Phaser CountDownLatch CyclicBarrier模拟实现并发
获取redis连接
public class JedisPoolManager {
private static String url = "127.0.0.1";
private static int port = 6379;
private static int timeout = 10000;
private static String auth = "admin";
// JedisConfig
private static int max_active = 1024;
private static int max_idle = 200;
private static int max_wait = 10000;
private static boolean test_on_borrow = true;
private static JedisPool jedisPool = null;
static {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(max_idle);
poolConfig.setMaxWaitMillis(max_wait);
poolConfig.setMaxTotal(max_active);
poolConfig.setTestOnBorrow(true);
jedisPool = new JedisPool(poolConfig, url, port, timeout/*, auth*/);
}
public Jedis getJedis() {
Jedis jedis = null;
if (null != jedisPool) {
jedis = jedisPool.getResource();
}
return jedis;
}
}
模拟的并发情况,最终的效果就是并发请求redis分布式,同一时刻只能有一个请求可以操作
package redis;
import com.yanxml.redis.demos.pool.JedisPoolManager;
import redis.clients.jedis.Jedis;
import java.util.Collections;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.ReentrantLock;
public class RedisLockDemo {
public static Jedis jedis = new JedisPoolManager().getJedis();
// demo1 Jedis lock can do but not perfect.
public static boolean notperfectLock(String key){
Long result = jedis.setnx(key, "This is a Lock.");
if(result == 1l){
return true;
}else{
return false;
}
}
// demo1 Jedis unlock can do but not perfect.
public static boolean notperfectUnlock(String key){
jedis.del(key);
return true;
}
// demo1 Jedis unlock can do but also not perfect.
public static boolean notperfectUnlock2(String lockKey, String lockValue){
if(lockKey.equals(jedis.get(lockKey))){
jedis.del(lockKey);
}
return true;
}
// demo2 perfect lock demo.
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXISTS = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
/**
* 设置分布式锁
* @param
* @param lockKey 锁
* @param requestId 请求标识
* @param expireTime 生效时间
* @return 是否释放成功
*/
public static boolean tryGetDistributedLock(String lockKey,String requestId,int expireTime){
String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXISTS,SET_WITH_EXPIRE_TIME,expireTime);
if(LOCK_SUCCESS.equals(result)){
System.out.println("jinlai");
return true;
}
System.out.println("meijinlai");
return false;
}
private static final Long RELEASE_SUCCESS = 1L;
/**
* 释放分布式锁
* @param jedis Redis客户端
* @param lockKey 锁
* @param requestId 请求标识
* @return 是否释放成功
*/
public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}
public static void main(String[] args) {
/* Phaser begin */
/* Phaser phaser=new Phaser();
phaser.bulkRegister(10);//这个类可以动态增加栏杆
phaser.register();//用于手动控制执行时机
ReentrantLock reentrantLock=new ReentrantLock();
for(int i=0;i<10;i++){
Thread t= new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "准备");
phaser.arriveAndAwaitAdvance();//10个线程等待在这里 才开始执行下面的
//System.out.println(Thread.currentThread().getName() + "起跑");
//Thread.sleep(2000);
reentrantLock.lock();//多个线程会同时来执行下面的代码,加锁进行控制
// System.out.println("getQueueLength="+reentrantLock.getQueueLength());
tryGetDistributedLock("hello","hello",10000);
//并发访问redis出现异常redis.clients.jedis.exceptions.JedisConnectionException: Unexpected end of stream
//解决办法加锁进行控制
} catch (Exception e) {
e.printStackTrace();
}finally {
//System.out.println(Thread.currentThread().getName() + "起跑");
reentrantLock.unlock();
}
}
});
t.start();
}
try {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + "起跑");
//可以手动控制执行的时机
phaser.arriveAndDeregister();//解除一个栏杆
}catch ( Exception e){
e.printStackTrace();
}
System.out.println( phaser.getUnarrivedParties()+"--" );//说明phaser也可以重置栏杆 在主线程当中执行的
*//* Phaser end *//*
*/
/*CyclicBarrier start 没有找到动态改变栏杆的方式,不能手动改变执行时机*/
CyclicBarrier cbRef = new CyclicBarrier(10);
ReentrantLock reentrantLock=new ReentrantLock();
for(int i=0;i<10;i++){
Thread t= new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "准备");
cbRef.await();//10个线程等待在这里 才开始执行下面的
reentrantLock.lock();
tryGetDistributedLock("hello","hello",10000);
} catch (Exception e) {
e.printStackTrace();
}finally {
reentrantLock.unlock();
}
}
});
t.start();
}
//这一段可以不要
try {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + "起跑");
System.out.println( cbRef.getParties()+"--" +cbRef.getNumberWaiting());
}catch (Exception e){
e.printStackTrace();
}
/* CyclicBarrier end*/
/* CountDownLatch cdl=new CountDownLatch(1);//一个栏杆
ReentrantLock reentrantLock=new ReentrantLock();
for(int i=0;i<10;i++){
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "准备");
cdl.await();
reentrantLock.lock();
tryGetDistributedLock("hello","hello",10000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
reentrantLock.unlock();
}
}
}).start();
}
try {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + "起跑");
//可以手动控制执行的时机
cdl.countDown();
}catch ( Exception e){
e.printStackTrace();
}*/
}
}
使用Redisson实现分布式锁,Spring AOP简化之
https://www.jianshu.com/p/828aa3b44564
感觉这篇写的很不错