Springboot搭配Redis实现接口限流

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 介绍限流的需求出现在许多常见的场景中:秒杀活动,有人使用软件恶意刷单抢货,需要限流防止机器参与活动某 api 被各式各样系统广泛调用,严重消耗网络、内存等资源,需要合理限流淘宝获取 ip 所在城市接口、微信公众号识别微信用户等开发接口,免费提供给用户时需要限流,更具有实时性和准确性的接口需要付费。

限流的思路

通过 ip:api 路径 的作为 key ,访问次数为 value 的方式对某一用户的某一请求进行唯一标识
每次访问的时候判断 key 是否存在,是否 count 超过了限制的访问次数
若访问超出限制,则应 response 返回 msg: 请求过于频繁 给前端予以展示
代码示例

准备一个springboot项目
必需pom依赖



org.springframework.boot
spring-boot-starter-web



org.springframework.boot
spring-boot-starter-data-redis


redis.clients
jedis
2.9.3

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//运行时执行
@Retention(RetentionPolicy.RUNTIME)
//指定注解的适用目标 表示该注解适用于方法上。
@Target(ElementType.METHOD)
public @interface AccessLimit {
/**

 * 限制时长 秒
 */
int seconds();

/**
 * 最大访问次数
 */
int maxCount();

/**
 * 是否需要登录
 */
boolean needLogin() default true;

}
redis工具类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.Protocol;
import redis.clients.util.SafeEncoder;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

@Autowired
private RedisTemplate<String, Object> redisTemplate;

// =============================common============================
/**
 * 指定缓存失效时间
 * @param key 键
 * @param time 时间(秒)
 * @return
 */
