方式一:直接添加synchronized关键字
方式二:通过apache提供的工具进行校验----双重检测锁(DCL)
1.引入
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-collections4artifactId>
<version>4.4version>
</dependency>
2.封装工具类
import org.apache.commons.collections4.map.LRUMap;
/**
* 幂等性判断
*/
public class IdempotentUtils {
// 根据 LRU(Least Recently Used,最近最少使用)算法淘汰数据的 Map 集合,最大容量 100 个
private static LRUMap reqCache = new LRUMap<>(100);/**
* 幂等性判断
* @return
*/public static boolean judge(String id, Object lockClass) {
synchronized (lockClass) {// 重复请求判断if (reqCache.containsKey(id)) {// 重复请求
System.out.println("请勿重复提交!!!" + id);return false;
}// 非重复请求,存储请求 ID
reqCache.put(id, 1);
}return true;
}
}
调用代码如下:
import com.example.idempote.util.IdempotentUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/user")
@RestController
public class UserController4 {
@RequestMapping("/add")
public String addUser(String id) {
// 非空判断(忽略)...
// -------------- 幂等性调用(开始) --------------
if (!IdempotentUtils.judge(id, this.getClass())) {
return "执行失败";
}
// -------------- 幂等性调用(结束) --------------
// 业务代码...
System.out.println("添加用户ID:" + id);
return "执行成功!";
}
}