@Autowired
private JedisConnectionFactory redisConnectionFactory;
private RedisTemplate<String, String> taskTemplate;
private ValueOperations<String, String> taskOps;
@PostConstruct
private void init() {
taskTemplate = new RedisTemplate<String, String>();
taskTemplate.setConnectionFactory(redisConnectionFactory);
taskTemplate.afterPropertiesSet();
taskOps = taskTemplate.opsForValue();
taskTemplate.setKeySerializer(new StringRedisSerializer());
taskTemplate.setValueSerializer(new StringRedisSerializer());
}
// key value 存活时间 时间单位
public boolean lock(String key, String value, long timeout, TimeUnit unit) {
try {
int randomNum = RandomUtils.nextInt(5000);
Thread.sleep(randomNum);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (taskOps.get(key) == null) {
taskOps.set(key, value, timeout, unit);
return true;
} else {
System.out.println("redis里别人已上锁: " + taskOps.get(key));
return false;
}
}
final JedisPool pool = RedisUtil.getPool();
// 对测试key赋初始值
Jedis jedis = pool.getResource();
jedis.hset("lock_test", "locker", "0");
String val = jedis.hget("lock_test", "locker");
System.out.println("lock_test.locker的初始值為:" + val);
jedis.close();
int threahSize = 64;
final CountDownLatch threadsCountDownLatch = new CountDownLatch(threahSize);
Runnable handler = new Runnable() {
public void run() {
Jedis jedis = pool.getResource();
while (true) {
jedis.watch("lock_test");
String val = jedis.hget("lock_test", "locker");
Integer integer = Integer.valueOf(val);
Transaction tx = jedis.multi();
tx.hset("lock_test", "locker", String.valueOf(integer + 1));
List<Object> exec = tx.exec();
if (exec == null || exec.isEmpty()) {
System.out.println(Thread.currentThread().getName() + ":" + "Error:(" + val + "=>" + (integer + 1) + ")");
} else {
String values = "";
for (int i = 0; i < exec.size(); i++) {
values += exec.get(i).toString();
}
System.out.println(Thread.currentThread().getName() + ":" + values + ":(" + val + "=>" + (integer + 1) + ")");
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
jedis.close();
threadsCountDownLatch.countDown();
}
};
for (int i = 0; i < threahSize; i++) {
new Thread(handler).start();
}
// 等待所有并行子线程任务完成。
try {
threadsCountDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("complete");
val = jedis.hget("lock_test", "locker");
System.out.println(val);
}