• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
haipali
博客园    首页    新随笔    联系   管理    订阅  订阅

自定义java@注解

自定义注解主要用于抽象出重复代码,以减少枯燥无味的重复工作量
举例:创建Redis分布式锁注解
步骤:

  1. 新建interface接口
@Target(ElementType.METHOD)
//描述注解使用范围
@Retention(RetentionPolicy.RUNTIME)//设置注解时间范围
//        SOURCE  源文件保留
//        CLASS,  编译期保留,默认值
//        RUNTIME 运行期保留,可通过反射去获取注解信息
@Documented //使用 javadoc 工具为类生成帮助文档时是否要保留其注解信息
@Inherited  //被Inherited注解修饰的注解具有继承性,如果父类使用了被@Inherited修饰的注解,则其子类将自动继承该注解。
public @interface RedisLock {
    String lockKey();
    long expireTime() default 5;
    TimeUnit timeUnit() default TimeUnit.MINUTES;
    int retryTimes() default 10;
}
  1. 再创建AOP工具类
@Aspect
public class RedislockAspect {
    @Around(value = "@annotation(com.haipali.annotation.RedisLock)")
    public void handleRedisLock(ProceedingJoinPoint joinPoint){
//        通过反射获取注解对象
        RedisLock redisLock = ((MethodSignature)joinPoint.getSignature())
                .getMethod()
                .getAnnotation(RedisLock.class);
//        获取对象变量
        String lockKey = redisLock.lockKey();
        LOCK_KEY = lockKey;
        long expireTime = redisLock.expireTime();
        TimeUnit timeUnit = redisLock.timeUnit();
        int retryTimes = redisLock.retryTimes();
//        获取锁
        if(tryLock(lockKey,expireTime,timeUnit,retryTimes)){
            try {
                joinPoint.proceed();
            } catch (Throwable e) {
                e.printStackTrace();
            }finally {
                releaseLock();
            }
        }
    }
}
  1. 以下为RedisTool
public class RedisTool {
    static Jedis jedis = new Jedis("localhost");
    static String LOCK_KEY = null;
    public static boolean tryLock(String lockKey, long expireTime, TimeUnit timeUnit, int retryTimes) {
        final long RETRY_WAIT_TIME = 100; // 获取锁失败后的重试等待时间,单位毫秒
        // 获取分布式锁
        while (retryTimes > 0) {
            // 使用 SETNX 命令尝试获取锁
            Long result = jedis.setnx(lockKey, "locked");
            if (result == 1) {
                // 成功获取到锁,设置过期时间
                jedis.expire(lockKey, expireTime);
                return true;
            } else {
                // 获取锁失败,重试等待一段时间
                retryTimes--;
                try {
                    Thread.sleep(RETRY_WAIT_TIME);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        return false;
    }
    public static void releaseLock() {
        jedis.del(LOCK_KEY);
    }
}
  1. 然后就能肆意妄为的使用啦
public class update {
    @RedisLock(lockKey = "lock",expireTime = 5,timeUnit = TimeUnit.SECONDS,retryTimes = 10)
    public static void update() {
        System.out.println("java");
    }
    public static void main(String[] args) {
        update();
    }
}
posted @ 2023-07-16 17:16  蓝光水母  阅读(39)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3