好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解java解决分布式环境中高并发环境下数据插入重复问题

java 解决分布式环境中 高并发环境下数据插入重复问题

前言

原因:服务器同时接受到的重复请求
现象:数据重复插入 / 修改操作

解决方案 : 分布式锁

对请求报文生成 摘要信息 + redis 实现分布式锁

工具类

分布式锁的应用

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

package com.nursling.web.filter.context;

 

import com.nursling.nosql.redis.redisutil;

import com.nursling.sign.signtype;

import com.nursling.sign.signutil;

import redis.clients.jedis.jedis;

 

import javax.servlet.servletrequest;

import javax.servlet.http.httpservletrequest;

import java.util.hashmap;

import java.util.map;

 

/**

  * 并发拦截

  * 高并发下 过滤掉 相同请求的工具

  * @author 杨.

  *

  */

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) { // 加锁

       jedis jedis = redisutil.getjedis();

       string utid = jedis.get(sign);

       if (utid == null ) {

         jedis.set(sign, tid);

         jedis.expire(sign, 36 );

         return true ;

       }

       return false ;

     }

   }

 

   /**

    * 锁验证

    * @param sign

    * @param tid

    * @return

    */

   public static boolean checklock(string sign, string tid){

     jedis jedis = redisutil.getjedis();

     string utid = jedis.get(sign);

     return tid.equals(utid);

   }

 

   /**

    * 去掉锁

    * @param sign

    * @param tid

    */

   public static void clent (string sign, string tid){

     if (checklock(sign, tid)) {

       jedis jedis = redisutil.getjedis();

       jedis.del(sign);

     }

   }

 

   /**

    * 获取摘要

    * @param request

    * @return

    */

   public static string getsign(servletrequest request){

     // 此工具是将 request中的请求内容 拼装成 key=value&key=value2 的形式 源码在线面

     map<string, string> map =       signutil.getrequstmap((httpservletrequest) request);

     string sign = null ;

     try {

       // 这里使用md5方法生成摘要 signutil.getrequstmap 方法源码就不贴了

       sign = signutil.buildrequest(map, signtype.md5);

     } catch (exception e) {

       e.printstacktrace();

     }

     return sign;

   }

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

public static map<string, string> getrequstmap(httpservletrequest req){

     map<string,string> params = new hashmap<string,string>();

     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;

   }

下面是过滤器代码

对分布式锁的利用

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

package com.nursling.web.filter.transaction;

 

import com.google.gson.gson;

import com.nursling.common.randomutil;

import com.nursling.dao.util.transactionutils;

import com.nursling.model.apiresult;

import com.nursling.model.apirtncode;

import com.nursling.web.filter.context.contextlj;

import org.apache.log4j.logger;

 

import javax.servlet.*;

import javax.servlet.http.httpservletresponse;

import java.io.ioexception;

 

/**

  * 对事物进行控制 并且 避免接口 直接报漏异常信息

  * 并且过滤频繁请求

  * created by yangchao on 2016/11/4.

  */

public class transactionfilter implements filter {

 

   logger log = logger.getlogger( this .getclass());

 

   @override

   public void init(filterconfig filterconfig) throws servletexception {

   }

 

   @override

   public void dofilter(servletrequest request, servletresponse myresp, filterchain chain) throws ioexception, servletexception {

     string sign = "sign_" + contextlj.getsign(request); // 生成摘要

     string tid = randomutil.getrandomstring( 3 ) + "_" + thread.currentthread().getid(); // 当前线程的身份

     try {

       if (!contextlj.lock(sign, tid)) {

         log.warn( "放弃相同 并发请求" + sign);

         frequentlyerror(myresp);

         return ;

       }

       if (!contextlj.checklock(sign, tid)) {

         log.warn( "加锁验证失败 " + sign + " " + tid);

         frequentlyerror(myresp);

         return ;

       }

       chain.dofilter(request, myresp); // 放行

     } catch (exception e) { // 捕获到异常 进行异常过滤

       log.error( "" , e);

       retrunerrorinfo(myresp);

     } finally {

       contextlj.clent(sign, tid);

     }

   }

 

   /**

    * 频繁请求

    * @param myresp

    */

   private void frequentlyerror(servletresponse myresp) throws ioexception {

     apiresult<object> re = new apiresult<>();

     ((httpservletresponse) myresp).setheader( "content-type" , "text/html;charset=utf-8" );

     re.setmsg( "稍安勿躁,不要频繁请求" );

     re.setcode(apirtncode.api_verify_fail);

     myresp.getwriter().write( new gson().tojson(re));

   }

 

   /**

    * 返回异常信息

    * @param myresp

    */

   private void retrunerrorinfo(servletresponse myresp) throws ioexception {

     apiresult<object> re = new apiresult<>();

     re.setmsg( "server error" );

     // 这里不必理会

     re.setcode(apirtncode.service_error);

     myresp.getwriter().write( new gson().tojson(re));

   }

 

   @override

   public void destroy() {

 

   }

}

程序本身应该还有需要完善的地方, 不过经过一段时间的测试。 这个解决方案还是比较可靠的 并发测试 + 生产环境上 也没有再出现 重复请求的问题

非极端情况下 还是很可靠的

以上所述是小编给大家介绍的java解决分布式环境中高并发环境下数据插入重复问题详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

原文链接:https://blog.csdn.net/qq_22956867/article/details/72529144

查看更多关于详解java解决分布式环境中高并发环境下数据插入重复问题的详细内容...

  阅读:19次