java限流

       高併發訪問時,緩存、限流、降級往往是系統的利劍,在互聯網蓬勃發展的時期,經常會面臨因用戶暴漲導致的請求不可用的情況,甚至引發連鎖反映導致整個系統崩潰。這個時候常見的解決方案之一就是限流了,當請求達到一定的併發數或速率,就進行等待、排隊、降級、拒絕服務等...

限流算法介紹

a、令牌桶算法

令牌桶算法的原理是系統會以一個恆定的速度往桶裏放入令牌,而如果請求需要被處理,則需要先從桶裏獲取一個令牌,當桶裏沒有令牌可取時,則拒絕服務。 當桶滿時,新添加的令牌被丟棄或拒絕。

b、漏桶算法

其主要目的是控制數據注入到網絡的速率,平滑網絡上的突發流量,數據可以以任意速度流入到漏桶中。 漏桶算法提供了一種機制,通過它,突發流量可以被整形以便爲網絡提供一個穩定的流量。 漏桶可以看作是一個帶有常量服務時間的單服務器隊列,如果漏桶爲空,則不需要流出水滴,如果漏桶(包緩存)溢出,那麼水滴會被溢出丟棄

c、計算器限流

計數器限流算法是比較常用一種的限流方案也是最爲粗暴直接的,主要用來限制總併發數,比如數據庫連接池大小、線程池大小、接口訪問併發數等都是使用計數器算法

如:使用 AomicInteger 來進行統計當前正在併發執行的次數,如果超過域值就直接拒絕請求,提示系統繁忙

限流具體代碼實踐

a、屬性配置

在 application.properites 資源文件中添加 redis 相關的配置項

spring.redis.host=192.168.68.110
spring.redis.port=6379
spring.redis.password=123456

b、RedisTemplate

默認情況下 spring-boot-data-redis 爲我們提供了StringRedisTemplate 但是滿足不了其它類型的轉換,所以還是得自己去定義其它類型的模板

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

/**
 * redis配置
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Serializable> limitRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

c、Limit 註解

具體代碼如下

import com.carry.enums.LimitType;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 限流
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Limit {

    /**
     * 資源的名字
     *
     * @return String
     */
    String name() default "";

    /**
     * 資源的key
     *
     * @return String
     */
    String key() default "";

    /**
     * Key的prefix
     *
     * @return String
     */
    String prefix() default "";

    /**
     * 給定的時間段
     * 單位秒
     *
     * @return int
     */
    int period();

    /**
     * 最多的訪問限制次數
     *
     * @return int
     */
    int count();

    /**
     * 類型
     *
     * @return LimitType
     */
    LimitType limitType() default LimitType.CUSTOMER;
}
package com.carry.enums;

public enum LimitType {
    /**
     * 自定義key
     */
    CUSTOMER,
    /**
     * 根據請求者IP
     */
    IP;
}

e、Limit 攔截器(AOP)

我們可以通過編寫 Lua 腳本實現自己的API,核心就是調用 execute 方法傳入我們的 Lua 腳本內容,然後通過返回值判斷是否超出我們預期的範圍,超出則給出錯誤提示。

import com.carry.annotation.Limit;
import com.carry.enums.LimitType;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.Method;


@Aspect
@Configuration
public class LimitInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class);

    private final RedisTemplate<String, Serializable> limitRedisTemplate;

    @Autowired
    public LimitInterceptor(RedisTemplate<String, Serializable> limitRedisTemplate) {
        this.limitRedisTemplate = limitRedisTemplate;
    }


    @Around("execution(public * *(..)) && @annotation(com.carry.annotation.Limit)")
    public Object interceptor(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        Limit limitAnnotation = method.getAnnotation(Limit.class);
        LimitType limitType = limitAnnotation.limitType();
        String name = limitAnnotation.name();
        String key;
        int limitPeriod = limitAnnotation.period();
        int limitCount = limitAnnotation.count();
        switch (limitType) {
            case IP:
                key = getIpAddress();
                break;
            case CUSTOMER:
                key = limitAnnotation.key();
                break;
            default:
                key = StringUtils.upperCase(method.getName());
        }
        ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key));
        try {
            String luaScript = buildLuaScript();
            RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
            Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod);
            logger.info("Access try count is {} for name={} and key = {}", count, name, key);
            if (count != null && count.intValue() <= limitCount) {
                return pjp.proceed();
            } else {
                throw new RuntimeException("You have been dragged into the blacklist");
            }
        } catch (Throwable e) {
            if (e instanceof RuntimeException) {
                throw new RuntimeException(e.getLocalizedMessage());
            }
            throw new RuntimeException("server exception");
        }
    }

    /**
     * 限流 腳本
     *
     * @return lua腳本
     */
    public String buildLuaScript() {
        StringBuilder lua = new StringBuilder();
        lua.append("local c");
        lua.append("\nc = redis.call('get',KEYS[1])");
        // 調用不超過最大值,則直接返回
        lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then");
        lua.append("\nreturn c;");
        lua.append("\nend");
        // 執行計算器自加
        lua.append("\nc = redis.call('incr',KEYS[1])");
        lua.append("\nif tonumber(c) == 1 then");
        // 從第一次調用開始限流,設置對應鍵值的過期
        lua.append("\nredis.call('expire',KEYS[1],ARGV[2])");
        lua.append("\nend");
        lua.append("\nreturn c;");
        return lua.toString();
    }

    private static final String UNKNOWN = "unknown";

    /**
     * 獲取IP地址
     * @return
     */
    public String getIpAddress() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}

 

 

f、控制層

在接口上添加 @Limit() 註解,如下代碼會在 Redis 中生成過期時間爲 100s 的 key = test 的記錄,特意定義了一個 AtomicInteger 用作測試

import com.carry.annotation.Limit;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;


@RestController
public class LimiterController {

    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();

    @Limit(key = "test", period = 100, count = 10, name="resource", prefix = "limit")
    @GetMapping("/test")
    public int testLimiter() {
        // 意味着100S內最多可以訪問10次
        return ATOMIC_INTEGER.incrementAndGet();
    }
}

 

注意:上面例子保存在redis中的key值應該爲“limittest”,即@Limit中prefix的值+key的值

測試

我們在postman中快速訪問localhost:8080/test,當訪問數超過10時出現以下結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章