文章来源:https://www.toymoban.com/news/detail-607498.html
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@Component
public class RedisIdWorker {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private static final long BEGIN_TIMESTAMP = 1672531200L;
private static final int COUNT_BITS = 32;
public long nextId(String keyPrefix) {
//生成时间戳
LocalDateTime now = LocalDateTime.now();
long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
long timestamp = nowSecond - BEGIN_TIMESTAMP;
//生成序列号
//获取当前日期,精确到天
String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
//拼接并返回
return timestamp << COUNT_BITS | count;
}
}
测试文章来源地址https://www.toymoban.com/news/detail-607498.html
package com.hmdp;
import com.hmdp.service.impl.ShopServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Primary;
import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@SpringBootTest
class ApplicationTests {
@Autowired
private RedisIdWorker redisIdWorker;
//线程池500个
private ExecutorService es = Executors.newFixedThreadPool(500);
@Test
void testIdWorker() throws InterruptedException {
//开启一个倒计时的插销
CountDownLatch countDownLatch = new CountDownLatch(300);
//开启线程
Runnable task = () -> {
for (int i = 0; i < 100; i++) {
long order = redisIdWorker.nextId("order");
System.out.println(order);
}
//倒计时-
countDownLatch.countDown();
};
long begin = System.currentTimeMillis();
for (int i = 0; i < 300; i++) {
es.submit(task);
}
//当倒计时为0立马停止等待
countDownLatch.await();
long end = System.currentTimeMillis();
System.out.println(end - begin);
}
}
到了这里,关于redis实现全局唯一id的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!