Springboot使用redis實現接口Api限流的示例代碼

前言

該篇介紹的內容如題,就是利用redis實現接口的限流(  某時間范圍內 最大的訪問次數 ) 。

正文 

慣例,先看下我們的實戰目錄結構:

首先是pom.xml 核心依賴:

 <!--用於redis數據庫連接-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--用於redis lettuce 連接池pool使用-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

然後是application.yml裡面的redis接入配置:

spring:
  redis:
    lettuce:
      pool:
        #連接池最大連接數 使用負值代表無限制 默認為8
        max-active: 10
        #最大空閑連接 默認8
        max-idle: 10
        #最小空閑連接 默認0
        min-idle: 1
    host: 127.0.0.1
    password: 123456
    port: 6379
    database: 0
    timeout: 2000ms
server:
  port: 8710

redis的配置類, RedisConfig.java:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
 
import static org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig;
 
/**
 * @Author: JCccc
 * @CreateTime: 2018-09-11
 * @Description:
 */
@Configuration
@EnableCaching
public class RedisConfig {
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration cacheConfiguration =
                defaultCacheConfig()
                        .disableCachingNullValues()
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer(Object.class)));
        return RedisCacheManager.builder(connectionFactory).cacheDefaults(cacheConfiguration).build();
    }
 
 
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        //序列化設置 ,這樣為瞭存儲操作對象時正常顯示的數據,也能正常存儲和獲取
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate;
    }
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }
 
}

自定義註解:

import java.lang.annotation.*;
 
/**
 * @Author JCccc
 * @Description
 * @Date 2021/7/23 11:46
 */
@Inherited
@Documented
@Target({ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestLimit {
 
    /**
     * 時間內  秒為單位
     */
    int second() default 10;
 
 
 
    /**
     *  允許訪問次數
     */
    int maxCount() default 5;
 
 
    //默認效果 : 10秒內 對於使用該註解的接口,隻能總請求訪問數 不能大於 5次
 
}

接下來是攔截器 RequestLimitInterceptor.java:

攔截接口的方式 是通過 ip地址+接口url ,做時間內的訪問計數

import com.elegant.testdemo.annotation.RequestLimit;
import com.elegant.testdemo.utils.IpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
 
/**
 * @Author JCccc
 * @Description
 * @Date 2021/7/23 11:49
 */
 
@Component
public class RequestLimitInterceptor implements HandlerInterceptor {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
 
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                // 獲取RequestLimit註解
                RequestLimit requestLimit = handlerMethod.getMethodAnnotation(RequestLimit.class);
                if (null==requestLimit) {
                    return true;
                }
                //限制的時間范圍
                int seconds = requestLimit.second();
                //時間內的 最大次數
                int maxCount = requestLimit.maxCount();
                String ipAddr = IpUtil.getIpAddr(request);
                // 存儲key
                String key =  ipAddr+":"+request.getContextPath() + ":" + request.getServletPath();
                // 已經訪問的次數
                Integer count = (Integer) redisTemplate.opsForValue().get(key);
                log.info("檢測到目前ip對接口={}已經訪問的次數", request.getServletPath() , count);
                if (null == count || -1 == count) {
                    redisTemplate.opsForValue().set(key, 1, seconds, TimeUnit.SECONDS);
                    return true;
                }
                if (count < maxCount) {
                    redisTemplate.opsForValue().increment(key);
                    return true;
                }
                log.warn("請求過於頻繁請稍後再試");
                returnData(response);
                return false;
            }
            return true;
        } catch (Exception e) {
            log.warn("請求過於頻繁請稍後再試");
            e.printStackTrace();
        }
        return true;
    }
 
    public void returnData(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        //這裡傳提示語可以改成自己項目的返回數據封裝的類
        response.getWriter().println(objectMapper.writeValueAsString("請求過於頻繁請稍後再試"));
        return;
    }
 
}

接下來是 攔截器的配置 WebConfig.java:

import com.elegant.testdemo.interceptor.RequestLimitInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
/**
 * @Author JCccc
 * @Description
 * @Date 2021/7/23 11:52
 */
 
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private RequestLimitInterceptor requestLimitInterceptor;
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestLimitInterceptor)
 
                //攔截所有請求路徑
                .addPathPatterns("/**")
                //再設置 放開哪些路徑
                .excludePathPatterns("/static/**","/auth/login");
    }
 
}

