在用户使用网站创建新闻时,由于网络波动,导致发送了多个创建新闻的请求,使得系统中存在了冗余的数据。
由于我的应用是单例的,所以采用guava来做缓存。
import com.csdc.cett.exception.RequestException; import com.csdc.cett.util.MD5; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Enumeration; import java.util.concurrent.TimeUnit; /** * 处理重复请求,保持请求的幂等性 * 使用双重检查锁定(DCL) * * @author ksyzz * @since <pre>2019/06/20</pre> */ @Component public class RequestInterceptor implements HandlerInterceptor { private static volatile Cache<String, String> loadingCache = CacheBuilder.newBuilder() .maximumSize(500) .expireAfterWrite(5, TimeUnit.SECONDS) .build(); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 只需要保持用户登录后的POST请求的幂等性,此处要排除文件分片上传 if ("POST".equals(request.getMethod()) && request.getHeader("Auth-Token") != null && !request.getRequestURI().contains("/upload/files")) { // 要求:用户5秒内不能重复提交相同url,相同参数的请求 // 存储方式为 md5(URI+Auth-Token+RequestParams+InputStream) StringBuilder md5 = new StringBuilder(); // Auth-Token为用户身份标识 String token = request.getHeader("Auth-Token"); md5.append(request.getRequestURI()); md5.append(token); Enumeration<String> parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String key = parameterNames.nextElement(); String parameter = request.getParameter(key); md5.append("&").append(key).append("=").append(parameter); } String cacheKey = MD5.getHashString(md5.toString()); // 校验是否已经提交过请求 if (loadingCache.getIfPresent(cacheKey) == null) { synchronized (loadingCache) { if (loadingCache.getIfPresent(cacheKey) == null) { // 此处value可不设置 loadingCache.put(cacheKey, ""); return true; } } } throw new RequestException("请勿重复提交"); } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }