---
title: "Memcached笔记——（四）应对高并发攻击"
author: "wxyfighting"
date: "2013-06-12T09:12:00Z"
tags: []
slug: "memcached"
draft: false
lastmod: "2013-06-12T14:33:03Z"
id: 1885599
url: "https://wxyfighting.iteye.com/blog/1885599"
---

近半个月过得很痛苦，主要是产品上线后，引来无数机器用户恶意攻击，不停的刷新产品各个服务入口，制造垃圾数据，消耗资源。他们的最好成绩，1秒钟可以并发6次，赶在Database入库前，Cache进行Missing Loading前，强占这其中十几毫秒的时间，进行恶意攻击。

为了应对上述情况，做了如下调整：

1. 更新数据时，先写Cache，然后写Database，如果可以，写操作交给队列后续完成。
2. 限制统一帐号，同一动作，同一秒钟并发次数，超过1次不做做动作，返回操作失败。
3. 限制统一用户，每日动作次数，超限返回操作失败。

要完成上述操作，同事给我支招。用Memcached的add方法，就可以很快速的解决问题。不需要很繁琐的开发，也不需要依赖数据库记录，完全内存操作。![](http://snowolf.iteye.com/images/smiles/icon_idea.gif)

以下实现一个判定冲突的方法：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. /\**
02. \*冲突延时1秒
03. \*/
04. publicstaticfinalintMUTEX\_EXP=1;
05. /\**
06. \*冲突键
07. \*/
08. publicstaticfinalStringMUTEX\_KEY\_PREFIX="MUTEX\_";
09. /\**
10. \*冲突判定
11. \*
12. \*@paramkey
13. \*/
14. publicbooleanisMutex(Stringkey){
15. returnisMutex(key,MUTEX\_EXP);
16. }
17. /\**
18. \*冲突判定
19. \*
20. \*@paramkey
21. \*@paramexp
22. \*@returntrue冲突
23. \*/
24. publicbooleanisMutex(Stringkey,intexp){
25. booleanstatus=true;
26. try{
27. if(memcachedClient.add(MUTEX\_KEY\_PREFIX+key,exp,"true")){
28. status=false;
29. }
30. }catch(Exceptione){
31. logger.error(e.getMessage(),e);
32. }
33. returnstatus;
34. }

做个说明：

选项 说明 add 仅当存储空间中不存在键相同的数据时才保存 replace 仅当存储空间中存在键相同的数据时才保存 set 与add和replace不同，无论何时都保存

也就是说，如果add操作返回为true，则认为当前不冲突！![](http://snowolf.iteye.com/images/smiles/icon_smile.gif)

回归场景，恶意用户1秒钟操作6次，遇到上述这个方法，只有乖乖地1秒后再来。别小看这1秒钟，一个数据库操作不过几毫秒。1秒延迟，足以降低系统负载，增加恶意用户成本。

附我用到的基于XMemcached实现：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

001. importnet.rubyeye.xmemcached.MemcachedClient;
002. importorg.apache.log4j.Logger;
003. importorg.springframework.beans.factory.annotation.Autowired;
004. importorg.springframework.stereotype.Component;
005. /\**
006. \*
007. \*@authorSnowolf
008. \*@version1.0
009. \*@since1.0
010. \*/
011. @Component
012. publicclassMemcachedManager{
013. /\**
014. \*缓存时效1天
015. \*/
016. publicstaticfinalintCACHE\_EXP\_DAY=3600\*24;
017. /\**
018. \*缓存时效1周
019. \*/
020. publicstaticfinalintCACHE\_EXP\_WEEK=3600\*24\*7;
021. /\**
022. \*缓存时效1月
023. \*/
024. publicstaticfinalintCACHE\_EXP\_MONTH=3600\*24\*30;
025. /\**
026. \*缓存时效永久
027. \*/
028. publicstaticfinalintCACHE\_EXP\_FOREVER=0;
029. /\**
030. \*冲突延时1秒
031. \*/
032. publicstaticfinalintMUTEX\_EXP=1;
033. /\**
034. \*冲突键
035. \*/
036. publicstaticfinalStringMUTEX\_KEY\_PREFIX="MUTEX\_";
037. /\**
038. \*Loggerforthisclass
039. \*/
040. privatestaticfinalLoggerlogger=Logger
041. .getLogger(MemcachedManager.class);
042. /\**
043. \*MemcachedClient
044. \*/
045. @Autowired
046. privateMemcachedClientmemcachedClient;
047. /\**
048. \*缓存
049. \*
050. \*@paramkey
051. \*@paramvalue
052. \*@paramexp
053. \*失效时间
054. \*/
055. publicvoidcacheObject(Stringkey,Objectvalue,intexp){
056. try{
057. memcachedClient.set(key,exp,value);
058. }catch(Exceptione){
059. logger.error(e.getMessage(),e);
060. }
061. logger.info("CacheObject:\["+key+"]");
062. }
063. /\**
064. \*ShutdowntheMemcachedCilent.
065. \*/
066. publicvoidfinalize(){
067. if(memcachedClient!=null){
068. try{
069. if(!memcachedClient.isShutdown()){
070. memcachedClient.shutdown();
071. logger.debug("ShutdownMemcachedManager...");
072. }
073. }catch(Exceptione){
074. logger.error(e.getMessage(),e);
075. }
076. }
077. }
078. /\**
079. \*清理对象
080. \*
081. \*@paramkey
082. \*/
083. publicvoidflushObject(Stringkey){
084. try{
085. memcachedClient.deleteWithNoReply(key);
086. }catch(Exceptione){
087. logger.error(e.getMessage(),e);
088. }
089. logger.info("FlushObject:\["+key+"]");
090. }
091. /\**
092. \*冲突判定
093. \*
094. \*@paramkey
095. \*/
096. publicbooleanisMutex(Stringkey){
097. returnisMutex(key,MUTEX\_EXP);
098. }
099. /\**
100. \*冲突判定
101. \*
102. \*@paramkey
103. \*@paramexp
104. \*@returntrue冲突
105. \*/
106. publicbooleanisMutex(Stringkey,intexp){
107. booleanstatus=true;
108. try{
109. if(memcachedClient.add(MUTEX\_KEY\_PREFIX+key,exp,"true")){
110. status=false;
111. }
112. }catch(Exceptione){
113. logger.error(e.getMessage(),e);
114. }
115. returnstatus;
116. }
117. /\**
118. \*加载缓存对象
119. \*
120. \*@paramkey
121. \*@return
122. \*/
123. public&lt;T&gt;TloadObject(Stringkey){
124. Tobject=null;
125. try{
126. object=memcachedClient.&lt;T&gt;get(key);
127. }catch(Exceptione){
128. logger.error(e.getMessage(),e);
129. }
130. logger.info("LoadObject:\["+key+"]");
131. returnobject;
132. }
133. }