package com.whereta.jedis;
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool;
import javax.annotation.Resource; import java.util.Calendar; import java.util.Date; import java.util.concurrent.TimeUnit;
/**
* Created by vincent on 15-10-14.
*/ @Aspect @Component public class JedisLockAop {
@Resource
private JedisPool jedisPool;
@Around("execution(public * com.heli.core.pay.soaservice.impl.*.*(..))")
public Object serviceAOP(ProceedingJoinPoint point) {
Object proceed = null;
Jedis jedis = jedisPool.getResource();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MILLISECOND, 0);
Date calendarTime = calendar.getTime();
long time = calendarTime.getTime();
//请求参数数组 Object[] args = point.getArgs();
//key可以自定义 String key = JedisLock.CacheName.ADD_BEAN_AFTER_CHECK_LOCK_KEY + ":" + args[0];
try {
if (jedis != null) {
Long lock = jedis.setnx(key, time + "");
while (lock == 0) {
TimeUnit.MILLISECONDS.sleep(50);
lock = jedis.setnx(key, time + "");
}
//设置超时时间 jedis.expire(key, 3);
}
//用户业务处理 proceed = point.proceed();
return proceed;
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
} finally {
if (jedis != null) {
jedis.del(key);
jedis.close();
}
}
}
}