package com.qianwen.core.sequence.range.redis; import cn.hutool.core.util.StrUtil; import com.qianwen.core.sequence.exception.SeqException; import com.qianwen.core.sequence.range.SeqRange; import com.qianwen.core.sequence.range.SeqRangeMgr; import redis.clients.jedis.Jedis; public class RedisSeqRangeMgr implements SeqRangeMgr { private static final String KEY_PREFIX = "x_sequence_"; private Jedis jedis; private String ip; private Integer port; private String auth; private int step = 1; private long stepStart = 0; private volatile boolean keyAlreadyExist; @Override // com.qianwen.core.sequence.range.SeqRangeMgr public SeqRange nextRange(String name) throws SeqException { if (!this.keyAlreadyExist) { Boolean isExists = this.jedis.exists(getRealKey(name)); if (!isExists.booleanValue()) { this.jedis.setnx(getRealKey(name), String.valueOf(this.stepStart)); } this.keyAlreadyExist = true; } Long max = this.jedis.incrBy(getRealKey(name), this.step); Long min = Long.valueOf((max.longValue() - this.step) + 1); return new SeqRange(min.longValue(), max.longValue()); } @Override // com.qianwen.core.sequence.range.SeqRangeMgr public void init() { checkParam(); this.jedis = new Jedis(this.ip, this.port.intValue()); if (StrUtil.isNotBlank(this.auth)) { this.jedis.auth(this.auth); } } private void checkParam() { if (isEmpty(this.ip)) { throw new SecurityException("[RedisSeqRangeMgr-checkParam] ip is empty."); } if (null == this.port) { throw new SecurityException("[RedisSeqRangeMgr-checkParam] port is null."); } } private String getRealKey(String name) { return KEY_PREFIX + name; } private boolean isEmpty(String str) { return null == str || str.trim().length() == 0; } public String getIp() { return this.ip; } public void setIp(String ip) { this.ip = ip; } public int getPort() { return this.port.intValue(); } public void setPort(int port) { this.port = Integer.valueOf(port); } public int getStep() { return this.step; } public void setStep(int step) { this.step = step; } public String getAuth() { return this.auth; } public void setAuth(String auth) { this.auth = auth; } public long getStepStart() { return this.stepStart; } public void setStepStart(long stepStart) { this.stepStart = stepStart; } }