Springboot做请求次数统计思路

这个功能,使用到了spring aop、redis来进行完成。具体思路是:使用aop对每个请求进行环绕通知,在每次请求的时候,都进行拦截,根据拦截的接口的方法名进行区分,在redis中创建不同的key,相同的key进行累加。然后可以定时将redis的请求统计写到数据库中。

具体代码实现:

aop代码:

@Aspect
@Component
public class CountOfTimesAop {

    @Autowired
    private RedisUtil redisUtil;

    @Pointcut("execution(* com.office.controller.synchronize.*.*(..)) || execution(* com.office.controller.*.*(..))")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        String key = RedisKeyPrefixConstants.TENANT_Call_LOGS + joinPoint.getSignature().getName() + "#" + DateUtil.format(new Date(), "yyyy/MM/dd");
        redisUtil.increment(key);
        redisUtil.expire(key,24, TimeUnit.HOURS);
        return joinPoint.proceed();
    }
}

redis工具类:

@Component
@RequiredArgsConstructor
public class RedisUtil {
    @NonNull
    public RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final long timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }
    /**
     * 单机redis 锁
     *
     * @param key setNX的key
     * @param value sexNX的值
     */
    public <T> boolean setCacheObjectNX(final String key, final T value) {
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(key, value));
    }
    /**
     * 单机redis 锁
     *
     * @param key setNX的key
     * @param value sexNX的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> boolean setCacheObjectNX(final String key, final T value,final long timeout, final TimeUnit timeUnit) {
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(key, value,timeout,timeUnit));
    }

    /**
     *
     * @param buildLockKey : 锁名称
     * @return
     */
    public boolean tryLock(String buildLockKey){
        String lockValue = IdUtil.simpleUUID()+ Thread.currentThread().getName();
        //尝试加锁,锁失效时间为 1 分钟,覆盖业务时间
        return this.setCacheObjectNX( buildLockKey, lockValue, RedisLockConstants.DEFAULT_EXPIRE_TIME, TimeUnit.SECONDS );
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout) {
        return Boolean.TRUE.equals(expire(key, timeout, TimeUnit.SECONDS));
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit) {
        return Boolean.TRUE.equals(redisTemplate.expire(key, timeout, unit));
    }

    /**根据key获取过期时间*/
    public Long getExpire(final String key){
        return redisTemplate.getExpire(key);
    }

    /** 判断key是否存在*/
    public boolean hasKey(final String key){
        return  Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

//    /**
//     * keys *pattern*
//     *
//     * @param
//     * @return 缓存键值对应的数据
//     */
//    public Set<String> keys(String pattern) {
//
//        return redisTemplate.keys(pattern);
//
//    }


    /**
     * 删除单个对象
     */
    public boolean deleteObject(final String key) {
        return Boolean.TRUE.equals(redisTemplate.delete(key));
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     */
    public long deleteObject(final Collection collection) {
        Long delete = redisTemplate.delete(collection);
        return ObjectUtil.isNull(delete) ? 0 :delete;
    }

    /**
     * 删除指定前缀key
     *
     * @param
     */
    public long deleteObjectPrefix(final String pattern) {
        // 获取Redis中特定前缀
        Set<String> keys = redisTemplate.keys(pattern);
        // 删除
        Long delete = redisTemplate.delete(keys);
        return ObjectUtil.isNull(delete) ? 0 :delete;
    }


    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList) {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }


    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public List getCacheList(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        for (T t : dataSet) {
            setOperation.add(t);
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     */
    public <T> Set<T> getCacheSet(final String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     */
    public <T> Map<String, T> getCacheMap(final String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 删除Hash中的数据
     */
    public void delCacheMapValue(final String key, final String hKey) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 返回指定指定的所有key
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }
    /**
     * 返回指定指定的所有key,使用全匹配
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keysLike(final String pattern) {
        return redisTemplate.keys("*"+pattern+"*");
    }
    /**
     * 返回指定指定的所有key,使用右匹配
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keysRightLike(final String pattern) {
        return redisTemplate.keys(pattern+"*");
    }
    /**
     * 返回指定指定的所有key,使用左匹配
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keysLeftLike(final String pattern) {
        return redisTemplate.keys("*"+pattern);
    }


    /**
     * 根据键值对进行累加计数
     * @param key 键值
     */
    public void increment(String key) {
        redisTemplate.opsForValue().increment(key);
    }


    public String getIncrement(String key) {
        return redisTemplate.opsForValue().get(key).toString();
    }
}

定时任务将数据写到数据库中:

@Slf4j
@Component
public class ScheduleTask {

    @Autowired
    private ServiceLogsDao serviceLogsDao;

    @Autowired
    private RedisUtil redisUtil;


    @Scheduled(cron = "0 0/5 * * * ?")
    public void init() {
        Collection<String> keys = redisUtil.keysRightLike(RedisKeyPrefixConstants.TENANT_Call_LOGS);
        String countDate = DateUtil.format(new Date(), "yyyy/MM/dd");
        //拿到当天时间的
        List<String> list = keys.stream().filter(key -> key.contains(countDate)).toList();
        //缓存没有,结束
        if(CollUtil.isEmpty(list))return;
        List<ServiceCallLogs> serviceCallLogsArrayList = new ArrayList<>(list.size());
        for (String redisDate : list) {
            //组装对象,这里相关代码没有编写,看实际情况完成。
        }
        if(CollUtil.isEmpty(serviceCallLogsArrayList))return;
        //存入mysql 存在则更新
        serviceLogsDao.getBaseMapper().replaceInsert(serviceCallLogsArrayList);
    }
}  

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Spring AOP和Scheduled定时任务来实现统计所有接口每秒钟请求次数的功能。具体实现步骤如下: 1. 定义一个切面类,使用@Aspect注解标识该类为切面类,并使用@Pointcut注解定义切入点表达式,表示对所有Controller层的接口进行拦截。 ```java @Aspect @Component public class RequestCountAspect { private static final int INTERVAL = 1; // 时间间隔,单位:秒 private Map<String, Integer> requestCountMap = new ConcurrentHashMap<>(); // 存储接口请求次数 @Pointcut("execution(public * com.example.controller..*.*(..))") public void requestCount() {} } ``` 2. 在切面类中定义一个计时器,使用Scheduled注解标识方法为定时任务,在每个时间间隔结束时打印接口每秒钟请求次数,并清空计数器。 ```java @Aspect @Component public class RequestCountAspect { private static final int INTERVAL = 1; // 时间间隔,单位:秒 private Map<String, Integer> requestCountMap = new ConcurrentHashMap<>(); // 存储接口请求次数 private Map<String, Integer> requestCountPerSecondMap = new ConcurrentHashMap<>(); // 存储每秒钟接口请求次数 private int count = 0; // 计数器 @Pointcut("execution(public * com.example.controller..*.*(..))") public void requestCount() {} @Around("requestCount()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { // 获取方法名 String methodName = joinPoint.getSignature().getName(); // 统计接口请求次数 if (requestCountMap.containsKey(methodName)) { requestCountMap.put(methodName, requestCountMap.get(methodName) + 1); } else { requestCountMap.put(methodName, 1); } count++; // 计数器加1 // 执行方法 Object result = joinPoint.proceed(); return result; } @Scheduled(fixedRate = INTERVAL * 1000) public void printRequestCountPerSecond() { for (Map.Entry<String, Integer> entry : requestCountMap.entrySet()) { String methodName = entry.getKey(); int requestCount = entry.getValue(); requestCountPerSecondMap.put(methodName, requestCount / INTERVAL); // 计算每秒钟请求次数 } System.out.println(requestCountPerSecondMap); requestCountMap.clear(); // 清空计数器和存储接口请求次数的Map requestCountPerSecondMap.clear(); count = 0; } } ``` 3. 在Spring Boot应用启动类中添加@EnableScheduling注解启用定时任务功能。 ```java @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 需要注意的是,以上代码仅为示例代码,具体实现需要根据实际业务需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值