??????? 最近遇上个需求,有个接口需要根据请求的id来限制访问间隔不得小于10秒,记录一下解决方案。
??????? 首先自定义一个注解
/**
* @author mxm
* @Date: 2020/08/18
* @Description: 接口注解类
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AccessLimit {
}
??????? 再定义一个拦截器
/**
* @author :mxm
* @date :Created in 2021/8/17 14:16
* @description:接口访问限制
* @modified By:
* @version: 1.1$
*/
@Component
//由于HandlerInterceptorAdapter已经过期,需要实现HandlerInterceptor接口
public class FangshuaInterceptor implements HandlerInterceptor{
@Autowired
private RedisTemplate redisTemplate;
@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;
}
String[] keys = request.getRequestURI().split("/");
String key = keys[keys.length - 1];
//从redis中获取用户访问的次数
Integer count= (Integer)redisTemplate.opsForValue().get(key);
if(count==null){
//第一次访问
redisTemplate.opsForValue().set(key,1,10, TimeUnit.SECONDS);
}else{
//若不存在则
error(response,"请误频繁点击呢");
return false;
}
}
return true;
}
private void error(HttpServletResponse response, String message)throws Exception {
response.setContentType("application/json;charset=UTF-8");
AjaxResult ajaxResult = AjaxResult.error(message);
ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult));
}
}
????????最后需要将其注册到spring容器中
/**
* @author mxm
* @Date: 2020/11/1 0:12
* @Description: 拦截器注册 到springcloud容器中
*/
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Autowired
private FangshuaInterceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor);
}
}
??????? 使用仅需在接口上添加注解即可
/**
* 手动触发
* @param id
* @return
*/
@ApiOperation("手动触发")
@AccessLimit
@GetMapping("/v1/manual/{id}")
public AjaxRes<String> manualTrigger(@PathVariable String id){
linkTriggerExecute.triggerLink(LinkTrigger.builder().actionId(id).linkTriggerType("1").build());
return AjaxRes.ok("调用成功");
}
参考于:https://blog.csdn.net/qq_37342720/article/details/113836454
|