<dependency>
<groupId>com.xuanner</groupId>
<artifactId>xsequence-core</artifactId>
<version>1.6</version>
</dependency>
import com.xuanner.seq.range.impl.redis.RedisSeqRangeMgr;
import com.xuanner.seq.sequence.impl.DefaultRangeSequence;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author ah
* @date 2020/3/18 20:19
*/
@Configuration
public class serialNumberConfig {
@Autowired
private JedisProperties jedisProperties;//redis配置
private RedisSeqRangeMgr redisSeqRangeMgr;
public RedisSeqRangeMgr RedisSeqRangeMgr(){
redisSeqRangeMgr=new RedisSeqRangeMgr();
redisSeqRangeMgr.setIp(jedisProperties.getHost());//redis ip
redisSeqRangeMgr.setPort(jedisProperties.getPort());//redis 端口
redisSeqRangeMgr.setAuth(jedisProperties.getPassword());//redis 密码
redisSeqRangeMgr.setStepStart(0);//起始位置 默认0
redisSeqRangeMgr.init();
//redisSeqRangeMgr.setStep("");//redis的步长 默认1000, 作者说的是“值越大 性能越好,但可能断层” 没懂什么意思未做深入研究
return redisSeqRangeMgr;
}
//一个叫circular_的序列生成器
@Bean
public DefaultRangeSequence circularRangeSequence(){
return getDefaultRangeSequence("circular_");
}
//一个叫sales_的序列生成器
@Bean
public DefaultRangeSequence salesSequence(){
return getDefaultRangeSequence("sales_");
}
@NotNull
private DefaultRangeSequence getDefaultRangeSequence(String circular) {
DefaultRangeSequence defaultRangeSequence = new DefaultRangeSequence();
defaultRangeSequence.setName(circular);
RedisSeqRangeMgr();
defaultRangeSequence.setSeqRangeMgr(redisSeqRangeMgr);
return defaultRangeSequence;
}
}
salesSequence.nextValue();获取下一个序列号
//注入两个不同的生成器
@Autowired
private DefaultRangeSequence circularRangeSequence;
@Autowired
private DefaultRangeSequence salesSequence;
@GetMapping("serialNumber")
public ResponseEntity serialNumber(){
return ResponseEntity.ok(circularRangeSequence.nextValue());
}
@GetMapping("sales")
public ResponseEntity salesNumber(){
for (int i = 0; i < 500; i++) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(salesSequence.nextValue());
}
}).start();
}
return ResponseEntity.ok(salesSequence.nextValue());
}
优势很明显,上手即用方便快捷;
缺点:有一定的局限性、扩展能力较差,比如如果要按照时间段初始化序列号,改起来就有点麻烦了。