Api介面防攻擊防刷註解實現
阿新 • • 發佈:2021-10-09
定義註解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ApiAccessLimit { int seconds() default 5; int maxCount() default 5; }
定義方法切面
@Aspect @Component @Slf4j public class ApiAccessLimitAspect { @Autowired @Qualifier("redisUtil2") privateRedisUtil redisUtil; @Before("@annotation(apiAccessLimit)") public void checkAccessLimit(JoinPoint joinPoint, ApiAccessLimit apiAccessLimit) { //獲取request物件 HttpServletRequest request = currentRequest(); if (Objects.isNull(request)) { return; } String ipAddress= IpAddressUtil.getIPAddress(request); String method = joinPoint.getSignature().getName(); Integer count = (Integer) redisUtil.get(ipAddress + method); if (count == null) { //第一次訪問 redisUtil.set(ipAddress + method, 1, apiAccessLimit.seconds()); }else if (count < apiAccessLimit.maxCount()) { //加1 redisUtil.increase(ipAddress + method, 1); } else { //超出訪問次數 throw new BaseException(ApiAccessErrorEnum.ACCESS_LIMIT_ERROR); } } /** * 獲取當前請求資訊 * @return Current request or null */ private HttpServletRequest currentRequest() { ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); return Optional.ofNullable(servletRequestAttributes).map(ServletRequestAttributes::getRequest).orElse(null); } }
定義異常
public enum ApiAccessErrorEnum implements IErrorCode { ACCESS_LIMIT_ERROR("10001", "Access Limit"); private final String errorCode; private final String errorMessage; private static final String ERROR_CODE_START = "Access-"; ApiAccessErrorEnum(String errorCode, String errorMessage) { this.errorCode = errorCode; this.errorMessage = errorMessage; } @Override public String getErrorCode() { return ERROR_CODE_START + errorCode; } @Override public String getErrorMessage() { return errorMessage; } }
Redis配置類
@Configuration public class RedisConfiguration { @Autowired private RedisProperties properties; @Bean("lettuceConnectionFactory") public LettuceConnectionFactory lettuceConnectionFactory() throws Exception { LettuceClientConfigurationBuilder lettuceClientConfigurationBuilder = LettuceClientConfiguration.builder(); if (this.properties.getSentinel() != null) { return new LettuceConnectionFactory(getSentinelConfig(), lettuceClientConfigurationBuilder.build()); } if (this.properties.getCluster() != null) { return new LettuceConnectionFactory(getClusterConfiguration(), lettuceClientConfigurationBuilder.build()); } RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setDatabase(properties.getDatabase()); redisStandaloneConfiguration.setHostName(properties.getHost()); redisStandaloneConfiguration.setPort(properties.getPort()); redisStandaloneConfiguration.setPassword(RedisPassword.of(AesUtils.aesDecrypt(properties.getPassword()))); return new LettuceConnectionFactory(redisStandaloneConfiguration, lettuceClientConfigurationBuilder.build()); } private RedisClusterConfiguration getClusterConfiguration() throws Exception { RedisProperties.Cluster clusterProperties = this.properties.getCluster(); RedisClusterConfiguration config = new RedisClusterConfiguration( clusterProperties.getNodes()); if (clusterProperties.getMaxRedirects() != null) { config.setMaxRedirects(clusterProperties.getMaxRedirects()); } if (this.properties.getPassword() != null) { config.setPassword(RedisPassword.of(AesUtils.aesDecrypt(this.properties.getPassword()))); } return config; } private RedisSentinelConfiguration getSentinelConfig() throws Exception { RedisSentinelConfiguration config = new RedisSentinelConfiguration(); RedisProperties.Sentinel sentinelProperties = this.properties.getSentinel(); config.master(sentinelProperties.getMaster()); config.setSentinels(createSentinels(sentinelProperties)); if (this.properties.getPassword() != null) { config.setPassword(RedisPassword.of(AesUtils.aesDecrypt(this.properties.getPassword()))); } config.setDatabase(this.properties.getDatabase()); return config; } private List<RedisNode> createSentinels(RedisProperties.Sentinel sentinel) { List<RedisNode> nodes = new ArrayList<>(); for (String node : sentinel.getNodes()) { try { String[] parts = StringUtils.split(node, ":"); Assert.state(parts.length == 2, "Must be defined as 'host:port'"); nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1]))); } catch (RuntimeException ex) { throw new IllegalStateException( "Invalid redis sentinel " + "property '" + node + "'", ex); } } return nodes; } @Bean public RedisTemplate<String, Object> redisTemplate(@Qualifier("lettuceConnectionFactory") RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); 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(); template.setKeySerializer(stringRedisSerializer); template.setHashKeySerializer(stringRedisSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } @Bean public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) { return new RedisUtil(redisTemplate); } }
Redis工具類
@Slf4j public final class RedisUtil { private RedisTemplate<String, Object> redisTemplate; public RedisUtil(RedisTemplate<String, Object> redisTemplate) { this.redisTemplate = redisTemplate; } /** * 指定快取失效時間 * * @param key 鍵 * @param time 時間(秒) */ private void expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } } catch (Exception e) { log.error("", e); } } /** * 指定快取失效時間 * * @param key 鍵 * @param time 時間(秒) */ public void expireAt(String key, Date time) { try { if (time != null && time.after(new Date())) { redisTemplate.expireAt(key, time); } } catch (Exception e) { log.error("", e); } } /** * 根據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) { log.error("", e); 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(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) { log.error("", e); 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) { log.error("", e); return false; } } /** * 遞增 * * @param key 鍵 * @param delta 要增加幾(大於0) * @return */ public long increase(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 decrease(String key, long delta) { if (delta < 0) { throw new RuntimeException("遞減因子必須大於0"); } return redisTemplate.opsForValue().increment(key, -delta); } // ================================Map================================= /** * @param key 鍵 不能為null * @param item 項 不能為null * @return 值 */ public Object hashget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 獲取hashKey對應的所有鍵值 * * @param key 鍵 * @return 對應的多個鍵值 */ public Map<Object, Object> getMap(String key) { return redisTemplate.opsForHash().entries(key); } /** * 176 HashSet 177 * * @param key 鍵 178 * @param map 對應多個鍵值 179 * @return true 成功 false 失敗 180 */ public boolean hmset(String key, Map<String, Object> map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { log.error("", e); 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) { log.error("", e); return false; } } /** * 212 向一張hash表中放入資料,如果不存在將建立 213 * * @param key 鍵 214 * @param item 項 215 * @param value 值 216 * @return true 成功 false失敗 217 */ public boolean hset(String key, String item, Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { log.error("", e); return false; } } /** * 229 向一張hash表中放入資料,如果不存在將建立 230 * * @param key 鍵 231 * @param item 項 232 * @param value 值 233 * @param time 時間(秒) 注意:如果已存在的hash表有時間,這裡將會替換原有的時間 234 * @return true 成功 false失敗 235 */ 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) { log.error("", e); return false; } } /** * 250 刪除hash表中的值 251 * * @param key 鍵 不能為null 252 * @param item 項 可以使多個 不能為null 253 */ public void hdel(String key, Object... item) { redisTemplate.opsForHash().delete(key, item); } /** * 259 判斷hash表中是否有該項的值 260 * * @param key 鍵 不能為null 261 * @param item 項 不能為null 262 * @return true 存在 false不存在 263 */ public boolean hHasKey(String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * 269 hash遞增 如果不存在,就會建立一個 並把新增後的值返回 270 * * @param key 鍵 271 * @param item 項 272 * @param by 要增加幾(大於0) 273 * @return 274 */ public double hincr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * 280 hash遞減 281 * * @param key 鍵 282 * @param item 項 283 * @param by 要減少記(小於0) 284 * @return 285 */ public double hdecr(String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, -by); } // ============================set============================= /** * 292 根據key獲取Set中的所有值 293 * * @param key 鍵 294 * @return 295 */ public Set<Object> sGet(String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { log.error("", e); return null; } } /** * 306 根據value從一個set中查詢,是否存在 307 * * @param key 鍵 308 * @param value 值 309 * @return true 存在 false不存在 310 */ public boolean sHasKey(String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { log.error("sHasKey", e); return false; } } /** * 321 將資料放入set快取 322 * * @param key 鍵 323 * @param values 值 可以是多個 324 * @return 成功個數 325 */ public long sSet(String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { log.error("sSet", e); 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) { log.error("", e); return 0; } } /** * 355 獲取set快取的長度 356 * * @param key 鍵 357 * @return 358 */ public long sGetSetSize(String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { log.error("", e); return 0; } } /** * 369 移除值為value的 370 * * @param key 鍵 371 * @param values 值 可以是多個 372 * @return 移除的個數 373 */ public long setRemove(String key, Object... values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { log.error("setRemove", e); return 0; } } // ===============================list================================= /** * 386 獲取list快取的內容 387 * * @param key 鍵 388 * @param start 開始 389 * @param end 結束 0 到 -1代表所有值 390 * @return 391 */ public List<Object> lGet(String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { log.error("", e); return null; } } /** * 402 獲取list快取的長度 403 * * @param key 鍵 404 * @return 405 */ public long lGetListSize(String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { log.error("", e); return 0; } } /** * 416 通過索引 獲取list中的值 417 * * @param key 鍵 418 * @param index 索引 index>=0時, 0 表頭,1 第二個元素,依次類推;index<0時,-1,表尾,-2倒數第二個元素,依次類推 419 * @return 420 */ public Object lGetIndex(String key, long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { log.error("", e); return null; } } /** * 431 將list放入快取 432 * * @param key 鍵 433 * @param value 值 434 * @return 436 */ public boolean lSet(String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { log.error("", e); 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) { log.error("", e); return false; } } /** * 467 將list放入快取 468 * * @param key 鍵 469 * @param value 值 470 * @return 472 */ public boolean lSet(String key, List<Object> value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { log.error("", e); return false; } } /** * 484 將list放入快取 485 * <p> * 486 * * @param key 鍵 487 * @param value 值 488 * @param time 時間(秒) 489 * @return 490 */ 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) { log.error("", e); 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) { log.error("", e); 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) { log.error("", e); return 0; } } }
註解使用:方法上添加註解即可,即5秒內同一ip最多呼叫5次
@ApiAccessLimit(seconds = 5, maxCount = 5)