Java服务使用Redis实现分布式全局唯一标识

此处以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:
如果您觉得我的文章对您有帮助,请关注我的微信公众号,谢谢!
程序员打怪之路

posted @ 2019-03-19 12:45  从此寂静无声  阅读(1504)  评论(0编辑  收藏  举报