public boolean expire(String key, long time) {
    try {
        if (time > 0) {
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 根据key 获取过期时间
 * @param key 键 不能为null
 * @return 时间(秒) 返回0代表为永久有效
 */
public long getExpire(String key) {
    return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}

/**
 * 判断key是否存在
 * @param key 键
 * @return true 存在 false不存在
 */
public boolean hasKey(String key) {
    try {
        return redisTemplate.hasKey(key);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 删除缓存
 * @param key 可以传一个值 或多个
 */
@SuppressWarnings("unchecked")
public void del(String... key) {
    if (key != null && key.length > 0) {
        if (key.length == 1) {
            redisTemplate.delete(key[0]);
        } else {
            redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
        }
    }
}

/**
 * 删除缓存
 * @param keys 可以传一个值 或多个
 */
public void del(Collection<String> keys) {
    if (CollectionUtils.isEmpty(keys)) {
        redisTemplate.delete(keys);
    }
}

// ============================String=============================
/**
 * 普通缓存获取
 * @param key 键
 * @return 值
 */
public Object get(String key) {
    return key == null ? null : redisTemplate.opsForValue().get(key);
}

/**
 * 普通缓存放入
 * @param key 键
 * @param value 值
 * @return true成功 false失败
 */
public boolean set(String key, Object value) {
    try {
        redisTemplate.opsForValue().set(key, value);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 普通缓存放入并设置时间
 * @param key 键
 * @param value 值
 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
 * @return true成功 false 失败
 */
public boolean set(String key, Object value, long time) {
    try {
        if (time > 0) {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        } else {
            set(key, value);
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 递增
 * @param key 键
 * @param delta 要增加几(大于0)
 * @return
 */
public long incr(String key, long delta) {
    if (delta < 0) {
        throw new RuntimeException("递增因子必须大于0");
    }
    return redisTemplate.opsForValue().increment(key, delta);
}

/**
 * 递减
 * @param key 键
 * @param delta 要减少几(小于0)
 * @return
 */
public long decr(String key, long delta) {
    if (delta < 0) {
        throw new RuntimeException("递减因子必须大于0");
    }
    return redisTemplate.opsForValue().increment(key, -delta);
}

// ================================Map=================================
/**
 * HashGet
 * @param key 键 不能为null
 * @param item 项 不能为null
 * @return 值
 */
public Object hget(String key, String item) {
    return redisTemplate.opsForHash().get(key, item);
}

/**
 * 获取hashKey对应的所有键值
 * @param key 键
 * @return 对应的多个键值
 */
public Map<Object, Object> hmget(String key) {
    return redisTemplate.opsForHash().entries(key);
}

/**
 * HashSet
 * @param key 键
 * @param map 对应多个键值
 * @return true 成功 false 失败
 */
public boolean hmset(String key, Map<String, Object> map) {
    try {
        redisTemplate.opsForHash().putAll(key, map);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * HashSet 并设置时间
 * @param key 键
 * @param map 对应多个键值
 * @param time 时间(秒)
 * @return true成功 false失败
 */
public boolean hmset(String key, Map<String, Object> map, long time) {
    try {
        redisTemplate.opsForHash().putAll(key, map);
        if (time > 0) {
            expire(key, time);
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 向一张hash表中放入数据,如果不存在将创建
 * @param key 键
 * @param item 项
 * @param value 值
 * @return true 成功 false失败
 */
public boolean hset(String key, String item, Object value) {
    try {
        redisTemplate.opsForHash().put(key, item, value);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 向一张hash表中放入数据,如果不存在将创建
 * @param key 键
 * @param item 项
 * @param value 值
 * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
 * @return true 成功 false失败
 */
public boolean hset(String key, String item, Object value, long time) {
    try {
        redisTemplate.opsForHash().put(key, item, value);
        if (time > 0) {
            expire(key, time);
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 删除hash表中的值
 * @param key 键 不能为null
 * @param item 项 可以使多个 不能为null
 */
public void hdel(String key, Object... item) {
    redisTemplate.opsForHash().delete(key, item);
}

/**
 * 删除hash表中的值
 * @param key 键 不能为null
 * @param items 项 可以使多个 不能为null
 */
public void hdel(String key, Collection items) {
    redisTemplate.opsForHash().delete(key, items.toArray());
}

/**
 * 判断hash表中是否有该项的值
 * @param key 键 不能为null
 * @param item 项 不能为null
 * @return true 存在 false不存在
 */
public boolean hHasKey(String key, String item) {
    return redisTemplate.opsForHash().hasKey(key, item);
}

/**
 * hash递增 如果不存在,就会创建一个 并把新增后的值返回
 * @param key 键
 * @param item 项
 * @param delta 要增加几(大于0)
 * @return
 */
public double hincr(String key, String item, double delta) {
    if (delta < 0) {
        throw new RuntimeException("递增因子必须大于0");
    }
    return redisTemplate.opsForHash().increment(key, item, delta);
}

/**
 * hash递减
 * @param key 键
 * @param item 项
 * @param delta 要减少记(小于0)
 * @return
 */
public double hdecr(String key, String item, double delta) {
    if (delta < 0) {
        throw new RuntimeException("递减因子必须大于0");
    }
    return redisTemplate.opsForHash().increment(key, item, -delta);
}

// ============================set=============================
/**
 * 根据key获取Set中的所有值
 * @param key 键
 * @return
 */
public Set<Object> 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;
    }
}

/**
 * 将数据放入set缓存
 * @param key 键
 * @param values 值 可以是多个
 * @return 成功个数
 */
public long sSet(String key, Object... values) {
    try {
        return redisTemplate.opsForSet().add(key, values);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

/**
 * 将数据放入set缓存
 * @param key 键
 * @param values 值 可以是多个
 * @return 成功个数
 */
public long sSet(String key, Collection values) {
    try {
        return redisTemplate.opsForSet().add(key, values.toArray());
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

/**
 * 将set数据放入缓存
 * @param key 键
 * @param time 时间(秒)
 * @param values 值 可以是多个
 * @return 成功个数
 */
public long sSetAndTime(String key, long time, Object... values) {
    try {
        Long count = redisTemplate.opsForSet().add(key, values);
        if (time > 0)
            expire(key, time);
        return count;
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

/**
 * 获取set缓存的长度
 * @param key 键
 * @return
 */
public long sGetSetSize(String key) {
    try {
        return redisTemplate.opsForSet().size(key);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

/**
 * 移除值为value的
 * @param key 键
 * @param values 值 可以是多个
 * @return 移除的个数
 */
public long setRemove(String key, Object... values) {
    try {
        Long count = redisTemplate.opsForSet().remove(key, values);
        return count;
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

// ===============================list=================================
/**
 * 获取list缓存的内容
 * @param key 键
 * @param start 开始
 * @param end 结束 0 到 -1代表所有值
 * @return
 */
public List<Object> lGet(String key, long start, long end) {
    try {
        return redisTemplate.opsForList().range(key, start, end);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

/**
 * 获取list缓存的长度
 * @param key 键
 * @return
 */
public long lGetListSize(String key) {
    try {
        return redisTemplate.opsForList().size(key);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

/**
 * 通过索引 获取list中的值
 * @param key 键
 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
 * @return
 */
public Object lGetIndex(String key, long index) {
    try {
        return redisTemplate.opsForList().index(key, index);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

/**
 * 将list放入缓存
 * @param key 键
 * @param value 值
 * @return
 */
public boolean lSet(String key, Object value) {
    try {
        redisTemplate.opsForList().rightPush(key, value);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 将list放入缓存
 * @param key 键
 * @param value 值
 * @param time 时间(秒)
 * @return
 */
public boolean lSet(String key, Object value, long time) {
    try {
        redisTemplate.opsForList().rightPush(key, value);
        if (time > 0)
            expire(key, time);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 将list放入缓存
 * @param key 键
 * @param value 值
 * @return
 */
public boolean lSet(String key, List<Object> value) {
    try {
        redisTemplate.opsForList().rightPushAll(key, value);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 将list放入缓存
 *
 * @param key 键
 * @param value 值
 * @param time 时间(秒)
 * @return
 */
public boolean lSet(String key, List<Object> value, long time) {
    try {
        redisTemplate.opsForList().rightPushAll(key, value);
        if (time > 0)
            expire(key, time);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 根据索引修改list中的某条数据
 * @param key 键
 * @param index 索引
 * @param value 值
 * @return
 */
public boolean lUpdateIndex(String key, long index, Object value) {
    try {
        redisTemplate.opsForList().set(key, index, value);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/**
 * 移除N个值为value
 * @param key 键
 * @param count 移除多少个
 * @param value 值
 * @return 移除的个数
 */
public long lRemove(String key, long count, Object value) {
    try {
        Long remove = redisTemplate.opsForList().remove(key, count, value);
        return remove;
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

/**
 * RedisTemplate 实现 setnx exptime (扩展 redisTemplate.setIfAbsent)
 *
 * 之前用 redisTemplate 实现setnx exptime 时 是分两步的
 * 1. redisTemplate.setIfAbsent
 * 2. redisTemplate.expire
 * 这样的不是原子性的 可能在第一步与第二步之间 重新发布了或者服务器重启了
 * 这个key就永远不会消失了 可以采用以下的方法
 *
 * @param key
 * @param value
 * @param exptime
 * @return
 */
public boolean setIfAbsent(final String key, final Serializable value, final long exptime) {
    Boolean b = (Boolean) redisTemplate.execute(new RedisCallback<Boolean>() {
        @Override
        public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
            RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
            RedisSerializer keySerializer = redisTemplate.getKeySerializer();
            Object obj = connection.execute("set", keySerializer.serialize(key),
                    valueSerializer.serialize(value),
                    SafeEncoder.encode("NX"),
                    //EX 秒,PX 毫秒
                    SafeEncoder.encode("EX"),
                    Protocol.toByteArray(exptime));
            return obj != null;
        }
    });
    return b;
}

}
主拦截器

import com.example.demo.service.AccessLimit;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AccessLimitInterceptor implements HandlerInterceptor {

@Resource
private RedisUtil redisUtil;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //拿到限流注解类的参数
        AccessLimit accessLimit = handlerMethod.getMethodAnnotation(AccessLimit.class);
        if(accessLimit==null){
            return true;
        }
        //时间
        int seconds = accessLimit.seconds();
        //最大次数
        int maxCount = accessLimit.maxCount();
        boolean needLogin = accessLimit.needLogin();

        if(needLogin){
         //判断是否登录
        }

        //获取访问ip和路径
        String ip=request.getRemoteAddr();
        String key=ip+":"+request.getServletPath();

        Integer count = (Integer)redisUtil.get(key);
        //首次进入
        if(count==null||-1==count){
            redisUtil.set(key,1);
            //设置过期时间
            redisUtil.expire(key,seconds);
            return true;
        }

        //如果访问次数<最大次数,则做加1操作
        if(count<maxCount){
            redisUtil.incr(key,1);
            return true;
        }

        //此时访问次数大于等于最大次数
        if(count>=maxCount){
            System.out.println("已经达到该接口限制最大次数========"+count);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("请求过于频繁,请稍后再试!");
            return false;
        }
    }
    return true;
}

}
注册拦截器
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;

@Configuration
public class InteceptorConfig implements WebMvcConfigurer {

@Autowired
private AccessLimitInterceptor accessLimitInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(accessLimitInterceptor)
            //添加限流拦截的接口路径
            .addPathPatterns("/access/accessLimit")
            .addPathPatterns("/main/hello")
            //添加不限流拦截的路径
            .excludePathPatterns("/access/login");
}

}
控制层
import com.example.demo.service.AccessLimit;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("access")
public class AccessController {

@ResponseBody
@GetMapping("accessLimit")
@AccessLimit(seconds = 60,maxCount = 5)
public String accessLimit(){
    return "Hellp world!";
}

}
@RestController
@RequestMapping("/main")
@Slf4j
public class MainCOntroller {

@Autowired
StringRedisTemplate redisTemplate;

@GetMapping("/hello")
@AccessLimit(seconds = 10,maxCount = 2)
public String helloo(){
    return "你好啊";
}

}
启动测试:
可以看到,两个接口都在限制的时间内有一定数量的访问限制,在redis里也能找到响应的key,从而实现了简单的接口限流

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
15小时前
|
JSON NoSQL Java
深入浅出Redis(十三):SpringBoot整合Redis客户端
深入浅出Redis(十三):SpringBoot整合Redis客户端
|
15小时前
|
Java Spring
spring boot访问接口报500
spring boot访问接口报500
13 2
|
15小时前
|
缓存 NoSQL Java
springboot业务开发--springboot集成redis解决缓存雪崩穿透问题
该文介绍了缓存使用中可能出现的三个问题及解决方案:缓存穿透、缓存击穿和缓存雪崩。为防止缓存穿透,可校验请求数据并缓存空值;缓存击穿可采用限流、热点数据预加载或加锁策略;缓存雪崩则需避免同一时间大量缓存失效,可设置随机过期时间。文章还提及了Spring Boot中Redis缓存的配置,包括缓存null值、使用前缀和自定义过期时间,并提供了改造代码以实现缓存到期时间的个性化设置。
|
15小时前
|
存储 NoSQL Java
Spring Boot与Redis:整合与实战
【4月更文挑战第29天】Redis,作为一个高性能的键值存储数据库,广泛应用于缓存、消息队列、会话存储等多种场景中。在Spring Boot应用中整合Redis可以显著提高数据处理的效率和应用的响应速度。
29 0
|
15小时前
|
Java Maven Kotlin
[AIGC] 请你写一遍博客介绍 “使用idea+kotinlin+springboot+maven 结合开发一个简单的接口“,输出markdown格式,用中文回答,请尽可能详细
[AIGC] 请你写一遍博客介绍 “使用idea+kotinlin+springboot+maven 结合开发一个简单的接口“,输出markdown格式,用中文回答,请尽可能详细
|
15小时前
|
存储 监控 负载均衡
保证Redis的高可用性是一个涉及多个层面的任务,主要包括数据持久化、复制与故障转移、集群化部署等方面
【5月更文挑战第15天】保证Redis高可用性涉及数据持久化、复制与故障转移、集群化及优化策略。RDB和AOF是数据持久化方法,哨兵模式确保故障自动恢复。Redis Cluster实现分布式部署,提高负载均衡和容错性。其他措施包括身份认证、多线程、数据压缩和监控报警,以增强安全性和稳定性。通过综合配置与监控,可确保Redis服务的高效、可靠运行。
7 2
|
15小时前
|
存储 NoSQL Redis
Redis源码、面试指南(5)多机数据库、复制、哨兵、集群(下)
Redis源码、面试指南(5)多机数据库、复制、哨兵、集群
7 1
|
15小时前
|
监控 NoSQL Redis
Redis源码、面试指南(5)多机数据库、复制、哨兵、集群(上)
Redis源码、面试指南(5)多机数据库、复制、哨兵、集群
15 0
|
15小时前
|
存储 监控 NoSQL
Redis哨兵&分片集群
Redis哨兵&分片集群
8 0
|
15小时前
|
NoSQL 算法 Java
深入浅出Redis(八):Redis的集群模式
深入浅出Redis(八):Redis的集群模式