此處以SpringBoot
為例,示范如何使用Redis
構造全局唯一標識.
1. RedisTemplate配置
spring.redis.database = 0
spring.redis.host = **
spring.redis.port = 6379
spring.redis.password = **
spring.redis.lettuce.pool.max-wait = 1000ms
以上配置,參照實際情況進行設置.,
2.Java服務中Redis配置
@Repository
@Slf4j
public class RedisCounterRepository {
private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
private RedisTemplate<String, Object> redisTemplate;
@Autowired
public RedisCounterRepository(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
// 根據獲取的自增數據,添加日期標識構造分布式全局唯一標識
private String getNumFromRedis(String changeNumPrefix) {
String dateStr = LocalDate.now().format(dateTimeFormatter);
Long value = incrementNum(changeNumPrefix + dateStr);
return dateStr + StringUtils.leftPad(String.valueOf(value), 4, '0');
}
// 從redis中獲取自增數據(redis保證自增是原子操作)
private long incrementNum(String key) {
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
if (null == factory) {
log.error("Unable to connect to redis.");
throw new UserException(AppStatus.INTERNAL_SERVER_ERROR);
}
RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, factory);
long increment = redisAtomicLong.incrementAndGet();
if (1 == increment) {
// 如果數據是初次設置,需要設置超時時間
redisAtomicLong.expire(1, TimeUnit.DAYS);
}
return increment;
}
PS:
如果您覺得我的文章對您有幫助,請關注我的微信公眾號,謝謝!