redis 数据库对接
uuid 编码方式
编码
- java
public static byte[] uuidToBytes(UUID uuid) {
byte[] bytes = new byte[16];
long msb = uuid.getMostSignificantBits();
long lsb = uuid.getLeastSignificantBits();
for (int i = 0; i < 8; i++) {
bytes[i] = (byte) (msb >>> 8 * (7 - i));
bytes[i + 8] = (byte) (lsb >>> 8 * (7 - i));
}
return bytes;
}
解码
- java
public static UUID bytesToUuid(byte[] bytes) {
long msb = 0;
long lsb = 0;
for (int i = 0; i < 8; i++) {
msb = (msb << 8) | (bytes[i] & 0xff);
lsb = (lsb << 8) | (bytes[i + 8] & 0xff);
}
return new UUID(msb, lsb);
}
添加服务器锁
- KEYS[1]: instance key 实例的key,为
prefix + "." + instanceId - ARGV[1]: random token 随机token
- ARGV[2]: expire time 过期时间
如果返回 0,表示服务器锁已经存在,应停止后续行为并关闭服务器。
if redis.call("setnx",KEYS[1],ARGV[1]) == 1 then
redis.call("expire", KEYS[1], ARGV[2])
return 1
else
return 0
end
更新服务器锁
- KEYS[1]: instance key 实例的key,为
prefix + "." + instanceId - ARGV[1]: random token 随机token
- ARGV[2]: expire time 过期时间
如果返回 0,表示服务器锁不存在, 应停止后续行为并关闭服务器。
if redis.call("get",KEYS[1]) == ARGV[1] or redis.call("setnx",KEYS[1],ARGV[1]) == 1 then
redis.call("expire", KEYS[1], ARGV[2])
return 1
else
return 0
end
删除服务器锁
- KEYS[1]: instance key 实例的key,为
prefix + "." + instanceId - ARGV[1]: random token 随机token
if redis.call("get",KEYS[1]) == ARGV[1] then
return redis.call("del",KEYS[1])
else
return 0
end
添加玩家锁
- KEYS[1]: player key 玩家的key,为
prefix + "." + playerId - KEYS[2]: instance key 实例的key,为
prefix + "." + instanceId - ARGV[1]: instance id 实例id
if redis.call("setnx",KEYS[1],ARGV[1]) == 1 or redis.call("get",KEYS[1]) == ARGV[1] then
return 1
else
if redis.call("get",KEYS[2]) == nil then
redis.call("set",KEYS[1],ARGV[1])
return 1
else
return 0
end
end
删除玩家锁
- KEYS[1]: player key 玩家的key,为
prefix + "." + playerId - ARGV[1]: instance id 实例id
if redis.call("get",KEYS[1]) == ARGV[1] then
return redis.call("del",KEYS[1])
else
return 0
end