电商分布式订单号生成
·
import cn.hutool.core.collection.ConcurrentHashSet;
import com.baseus.mall.common.utils.OrderSnUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@RunWith(SpringRunner.class)
@SpringBootTest
public class OrderGenericTest {
@Autowired
RedisTemplate redisTemplate;
/**
* 生成订单号
*/
@Test
public void genericOrderNo() {
Set<String> sns = new ConcurrentHashSet<>(50000);
List<Thread> list = new ArrayList<>(50);
OrderSnUtil orderSnUtil = new OrderSnUtil(1);
for (int i = 0; i < 500; i++) {
list.add(new Thread(() -> {
for (int ii = 0; ii < 1000; ii++) {
String sn = getOrderId("No");
sns.add(sn);
}
}));
}
long time = System.currentTimeMillis();
list.forEach(e -> e.start());
list.forEach(e -> {
try {
e.join();
} catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
});
time = System.currentTimeMillis() - time;
System.out.println("cost=" + time + ", num=" + sns.size());
sns.forEach(System.out::println);
}
public String getOrderId(String prefix) {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// String time = sdf.format(new Date());
String time = LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis()), ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyMMddHHmmssSSS"));
//当天流水7位
Long tx = redisTemplate.opsForValue().increment("OUR_ORDER_ID_INCREMENT_KEY", 1);
return prefix + time + tx;
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)