前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >利用AOP手写一个简单的熔断和限流

利用AOP手写一个简单的熔断和限流

作者头像
用户1215919
发布2021-12-28 12:42:50
3660
发布2021-12-28 12:42:50
举报
文章被收录于专栏:大大的微笑大大的微笑

MAVEN依赖

代码语言:javascript
复制
<!-- aspectj -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>

注解类

代码语言:javascript
复制
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimiter {

    int timeout() default -1;
	int count() default -1;
}

AOP处理类

代码语言:javascript
复制
@Component
@Aspect
public class RatelimiterAop {
	  private static ConcurrentHashMap<String, Semaphore> LIMITER = new ConcurrentHashMap<>();
    @Pointcut("@annotation(RateLimiter)")
    public void point() {

    }

    @Around("point()")
    public Object limit(ProceedingJoinPoint proceedingJoinPoint) {
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        RateLimiter limit = methodSignature.getMethod().getDeclaredAnnotation(RateLimiter.class);
        if (limit.timeout() > 0) {
            ExecutorService es = Executors.newFixedThreadPool(2);
            Future future = es.submit(() -> {
                try {
                    return proceedingJoinPoint.proceed();
                } catch (Throwable throwable) {
                    return null;
                }
            });
            final Object obj;
            try {
                obj = future.get(limit.timeout(), TimeUnit.MILLISECONDS);
                return obj;
            } catch (Exception e) {
                future.cancel(true);
                throw new RuntimeException("处理超时");
            }

        }else if (limit.count() > 0) {
            // key unique.
            String cacheKey = proceedingJoinPoint.getTarget().getClass().getName() + "::" + methodSignature.getName()
                    + "::" + Arrays.toString(methodSignature.getParameterNames());
            LIMITER.putIfAbsent(cacheKey, new Semaphore(limit.count()));
            System.out.println(cacheKey);

            Semaphore semaphore = LIMITER.get(cacheKey);
            try {
                semaphore.acquire();
                proceedingJoinPoint.proceed();
            } catch (Throwable throwable) {
               throw  new RuntimeException("请求异常");
            } finally {
                // 释放
                if (null != semaphore) {
                    semaphore.release();
                }
            }

        }


        try {
            return proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            return null;
        }
    }

测试

代码语言:javascript
复制
@RestController
public class TestController {
    @RateLimiter(timeout = 100)
    @PostMapping(value = "/test")
    public void test(){
        try {
            Random random = new Random();
            int time = random.nextInt(200);
            System.out.println(time + "ms");
            Thread.sleep(time);
            System.out.println("the end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
腾讯云服务器利旧
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档