https://blog.csdn.net/qq_32447301/article/details/86659474
一、限流操作:
為什么限流,是防止用戶惡意刷新接口,因為部署在外部服務器,並且我們采用websocket的接口實現的,公司沒有對硬件升級,導致程序時長崩潰,為了解決這個問題,請教公司的大佬,提出一個方案,限流操作。但是最后找到原因所在,解決了,吞吐量1萬6左右,用的測試服務器,進行測試的,我開發的筆記本進行壓測,工具是Jmeter,結果我的電腦未響應,卡了,服務器還沒有掛。
限流那些方法
常見的限流:
1、Netflix的hystrix
2、阿里系開源的sentinel
3、說白了限流,為了處理高並發接口那些方式:隊列,線程,線程池,消息隊列、 kafka、中間件、sentinel:直接拒絕、Warm Up、勻速排隊等
技術層面:
1、判斷是否有相同的請求,可以通過自身緩存擋住相同請求
2、用負載均衡,比如nginx
3、用緩存數據庫,把熱點數據get到緩存中,redis,ES
4、善於使用連接池
業務層面:
1、加入交互,排隊等待
二、應用級別限流與限流實現:
方法一、使用google的guava,令牌桶算法實現:平滑突發限流 ( SmoothBursty) 、平滑預熱限流 ( SmoothWarmingUp) 實現
<!--Java項目廣泛依賴 的核心庫-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
package com.citydo.dialogue.controller;
import com.google.common.util.concurrent.RateLimiter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
@RestController
public class HomeController {
// 這里的1表示每秒允許處理的量為10個
private RateLimiter limiter = RateLimiter.create(10.0);
//RateLimiter.create(doublepermitsPerSecond, long warmupPeriod, TimeUnit unit);
//RateLimiter limiter = RateLimiter.create(5, 1000, TimeUnit.MILLISECONDS);
//permitsPerSecond: 表示 每秒新增 的令牌數
// warmupPeriod: 表示在從 冷啟動速率 過渡到 平均速率 的時間間隔
@GetMapping("/test/{name}")
public String Test(@PathVariable("name") String name){
// 請求RateLimiter, 超過permits會被阻塞
final double acquire = limiter.acquire();
System.out.println("--------"+acquire);
//判斷double是否為空或者為0
if(acquire>=(-1e-6)&&acquire<=(1e-6)){
return name;
}else{
return "操作太頻繁";
}
}
}
這個有點類似與QPS流量控制:
當 QPS 超過某個閾值的時候,則采取措施進行流量控制。
直接拒絕:
方式是默認的流量控制方式,當QPS超過任意規則的閾值后,新的請求就會被立即拒絕,拒絕方式為拋出Exception或者返回值404。這種方式適用於對系統處理能力確切已知的情況下,比如通過壓測確定了系統的准確水位時。
方法二、請求一次redis增加1,key可以是IP+時間或者一個標識+時間,沒有就創建,需要設置過期時間
設置攔截器:
package com.citydo.dialogue.config; import com.citydo.dialogue.service.AccessLimitInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /** * 攔截器配置 * @author nick */ @Configuration public class InterceptorConfig extends WebMvcConfigurationSupport { @Override public void addInterceptors(InterceptorRegistry registry) { //addPathPatterns 添加攔截規則 registry.addInterceptor(new AccessLimitInterceptor()) //添加需要攔截請求的路徑 .addPathPatterns("/**"); //swagger2 放行 .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**"); //.excludePathPatterns("/*") //去除攔截請求的路徑 } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/"); } }
攔截方法
package com.citydo.dialogue.service; import com.citydo.dialogue.entity.AccessLimit; import com.citydo.dialogue.utils.IpUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; public class AccessLimitInterceptor implements HandlerInterceptor { //使用RedisTemplate操作redis @Autowired private RedisTemplate<String, Integer> redisTemplate; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); if (!method.isAnnotationPresent(AccessLimit.class)) { return true; } AccessLimit accessLimit = method.getAnnotation(AccessLimit.class); if (accessLimit == null) { return true; } int limit = accessLimit.limit(); int sec = accessLimit.sec(); String key = IpUtil.getIpAddr(request) + request.getRequestURI(); //資源唯一標識 String formatDate=new SimpleDateFormat("yyyyMMddHHmm").format(new Date()); //String key="request_"+formatDate; Integer maxLimit = redisTemplate.opsForValue().get(key); if (maxLimit == null) { //set時一定要加過期時間 redisTemplate.opsForValue().set(key, 1, sec, TimeUnit.SECONDS); } else if (maxLimit < limit) { redisTemplate.opsForValue().set(key, maxLimit + 1, sec, TimeUnit.SECONDS); } else { output(response, "請求太頻繁!"); return false; } } return true; } public void output(HttpServletResponse response, String msg) throws IOException { response.setContentType("application/json;charset=UTF-8"); ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); outputStream.write(msg.getBytes("UTF-8")); } catch (IOException e) { e.printStackTrace(); } finally { outputStream.flush(); outputStream.close(); } } @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 { } }
可以設置成注解,當然也可以直接添加參數
package com.citydo.dialogue.entity; import java.lang.annotation.*; @Inherited @Documented @Target({ElementType.FIELD,ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface AccessLimit { //標識 指定sec時間段內的訪問次數限制 int limit() default 5; //標識 時間段 int sec() default 5; }
redis編寫配置
package com.citydo.dialogue.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * 解決redis亂碼問題 * 解決配置問題 * @author nick */ @Configuration public class RedisConfig { /** * 此方法解決存儲亂碼 */ @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>(); template.setConnectionFactory(redisConnectionFactory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer()); template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); template.afterPropertiesSet(); return template; } }
方法三、分布式限流,分布式限流最關鍵的是要將限流服務做成原子化,而解決方案可以使用redis+lua或者nginx+lua技術進行實現。
方法四、可以使用池化技術來限制總資源數:連接池、線程池。比如分配給每個應用的數據庫連接是 100,那么本應用最多可以使用 100 個資源,超出了可以 等待 或者 拋異常。
方法五、限流總並發/連接/請求數,如果你使用過 Tomcat,其 Connector 其中一種配置有如下幾個參數:
maxThreads:
Tomcat 能啟動用來處理請求的 最大線程數,如果請求處理量一直遠遠大於最大線程數,可能會僵死。
maxConnections:
瞬時最大連接數,超出的會 排隊等待。
acceptCount:
如果 Tomcat 的線程都忙於響應,新來的連接會進入 隊列排隊,如果 超出排隊大小,則 拒絕連接。
方法六、限流某個接口的總並發/請求數,使用 Java 中的 AtomicLong,示意代碼:
try{ if(atomic.incrementAndGet() > 限流數) { //拒絕請求 } else { //處理請求 } } finally { atomic.decrementAndGet(); }
方法七、 限流某個接口的時間窗請求數使用 Guava 的 Cache,示意代碼:
LoadingCache counter = CacheBuilder.newBuilder()
.expireAfterWrite(2, TimeUnit.SECONDS)
.build(newCacheLoader() {
@Override
public AtomicLong load(Long seconds) throws Exception {
return newAtomicLong(0);
}
});
longlimit =1000;
while(true) {
// 得到當前秒
long currentSeconds = System.currentTimeMillis() /1000;
if(counter.get(currentSeconds).incrementAndGet() > limit) {
System.out.println("限流了: " + currentSeconds);
continue;
}
// 業務處理
不管哪種目的是為了,進行限流操作。
參考:https://blog.csdn.net/fanrenxiang/article/details/80683378
參考:https://mp.weixin.qq.com/s/2_oDGJiI1GhaNYnaeL7Qpg
源碼:https://github.com/863473007/springboot_current_limiting
