springboot整合redis+自定义注解+反射+aop实现接口限流

为什么我们要对接口进行限流呢?

因为在面对大并发大流量的请求时,突发情况下,大量的请求会将系统整垮,造成响应失败超时等状况。那为了防止出现这种情况最常见的解决方案之一就是限流,当请求达到一定的并发数或速率,就进行等待、排队、降级、拒绝服务等。

本文基于限流反射之一的计数器方式来实现限流

1.定义注解

package com.cwf.framework.limit.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Limit {
    /**
     * 资源的key,唯一
     * 作用:不同的接口,不同的流量控制
     */
    String key() default "";

    /**
     * 最多的访问限制次数
     */
    long count() default 7;

    /**
     * 过期时间也可以理解为单位时间,单位秒,默认60
     */
    long expire() default 60;


    /**
     * 提示语
     */
    String msg() default "系统繁忙,请稍后再试!";
}

2.aop+redis

利用redis 的incr 高并发 原子性计数器来计数,当请求次数超过规定次数就抛出自定义异常,全局异常捕获异常信息返回给前台

package com.cwf.framework.limit.aspectj;

import com.cwf.common.core.controller.BaseController;
import com.cwf.common.exception.base.MyException;
import com.cwf.common.utils.ip.IpUtils;
import com.cwf.framework.limit.annotation.Limit;
import com.cwf.framework.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;


/**
 * 限流服务
 */
@SuppressWarnings("all")
@Slf4j
@Component
@Aspect
public class LimitAOP extends BaseController {

    @Autowired
    private RedisService redisService;

    @Pointcut("@annotation(com.cwf.framework.limit.annotation.Limit)")
    private void LimitPointcut() {

    }

    @Before("@annotation(limit)")
    public void before(JoinPoint point, Limit limit) throws ClassNotFoundException, IllegalAccessException, NoSuchFieldException {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        assert requestAttributes != null;
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        assert request != null;
        String path = request.getRequestURI();
        String ip = IpUtils.getIpAddress(request);

        //获取注解信息
        String key = limit.key();
        long count = limit.count();
        String msg = limit.msg();
        long expire = limit.expire();

        String redisKey = ip+path+key+getUserId();
        Long inc = redisService.inc(redisKey);

        if (inc==1){
            redisService.expire(redisKey, expire, TimeUnit.SECONDS);
        }

        if (inc > count){
            log.error("\n{}触发限制流量",key);
            throw new MyException(msg,400);
        }



    }

}


1.使用

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用 Redisson 实现分布式锁,具体实现如下: 1. 引入 Redisson 依赖: ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.16.1</version> </dependency> ``` 2. 定义自定义注解 `DistributedLock`: ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface DistributedLock { String value() default ""; long leaseTime() default 30L; TimeUnit timeUnit() default TimeUnit.SECONDS; } ``` 3. 在需要加锁的方法上加上 `@DistributedLock` 注解: ```java @Service public class UserService { @DistributedLock("user:#{#userId}") public User getUserById(String userId) { // ... } } ``` 4. 实现 `DistributedLockAspect` 切面: ```java @Aspect @Component public class DistributedLockAspect { private final RedissonClient redissonClient; public DistributedLockAspect(RedissonClient redissonClient) { this.redissonClient = redissonClient; } @Around("@annotation(distributedLock)") public Object around(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable { String lockKey = distributedLock.value(); if (StringUtils.isEmpty(lockKey)) { lockKey = joinPoint.getSignature().toLongString(); } RLock lock = redissonClient.getLock(lockKey); boolean locked = lock.tryLock(distributedLock.leaseTime(), distributedLock.timeUnit()); if (!locked) { throw new RuntimeException("获取分布式锁失败"); } try { return joinPoint.proceed(); } finally { lock.unlock(); } } } ``` 5. 在 `application.yml` 中配置 Redisson: ```yaml spring: redis: host: localhost port: 6379 password: database: 0 redisson: single-server-config: address: redis://${spring.redis.host}:${spring.redis.port} ``` 这样就实现了一个基于 Redis 的分布式锁。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值