在Java开发中,我们可以使用Jedis客户端来实现Redis分布式锁。以下是一个简单的示例: ```java import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class DistributedLock { private static final String LOCK_KEY = "distributed-lock"; private static final int LOCK_EXPIRE = 60; private JedisPool jedisPool; public DistributedLock(JedisPoolConfig jedisPoolConfig, String host, int port) { this.jedisPool = new JedisPool(jedisPoolConfig, host, port); } public boolean lock() { Jedis jedis = jedisPool.getResource(); try { String lockId = UUID.randomUUID().toString(); String result = jedis.setnx(LOCK_KEY + lockId, lockId); if (result != null && result.equals("1")) { jedis.expire(LOCK_KEY + lockId, LOCK_EXPIRE); return true; } } catch (Exception e) { e.printStackTrace(); } finally { jedis.close(); } return false; } public boolean unlock(String lockId) { Jedis jedis = jedisPool.getResource(); try { String result = jedis.del(LOCK_KEY + lockId); return result != null && result.equals("1"); } catch (Exception e) { e.printStackTrace(); } finally { jedis.close(); } return false; } } ``` 在这个示例中,我们使用Jedis的setnx命令来获取锁。如果setnx命令成功,那么我们就获取到了锁,并且设置了一个过期时间。如果setnx命令失败,那么我们就尝试获取其他的锁。 我们还提供了一个unlock方法来释放锁。我们使用Jedis的del命令来删除锁。 注意,这个示例只是一个基本的实现,没有处理一些特殊情况,比如Jedis连接失败、网络中断等。在实际使用中,你可能需要添加更多的错误处理代码。 [2023-11-07 22:31:08 | AI小红书种草文 | 422点数解答]