NutzCN Logo
问答 求推荐一个支持高并发,不重复的订单号生成算法
发布于 2922天前 作者 Mr-GaoSai 2306 次浏览 复制 上一个帖子 下一个帖子
标签:

rt
求推荐一个支持高并发,不重复的订单号生成算法

5 回复
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.nutz.ioc.loader.annotation.IocBean;

@IocBean
public class IdGenerator implements Runnable {

	private String time;

	private AtomicInteger value;

	private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

	private Thread thread;

	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
	
	public IdGenerator() {
		time = LocalDateTime.now().format(FORMATTER);
		value = new AtomicInteger(1);
		thread = new Thread(this);
		thread.setDaemon(true);
		thread.start();
	}

	public String next() {
		lock.readLock().lock();
		StringBuffer sb = new StringBuffer(time).append(value.getAndIncrement());
		lock.readLock().unlock();
		return sb.toString();
	}
	
	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(1000 * 1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			String now = LocalDateTime.now().format(FORMATTER);
			if (!now.equals(time)) {
				lock.writeLock().lock();
				time = now;
				value.set(1);
				lock.writeLock().unlock();
			}
		}
	}

}

自己测试去

基于时间的? 这个只能单进程吧?

添加回复
请先登陆
回到顶部