场景描述
大型互联网项目中,由于业务特点(例如秒杀)同一时间很多的人在使用,用户连续快速点击,而且前端没有针对性处理,导致连续发送两次请求,此时如果不做好控制,那么系统将会产生很多的数据重复的问题。
解决方案
解决思路:相同的请求在同一时间只能被处理一次。
分布式锁
1.服务器A接收到请求之后,获取锁,获取成功
2.服务器A进行业务处理,订单提交成功
3.服务器B接收到相同的请求,获取锁,失败,因为锁被服务器A获取了,并且未释放
4.服务器A处理完成,释放锁 实现采用redis
流程图
代码设计
防重复提交注解类
/**
* 避免重复提交注解
* @Author huanglian
* @Date 2019-01-24-下午4:56
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AvoidRepeatableCommit {
long acquireTimeout() default 1000;
long lockTimeout() default 2000;
}
防重复提交切面类
/**
* 避免重复提交切面
*
* @Author huanglian
* @Date 2019-01-24-下午5:09
*/
@Component
@Aspect
public class AvoidRepeatableCommitAspect {
private static final Logger logger = LoggerFactory.getLogger(AvoidRepeatableCommitAspect.class);
@Autowired
private StringRedisTemplate stringRedisTemplate;
private AvoidRepeatableCommitLock avoidRepeatableCommitLock;
@PostConstruct
private void init() {
avoidRepeatableCommitLock = new AvoidRepeatableCommitLock(stringRedisTemplate);
}
@Autowired
private HttpServletRequest request;
@Around("execution(public * com.app.sns.controller..*.*(..))")
public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
AvoidRepeatableCommit avoidRepeatableCommitAnnotation = method.getAnnotation(AvoidRepeatableCommit.class);
//如果注解为空,则不需要校验重复提交
if (avoidRepeatableCommitAnnotation == null) {
return joinPoint.proceed();
}
//按key从小到大,对参数进行排序,目的是确保统一请求的内容加密结果一致
Map requestParams = request.getParameterMap();
String body = requestParams.get("body")[0];
//按key从小到大,对参数body进行排序
TreeMap treeMap = JSONObject.parseObject(body, TreeMap.class);
body = JSONObject.toJSONString(treeMap);
requestParams.put("body", new String[]{body});
String lockName = MapUtil.getRedisKeyByParam(requestParams);
logger.info("lockName ->" + lockName);
long start = System.currentTimeMillis();
//获取锁
String identifier = avoidRepeatableCommitLock.acquireLock(lockName);
//锁标识为空,则表示锁已存在,当前请求是重复提交
if (identifier == null) {
IBaseResp resp = new IBaseResp();
return BaseRespUtils.buildFailed(resp, ErrorType.FAILED.getErrorCode(), "您操作太频繁啦");
}
logger.info("acquireLock time -> " + (System.currentTimeMillis() - start));
try {
return joinPoint.proceed();
} finally {
//释放锁
boolean flag = avoidRepeatableCommitLock.releaseLock(lockName, identifier);
logger.info("releaseLock flag ->" + flag);
}
}
}
防重复提交锁类
/**
* Redis防重复提交锁
*
* @Author huanglian
* @Date 2019-01-24-上午9:50
*/
public class AvoidRepeatableCommitLock {
private static Logger logger = LoggerFactory.getLogger(AvoidRepeatableCommitLock.class);
private final long lockTimeout = 3000;
private StringRedisTemplate redisTemplate;
public AvoidRepeatableCommitLock(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public String acquireLock(final String lockName) {
return acquireLock(lockName, lockTimeout);
}
public String acquireLock(final String lockName, final long lockTimeout) {
//保证释放锁的时候是同一个持有锁的人
final String identifier = UUID.randomUUID().toString();
final int lockExpire = (int) (lockTimeout / 1000);
final String lockKey = "lock:" + lockName;
final String lua = "if redis.call(\"setnx\",KEYS[1], ARGV[1])==1 then " +
"redis.call(\"expire\",KEYS[1], ARGV[2]) " +
"return 1 " +
"else return 0 end";
Long rs = redisTemplate.execute(new RedisCallback() {
@Override
public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
Object nativeConnection = redisConnection.getNativeConnection();
Long result = 0L;
List keys = new ArrayList<>();
keys.add(lockKey);
List values = new ArrayList<>();
values.add(identifier);
values.add(lockExpire + "");
// 集群模式
if (nativeConnection instanceof JedisCluster) {
result = (Long) ((JedisCluster) nativeConnection).eval(lua, keys, values);
}
// 单机模式
if (nativeConnection instanceof Jedis) {
result = (Long) ((Jedis) nativeConnection).eval(lua, keys, values);
}
return result;
}
});
return rs == 1 ? identifier : null;
}
public boolean releaseLock(final String lockName, final String identifier) {
logger.info(lockName + "开始释放锁:" + identifier);
final String lockKey = "lock:" + lockName;
final String lua = "if redis.call(\"get\",KEYS[1])==ARGV[1] then " +
"return redis.call(\"del\",KEYS[1]) " +
"else return 0 end";
Long rs = redisTemplate.execute(new RedisCallback() {
@Override
public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
Object nativeConnection = redisConnection.getNativeConnection();
Long result = 0L;
List keys = new ArrayList<>();
keys.add(lockKey);
List values = new ArrayList<>();
values.add(identifier);
// 集群模式
if (nativeConnection instanceof JedisCluster) {
result = (Long) ((JedisCluster) nativeConnection).eval(lua, keys, values);
}
// 单机模式
if (nativeConnection instanceof Jedis) {
result = (Long) ((Jedis) nativeConnection).eval(lua, keys, values);
}
return result;
}
});
return rs.intValue() > 0;
}
}
Controller类
/**
* @Author huanglian
* @Date 2019-01-24-上午11:38
*/
@Controller
@RequestMapping(value = "/lock/")
public class LockController {
@AvoidRepeatableCommit
@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public IBaseResp lock() throws InterruptedException {
Thread.sleep(1000);
return BaseRespUtils.buildSuccess(new IBaseResp());
}
}