Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Interface Anti-brushing in SpringBoot Project

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to realize the interface anti-brushing in the SpringBoot project". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "how to achieve interface brush prevention in the SpringBoot project"!

Custom annotations import java.lang.annotation.Retention;import java.lang.annotation.Target;import static java.lang.annotation.ElementType.METHOD;import static java.lang.annotation.RetentionPolicy.RUNTIME;/** * @ author Yang * @ version 1.0 * @ date 10:28 on 2021-2-22 * / @ Retention (RUNTIME) @ Target (METHOD) public @ interface AccessLimit {int seconds (); int maxCount (); boolean needLogin () default true } 2. Define interceptor import com.alibaba.fastjson.JSON;import com.mengxiangnongfu.payment.annotation.AccessLimit;import com.mengxiangnongfu.payment.commons.RedisUtil;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.stereotype.Component;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.OutputStream / * @ author Yang * @ version 1.0 * @ date on 2021-2-22 10:29 * / @ Componentpublic class FangshuaInterceptor extends HandlerInterceptorAdapter {@ Autowired private RedisUtil redisUtil; @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {/ / determine whether the request belongs to the method if (handler instanceof HandlerMethod) {HandlerMethod hm = (HandlerMethod) handler / / get the annotation in the method to see if it is available: AccessLimit accessLimit = hm.getMethodAnnotation (AccessLimit.class); if (accessLimit = = null) {return true;} int seconds = accessLimit.seconds (); int maxCount = accessLimit.maxCount (); boolean login = accessLimit.needLogin (); String key = "1" / / if you need to log in to if (login) {/ / get the login session to judge / /. Key + = "" + "1"; / / assume that the user is 1, and the project is dynamically acquired userId} / / the number of user visits obtained from redis Integer count = (Integer) redisUtil.get (key); if (count = = null) {/ / first visit to redisUtil.set (key, 1, seconds) } else if (count

< maxCount) { //加1 redisUtil.incr(key, 1); } else { //超出访问次数 render(response, "请求过于频繁~请稍后再试~"); //这里的CodeMsg是一个返回参数 return false; } } return true; } private void render(HttpServletResponse response, String cm) throws Exception { response.setContentType("application/json;charset=UTF-8"); OutputStream out = response.getOutputStream(); String str = JSON.toJSONString(cm); out.write(str.getBytes("UTF-8")); out.flush(); out.close(); }}三、Redis工具类import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Component;import org.springframework.util.CollectionUtils;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;/** * @author Yang * @version 1.0 * @date 2020/11/29 17:06 */@Component@Slf4jpublic class RedisUtil { @Autowired RedisTemplate 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) {log.error (key, e); return false }} / * get expiration time based on key * * @ param key key cannot return 0 for null * @ return time (seconds) represents permanent validity * / public long getExpire (String key) {return redisTemplate.getExpire (key, TimeUnit.SECONDS) } / * determine whether key exists * * @ param key key * @ return true does not exist * / public boolean hasKey (String key) {try {return redisTemplate.hasKey (key);} catch (Exception e) {log.error (key, e); return false }} / * * delete cache * * @ param key can pass a value or multiple * / @ SuppressWarnings ("unchecked") public void del (String...) Key) {if (key! = null & & key.length > 0) {if (key.length = = 1) {redisTemplate.delete (key [0]);} else {redisTemplate.delete (CollectionUtils.arrayToList (key)) } / = = String== / * ordinary cache acquires * * @ param key key * @ return value * / public Object get (String key) {return key = = null? Null: redisTemplate.opsForValue (). Get (key);} / * * ordinary cache put in * * @ param key key * @ param value value * @ return true success false failed * / public boolean set (String key, Object value) {try {redisTemplate.opsForValue () .set (key, value); return true } catch (Exception e) {log.error (key, e); return false }} / * ordinary cache put and set time * * @ param key key * @ param value value * @ param time time (seconds) time is greater than 0 if time is less than or equal to 0, indefinitely * @ return true successful false failed * / 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) {log.error (key, e); return false }} / * incremental application scenarios: https://blog.csdn.net/y_y_y_k_k_k_k/article/details/79218254 is high and occurs as order number, second kill business logic, etc. * * @ param key key * @ param delta to add several (greater than 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 hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { log.error(key, e); return false; } } /** * HashSet 并设置时间 * * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败 */ public boolean hmset(String key, Map map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time >

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report