SpringBoot 限流實現

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

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

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

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

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

限流具體代碼實踐

  • 導入mvn依賴包
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>21.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
</dependencies>
  • 實現redis配置信息
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;
    }
}

當然,你也可以使用普通的jedis.eval方法執行下面的lua腳本命令。

    /**
     * 執行lua腳本命令
    * @author 高國藩
    * @date 2019年6月19日 下午5:48:37
    * @param scriptKey
    * @param keys
    * @param args
    * @return
     */
    public Object eval(String luaScript, ImmutableList<String> keys, String... args) {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = this.getJedis();
            return jedis.eval(luaScript, keys, Arrays.asList(args));
        }
        catch (Exception e) {
            isBroken = true;
        }
        finally {
            release(jedis, isBroken);
        }
        return null;
    }
  • 實現限流注解Class
package com.soul.home.lws.request.conf;

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;

/**
 * 限流注解定義
* @author 高國藩
* @date 2019年6月19日 下午5:09:53
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Limit {

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

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

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

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

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

    /**
     * 限流類型
    * @author 高國藩
    * @date 2019年6月19日 下午5:10:09
    * @return
     */
    LimitType limitType() default LimitType.IP;
}
package com.soul.home.lws.request.conf;

/**
 * 限流分類枚舉
* @author 高國藩
* @date 2019年6月19日 下午5:10:41
 */
public enum LimitType {
    
    /** 自定義key */
    CUSTOMER,
    
    /** 根據請求者IP */
    IP;
}
  • 實現aop攔截器信息

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

package com.soul.home.lws.request.conf;

import com.google.common.collect.ImmutableList;
import com.soul.home.lws.system.exception.RequestLimitException;
import com.soul.home.lws.system.service.RedisService;

import net.sf.json.JSONObject;

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.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 
* @author 高國藩
* @date 2019年6月20日 上午11:48:06
 */
@Aspect
@Configuration
public class LimitInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class);
    
    @Autowired RedisService redisService;

    @Around("execution(public * *(..)) && @annotation(com.soul.home.lws.request.conf.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;
        Integer limitPeriod = limitAnnotation.period();
        Integer 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();
            
            Object resultCount = redisService.eval(luaScript, keys, limitCount.toString(), limitPeriod.toString());
            Number count = Integer.valueOf(resultCount.toString());
            logger.info("Access try count is {} for name={} and key = {}", count, name, key);
            if (count != null && count.intValue() <= limitCount) {
                return pjp.proceed();
            } else {
                sendLimtErrorCodeMessage();
                return null;
            }
        } catch (Throwable e) {
            if (e instanceof RuntimeException) {
                throw new RuntimeException(e.getLocalizedMessage());
            }
            throw new RuntimeException("server exception");
        }
    }
    
    
    /**
     * 拋出請求異常信息,提示請求客戶端
    * @author 高國藩
    * @date 2019年6月20日 上午11:47:42
     */
    private void sendLimtErrorCodeMessage() {
        try {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            HttpServletResponse response = servletRequestAttributes.getResponse();
            if (request == null) {
                throw new RequestLimitException("方法中缺失HttpServletRequest參數");
            }
            response.setCharacterEncoding("UTF-8");  
            response.setContentType("application/json; charset=utf-8");
            Map<String, Object> error = new HashMap<>();
            error.put("ret", -1);
            error.put("errCode", 100);
            error.put("errMsg", "請求頻繁,請稍後重試");
            String str = JSONObject.fromObject(error).toString();
            byte[] bytes = str.getBytes();
            response.setContentLength(bytes.length);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    

    /**
     * 限流LUA腳本命令
    * @author 高國藩
    * @date 2019年6月20日 上午11:47:32
    * @return
     */
    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地址信息(存在反向代理信息和正向代理信息)
    * @author 高國藩
    * @date 2019年6月20日 上午11:48:22
    * @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;
    }
}
  • 實現最終限流
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的值

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