接了一個需求,公司有要調用一個其他平台的收費接口,調用一次,收取一次費用;需要封裝一下,防止被惡意盜刷;自己思考了一下,,記錄每個用戶的訪問次數,調用一次,累計數量+1,當達到設置上限 是,直接返回提示信息;;
初步構思,從2個維度限制;1、限制每個用戶每小時內的最大訪問次數,,2限制每個用戶每天的最大訪問次數;;結合redis的 incrby 和TTL實現,,redis自增方法保證並發情況下 +1 操作線程安全; redis的 key 為 接口名+用戶唯一標識+固定字符串(日期),value為訪問次數,,並設置過期時間為 1小時,,一天; 代碼如下:
pom.xml 引入redis 依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.3.4.RELEASE</version> </dependency>
application.properties redis配置(測試使用單節點)
# Redis數據庫索引(默認為0) spring.redis.database=0 # Redis服務器地址 spring.redis.host=127.0.0.1 # Redis服務器連接端口 spring.redis.port=6379 # Redis服務器連接密碼(默認為空) spring.redis.password= # 連接池最大連接數(使用負值表示沒有限制) spring.redis.pool.max-active=200 # 連接池最大阻塞等待時間(使用負值表示沒有限制) spring.redis.pool.max-wait=-1 # 連接池中的最大空閑連接 spring.redis.pool.max-idle=10 # 連接池中的最小空閑連接 spring.redis.pool.min-idle=0 # 連接超時時間(毫秒) spring.redis.timeout=1000 #哨兵模式redis集群配置,就是為了通過redis找主節點,做到無感切換 #spring.redis.password=123456 #spring.redis.sentinel.master=mymaster #spring.redis.sentinel.nodes=192.168.184.133:26379,192.168.184.135:26379,192.168.184.136:26379 ##連接超時時間 #spring.redis.timeout=6000ms ##Redis數據庫索引(默認為0) #spring.redis.database=0 ## 連接池配置,springboot2.0中直接使用jedis或者lettuce配置連接池,默認為lettuce連接池 ##連接池最大連接數(使用負值表示沒有限制) #spring.redis.jedis.pool.max-active=8 ##連接池最大阻塞等待時間(使用負值表示沒有限制) #spring.redis.jedis.pool.max-wait=-1s ##連接池中的最大空閑連接 #spring.redis.jedis.pool.max-idle=8 ##接池中的最小空閑連接 #spring.redis.jedis.pool.min-idle=0 ############################# #連接超時時間 #spring.redis.cluster.nodes=192.168.184.133:7000,192.168.184.133:7001,192.168.184.133:7002,192.168.184.133:7003,192.168.184.133:7004,192.168.184.133:7005 #spring.redis.password=123456 #spring.redis.timeout=6000ms #Redis數據庫索引(默認為0) #spring.redis.database=0 # 連接池配置,springboot2.0中直接使用jedis或者lettuce配置連接池,默認為lettuce連接池 #連接池最大連接數(使用負值表示沒有限制) #spring.redis.jedis.pool.max-active=8 #連接池最大阻塞等待時間(使用負值表示沒有限制) #spring.redis.jedis.pool.max-wait=-1s #連接池中的最大空閑連接 #spring.redis.jedis.pool.max-idle=8 #接池中的最小空閑連接 #spring.redis.jedis.pool.min-idle=0
redis配置類
package com.wanglin.study.design.pattern.work.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * @ClassName RedisConfig * @Description * @Author WANGQW * @Date 2021/3/3 9:59 **/ @Configuration public class RedisConfig { @Bean @SuppressWarnings("all") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.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); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
redis工具類
package com.wanglin.study.design.pattern.work.utils; 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.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * @ClassName RedisUtil * @Description * @Author WANGQW * @Date 2021/3/3 10:01 **/ @Component public class RedisUtil { @Autowired private RedisTemplate<String, Object> redisTemplate; /** * 指定緩存失效時間 * @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)); } } } // ============================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; } } /** * 遞增 如果不存在key,自動創建一個key; * @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 item 項 不能為null * @return true 存在 false不存在 */ public boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * hash遞增 如果不存在,就會創建一個 並把新增后的值返回 * @param key 鍵 * @param item 項 * @param by 要增加幾(大於0) * @return */ public double hincr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * hash遞減 * @param key 鍵 * @param item 項 * @param by 要減少記(小於0) * @return */ public double hdecr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, -by); } // ============================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; } } /** 336 * 將set數據放入緩存 337 * @param key 鍵 338 * @param time 時間(秒) 339 * @param values 值 可以是多個 340 * @return 成功個數 341 */ 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 值 * @param time 時間(秒) * @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 值 * @param time 時間(秒) * @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; } } }
使用spring aop 結合自定義注解完成 訪問次數累加;
自定義注解:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface IAccessRestrictionsForHour { }
切面:
package com.wanglin.study.design.pattern.work.aspect; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.ruijie.framework.common.RemoteResult; import com.wanglin.study.design.pattern.work.annotion.IAccessRestrictionsForHour; import com.wanglin.study.design.pattern.work.domain.Constants; import com.wanglin.study.design.pattern.work.domain.User; import com.wanglin.study.design.pattern.work.utils.RedisUtil; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @ClassName AccessRestrictionsAspect * @Description * @Author WANGQW * @Date 2021/3/2 14:21 **/ @Aspect @Component public class AccessRestrictionsAspect { private static final Logger log = LoggerFactory.getLogger(AccessRestrictionsAspect.class); @Autowired private RedisUtil redisUtil; @Pointcut("execution(* com.wanglin.study.design.pattern.work.controller.*.*(..)) && @annotation(com.wanglin.study.design.pattern.work.annotion.IAccessRestrictionsForHour)") public void before(){} @Before("before()") public void requestLimit(JoinPoint joinPoint) throws Exception{ Object[] args = joinPoint.getArgs(); User user = JSON.parseObject(JSON.toJSONString(args[0]), new TypeReference<User>() {}); if(null == user || StringUtils.isEmpty(user.getUserId())){ throw new RuntimeException("當前用戶未登錄,請先登錄后重試!"); } log.info(user.getUserId()+"=============="+user.getUserName()); String redisKey = Constants.ACCESS_LIMIT + Constants.ATRRBITE_SPLIT + user.getUserId(); Object o = redisUtil.get(redisKey); // IAccessRestrictionsForHour limit = this.getAnnotation(joinPoint); // if(limit == null) { // return; // } long incr = redisUtil.incr(redisKey, 1); if(1l == incr){
//設置過期時間
redisUtil.expire(redisKey,30);
} if(incr >= 30 ){ throw new RuntimeException("調用頻繁,請稍后再試!"); } } /** * @Description: 獲得注解 */ private IAccessRestrictionsForHour getAnnotation(JoinPoint joinPoint) throws Exception { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method != null) { return method.getAnnotation(IAccessRestrictionsForHour.class); } return null; } }
切面最終版:
package com.ruijie.demo.aspect; import com.ruijie.demo.entity.domain.AccessRecord; import com.ruijie.demo.exception.TycException; import com.ruijie.demo.service.AccessRecordService; import com.ruijie.demo.service.UpperLimitService; import com.ruijie.demo.util.GuavaCacheManager; import com.ruijie.framework.common.RemoteResult; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Date; /** * @ClassName UpperLimitAspect * @Description * @Author WANGQW * @Date 2021/3/18 10:31 **/ @Aspect @Component public class UpperLimitAspect { private static final Logger log = LoggerFactory.getLogger(UpperLimitAspect.class); @Autowired private UpperLimitService upperLimitService; @Autowired private AccessRecordService accessRecordService; @Pointcut("execution(* com.ruijie.demo.api.*.*(..)) && @annotation(com.ruijie.demo.annotaion.UpperLimitAnnotation)") public void pointCut(){} @Around("pointCut()") public RemoteResult around(ProceedingJoinPoint joinPoint) throws Throwable { log.info("進入控制訪問上限切面=======================satrt"); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String sysId = request.getHeader("sysId"); String uri = request.getRequestURI(); upperLimitService.checkAndIncrAccessNumber(sysId,uri); // 進入真正方法的 都是未達訪問上限的請求 RemoteResult proceed = (RemoteResult)joinPoint.proceed(); //訪問記錄 AccessRecord accessRecord = new AccessRecord(); accessRecord.setSysId(sysId); accessRecord.setPath(uri); accessRecord.setCreateTime(new Date()); accessRecord.setReason(proceed.getErr()); accessRecord.setSuccess(proceed.getStatus()); accessRecordService.insertAccessRecord(accessRecord); log.info("控制訪問上限切面=======================end"); return proceed; } //異常通知 @AfterThrowing(value="execution(* com.ruijie.demo.api.*.*(..)) && @annotation(com.ruijie.demo.annotaion.UpperLimitAnnotation)",throwing="e") public void afterThrowing(JoinPoint joinPoint,TycException e){ log.error("異常通知=======================start"); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String sysId = request.getHeader("sysId"); String uri = request.getRequestURI(); AccessRecord accessRecord = new AccessRecord(); accessRecord.setSysId(sysId); accessRecord.setPath(uri); accessRecord.setCreateTime(new Date()); accessRecord.setReason(e.getMessage()); accessRecord.setSuccess(e.getErrCode()); accessRecordService.insertAccessRecord(accessRecord); log.error("異常通知=======================end"); } }
controller
package com.wanglin.study.design.pattern.work.controller; import com.wanglin.study.design.pattern.work.annotion.IAccessRestrictionsForHour; import com.wanglin.study.design.pattern.work.domain.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; /** * @ClassName LimitController * @Description * @Author WANGQW * @Date 2021/3/2 14:39 **/ @Controller public class LimitController { @IAccessRestrictionsForHour @PostMapping("test") @ResponseBody public String testMethod(@RequestBody User user){ return "success"; } @PostMapping("test2") @ResponseBody public String testMethod2(@RequestBody User user){ return "success2222222222"; } }