栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

redis学习十-分布式锁

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

redis学习十-分布式锁

1 手写分布式锁 1.1 定义注解
@Target(value={ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DistributeLock {

	
	String key();

	
	long expire();

	
	int tryTimes();

	
	long waitInterval();
}
1.2 编写切面
@Slf4j
@Component
@Aspect
public class LockAspect {

    @Autowired
    private JedisClient jedisClient;

    @Around("execution(* *..*.*(..)) && @annotation(com.demo.distribute.lock.annotation.DistributeLock)")
    public Object execute(ProceedingJoinPoint point) {
        //读取接口方法签名
        Method method = ((MethodSignature)point.getSignature()).getMethod();
        DistributeLock distributeLock = method.getAnnotation(DistributeLock.class);
        String key = distributeLock.key();
        long expire = distributeLock.expire();
        int tryTimes = distributeLock.tryTimes();
        long waitInterval = distributeLock.waitInterval();
        String value = UUID.randomUUID().toString();
        try {
            while(tryTimes -- > 0) {
                if(jedisClient.setnx(key, value, expire)) {
                    return point.proceed();
                }
                Thread.sleep(waitInterval);
            }
        }catch(Throwable e) {
            log.info("execute method error, e:", e);
        }finally {
            jedisClient.del(key, value);
        }
        return null;
    }

}
1.3 测试代码
public class Consumer {
	
	@DistributeLock(key = "distributeLockSecondKill", expire = 1000, tryTimes = 10, waitInterval = 10)
	public void secondKill() {
		int num = Good.getNum();
		if(num -- > 0) {
			System.out.println(Thread.currentThread().getName() + "抢到商品,商品剩余:" + num);
			Good.setNum(num);
		}
	}
}

输出

Thread-10抢到商品,商品剩余:9
Thread-23抢到商品,商品剩余:8
Thread-60抢到商品,商品剩余:7
Thread-81抢到商品,商品剩余:6
Thread-80抢到商品,商品剩余:5
Thread-63抢到商品,商品剩余:4
Thread-84抢到商品,商品剩余:3
Thread-13抢到商品,商品剩余:2
Thread-79抢到商品,商品剩余:1
Thread-16抢到商品,商品剩余:0
2 redisson实现分布式锁
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/591019.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号