最後還有兩個工具類

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
 
/**
 * @Author : JCccc
 * @CreateTime : 2018-11-23
 * @Description :
 * @Point: Keep a good mood
 **/
public class IpUtil {
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根據網卡取本機配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 對於通過多個代理的情況,第一個IP為客戶端真實IP,多個IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();
 
        return ipAddress;
    }
}

RedisUtil :

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
 
 
@Component
public class RedisUtils {
 
 
    @Autowired
 
    private RedisTemplate redisTemplate;
 
 
    /**
     * 寫入String型 [ 鍵,值]
     *
     * @param key
     * @param value
     * @return
     */
 
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
 
    }
 
 
 
  /**
     * 寫入String型,順便帶有過期時間 [ 鍵,值]
     *
     * @param key
     * @param value
     * @return
     */
 
    public boolean setWithTime(final String key, Object value,int seconds) {
        boolean result = false;
        try {
 
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value,seconds, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
 
    }
 
 
 
    /**
     * 批量刪除對應的value
     *
     * @param keys
     */
 
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }
 
    /**
     * 批量刪除key
     *
     * @param pattern
     */
 
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }
 
    /**
     * 刪除對應的value
     *
     * @param key
     */
 
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }
 
 
    /**
     * 判斷緩存中是否有對應的value
     *
     * @param key
     * @return
     */
 
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
 
 
    /**
     * 讀取緩存
     *
     * @param key
     * @return
     */
 
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
 
 
    /**
     * 哈希 添加
     * hash 一個鍵值(key->value)對集合
     *
     * @param key
     * @param hashKey
     * @param value
     */
 
    public void hmSet(String key, Object hashKey, Object value) {
 
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
 
        hash.put(key, hashKey, value);
 
    }
 
 
    /**
     * Hash獲取數據
     *
     * @param key
     * @param hashKey
     * @return
     */
 
    public Object hmGet(String key, Object hashKey) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash.get(key, hashKey);
 
    }
 
 
    /**
     * 列表添加
     * list:lpush key value1
     *
     * @param k
     * @param v
     */
 
    public void lPush(String k, Object v) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k, v);
    }
 
 
    /**
     * 列表List獲取
     * lrange: key 0 10 (讀取的個數 從0開始 讀取到下標為10 的數據)
     *
     * @param k
     * @param l
     * @param l1
     * @return
     */
 
    public List<Object> lRange(String k, long l, long l1) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k, l, l1);
    }
 
 
    /**
     * Set集合添加
     *
     * @param key
     * @param value
     */
 
    public void add(String key, Object value) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key, value);
    }
 
 
    /**
     * Set 集合獲取
     *
     * @param key
     * @return
     */
 
    public Set<Object> setMembers(String key) {
 
        SetOperations<String, Object> set = redisTemplate.opsForSet();
 
        return set.members(key);
 
    }
 
 
    /**
     * Sorted set :有序集合添加
     *
     * @param key
     * @param value
     * @param scoure
     */
 
    public void zAdd(String key, Object value, double scoure) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key, value, scoure);
    }
 
 
    /**
     * Sorted set:有序集合獲取
     *
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
 
    public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
 
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
 
        return zset.rangeByScore(key, scoure, scoure1);
 
    }
 
 
    /**
     * 根據key獲取Set中的所有值
     *
     * @param key 鍵
     * @return
     */
 
    public Set<Integer> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
 
    /**
     * 根據value從一個set中查詢,是否存在
     *
     * @param key   鍵
     * @param value 值
     * @return true 存在 false不存在
     */
 
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 
}

最後寫個測試接口

TestController.java

import com.elegant.testdemo.annotation.RequestLimit;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
 
/**
 * @Author JCccc
 * @Description
 * @Date 2021/7/23 11:55
 */
@RestController
public class TestController {
 
    @GetMapping("/test")
    @RequestLimit(maxCount = 3,second = 60)
    public String test() {
        return "你好,如果對你有幫助,請點贊加關註。";
    }

}

這個/test接口的註解,我們設置的是 60秒內 最大訪問次數為 3次 (實際應用應該是根據具體接口做相關的次數限制。)

然後使用postman測試一下接口:

前面三次都是請求通過的:

第四次:

 ok,就先到這。

到此這篇關於Springboot使用redis實現接口Api限流的示例代碼的文章就介紹到這瞭,更多相關Springboot redis接口限流內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: