欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java并发请求下数据插入重复问题的解决方法

程序员文章站 2024-01-03 10:13:10
目录前言分布式锁工具类在过滤器实现请求拦截总结前言前段时间发现数据库里经常会存在两条相同的用户数据,导致数据查询异常。查了原因,发现前端微信小程序在授权登录时,有时会出现同时发送了两条一模一样的请求(...

前言

前段时间发现数据库里经常会存在两条相同的用户数据,导致数据查询异常。查了原因,发现前端微信小程序在授权登录时,有时会出现同时发送了两条一模一样的请求(也就是常说的并发)。虽然后端代码有做防重复的判断,但是避免不了并发时候的重复性操作。于是就开始考虑并发的解决方案,解决方案有很多,从拦截请求到数据库层面都可以入手。

我们采用了对请求报文生成摘要信息+redis分布式锁的方案。运行了一段时间,功能很可靠,代码也很简洁。于是上来做下记录以便后续参考。

解决方案说明:

系统架构用的spring boot,定义一个filter过滤器对请求进行过滤,然后对请求报文生成摘要信息并设置redis分布式锁。通过摘要和锁判断是否为同一请求。

分布式锁工具类

public class contextlj {
	
	private static final integer jd = 0;
	
	  /**
	   * 上锁 使用redis 为分布式项目 加锁
	   * @param sign
	   * @param tid
	   * @return
	   * @throws exception
	   */
	  public static boolean lock(string sign, string tid) {
	    synchronized (jd) { // 加锁
	    	cache<string> cache = cachemanager.getcommoncache(sign);
	    	if(cache == null || stringutils.isblank(cache.getvalue())) {
	    		cachemanager.putcommoncacheinfo(sign, tid, 10000);
	    		return true;
			}
	    	return false;
	    }
	 }
	 
	  /**
	   * 锁验证
	   * @param sign
	   * @param tid
	   * @return
	   */
	  public static boolean checklock(string sign, string tid){
		  cache<string> cache = cachemanager.getcommoncache(sign);
		  string utid = stringutils.replace(cache.getvalue(), "\"", "");
		  return tid.equals(utid);
	  }
	 
	  /**
	   * 去掉锁
	   * @param sign
	   * @param tid
	   */
	  public static void clent (string sign, string tid){
		    if (checklock(sign, tid)) {
		    	cachemanager.clearonly(sign);
		    }
	  }
	 
	  /**
	   * 获取摘要
	   * @param request
	   */
	  public static string getsign(servletrequest request){
	    // 此工具是将 request中的请求内容 拼装成 key=value&key=value2 的形式 源码在线面
	    string sign = null;
	    try {
	    	map<string, string> map =  getrequstmap((httpservletrequest) request);
	    	// 生成摘要
	    	sign = buildrequest(map);
	    } catch (exception e) {
	    	e.printstacktrace();
	    }
	    return sign;
	  }
	  
	  public static map<string, string> getrequstmap(httpservletrequest req) throws exception{
 		    map<string,string> params = new hashmap<string,string>();
 		    params.put("uri", req.getrequesturi());
		    map<string, string[]> requestparams = req.getparametermap();
		    for (iterator<string> iter = requestparams.keyset().iterator(); iter.hasnext();) {
		      string name = (string) iter.next();
		      string[] values = (string[]) requestparams.get(name);
		      string valuestr = "";
		      for (int i = 0; i < values.length; i++) {
		        valuestr = (i == values.length - 1) ? valuestr + values[i] : valuestr + values[i] + ",";
		      }
		      params.put(name, valuestr);
		    }
		    return params;
	}
	  
	 private static string buildrequest(map<string, string> map) {
		 list<string> signlist = new arraylist<>();
		 for(entry<string, string> entry : map.entryset()) {
			 signlist.add(entry.getkey() + "=" + entry.getvalue());
		 }
		 string sign = stringutils.join(signlist, "&");
		 return digestutils.md5hex(sign);
	}
	
}

在过滤器实现请求拦截

/**
 * 过滤频繁请求
 */
@slf4j
@component
public class myfilter implements filter{
	
	@override
	public void init(filterconfig filterconfig) throws servletexception {
		
	}

	@override
	public void dofilter(servletrequest request, servletresponse myresp, filterchain chain) throws ioexception, servletexception {
		httpservletrequest req = (httpservletrequest) request;
		boolean isdict = stringutils.contains(req.getrequesturi(), "/dict/getdatas");
		boolean isfile = stringutils.contains(req.getrequesturi(), "/files/file");
		if(isdict || isfile) {
			chain.dofilter(request, myresp); // 查询数据字典或者文件,直接放行
			return;
		}
		string sign = "sign_" + contextlj.getsign(request); // 生成摘要
	    string tid = randomutils.randomcode(3) + "_" + thread.currentthread().getid(); // 当前线程的身份
	    try { 
	    	if (!contextlj.lock(sign, tid)) {
	    		map<string,string> map = contextlj.getrequstmap((httpservletrequest)request);
	    		log.warn("放弃相同并发请求【" + sign+ "】【" + tid+"】"+json.tojsonstring(map));
	    		frequentlyerror(myresp);
	    		return;
	    	}
	    	if (!contextlj.checklock(sign, tid)) {
	    		map<string,string> map = contextlj.getrequstmap((httpservletrequest)request);
		    	  log.warn("加锁验证失败 【" + sign+ "】【" + tid+"】"+json.tojsonstring(map));
		    	  frequentlyerror(myresp);
		    	  return;
	    	}
	    	chain.dofilter(request, myresp); // 放行
	    } catch (exception e) { // 捕获到异常 进行异常过滤
		      log.error("", e);
		      myresp.getwriter().write(json.tojsonstring(apirs.aserror("服务器繁忙,请重试")));
	    } finally {
	    	contextlj.clent(sign, tid);
	    }
	}

	@override
	public void destroy() {
		
	}
	
	/**
	 * 频繁请求
	 */
	private void frequentlyerror(servletresponse myresp) throws ioexception {
	  ((httpservletresponse) myresp).setheader("content-type", "text/html;charset=utf-8");
	  myresp.getwriter().write(json.tojsonstring(apirs.aserror("稍安勿躁,不要频繁请求")));
	}

}

总结

到此这篇关于java并发请求下数据插入重复问题的解决方法的文章就介绍到这了,更多相关java并发请求数据插入重复内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

上一篇:

下一篇: