码迷,mamicode.com
首页 > 其他好文 > 详细

redis分布式锁的使用

时间:2019-02-07 23:54:18      阅读:312      评论:0      收藏:0      [点我收藏+]

标签:done   redist   void   redis分布式   out   ==   分布式   autowire   exec   

一  本身自带的方法进行使用:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
public class RedisTool {
 
    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
 
    /**
     * 尝试获取分布式锁
     * @param jedis Redis客户端
     * @param lockKey 锁
     * @param requestId 请求标识
     * @param expireTime 超期时间
     * @return 是否获取成功
     */
    public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
 
        String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
 
        if (LOCK_SUCCESS.equals(result)) {
            return true;
        }
        return false;
 
    }
 
}
public class RedisTool {
 
    private static final Long RELEASE_SUCCESS = 1L;
 
    /**
     * 释放分布式锁
     * @param jedis Redis客户端
     * @param lockKey 锁
     * @param requestId 请求标识
     * @return 是否释放成功
     */
    public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
 
        String script = "if redis.call(‘get‘, KEYS[1]) == ARGV[1] then return redis.call(‘del‘, KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
 
        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
        return false;
 
    }
 
}

二:redisson使用:

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.5.4</version>
</dependency>
@RestController
public class StockController {
    @Autowired
    StockRepository stockRepository;
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    @Autowired
    RedissonClient redissonClient;
    final static String id = "1";
    @RequestMapping("/addStock")
    public void addStock() {
        RLock lock = redissonClient.getLock("redisson:lock:stock:" + id);
        for (int i = 0; i < 100; i++) {
            executorService.execute(() -> {
                lock.lock();
                try {
                    Stock stock = stockRepository.findOne(id);
                    stock.setNumber(stock.getNumber() + 1);
                    stockRepository.save(stock);
                } finally {
                    lock.unlock();
                }
            });
        }
    }
}
@RequestMapping("testReentrant")
public void ReentrantLock() {
    RLock lock = redissonClient.getLock("fibonacci");
    lock.lock();
    try {
        int result = fibonacci(10);
        System.out.println(result);
    } finally {
        lock.unlock();
    }
}
int fibonacci(int n) {
    RLock lock = redissonClient.getLock("fibonacci");
    try {
        if (n <= 1) return n;
        else
            return fibonacci(n - 1) + fibonacci(n - 2);
    } finally {
        lock.unlock();
    }
}

 

redis分布式锁的使用

标签:done   redist   void   redis分布式   out   ==   分布式   autowire   exec   

原文地址:https://www.cnblogs.com/xiufengchen/p/10355616.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!