All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sghd.common.utils.id.account.AccountMultiServerIdGenerator Maven / Gradle / Ivy

The newest version!
package com.sghd.common.utils.id.account;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.sghd.common.utils.id.MultiServerIdGenerator;

/**
 * 多服的主键生成器
 */
public class AccountMultiServerIdGenerator implements MultiServerIdGenerator {

	/** 主键生成器映射 */
	private ConcurrentMap generators = new ConcurrentHashMap();

	/**
	 * 主键生成器映射键值
	 */
	private int getKey(short operator, short server) {
		return (operator << 12) + server;
	}

	public boolean isInit(short operator, short server) {
		int key = getKey(operator, server);
		if (generators.containsKey(key)) {
			return true;
		}
		return false;
	}

	/**
	 * 添加指定服标识的主键生成器
	 * @param area 服标识
	 * @param max 当前的主键最大值
	 */
	public void init(short operator, short area, Long max) {
		int key = getKey(operator, area);
		if (generators.containsKey(key)) {
			throw new IllegalStateException("运营商[" + operator + "]服务器[" + area + "]的主键生成器已存在");
		}
		AccountIdGenerator generator = new AccountIdGenerator(operator, area, max);
		generators.putIfAbsent(key, generator);
	}

	/**
	 * 获取下一个自增主键
	 * @param area 服标识
	 * @return
	 */
	public long getNext(short operator, short area) {
		int key = getKey(operator, area);
		AccountIdGenerator generator = generators.get(key);
		if (generator == null) {
			throw new IllegalStateException("运营商[" + operator + "]服务器[" + area + "]的主键生成器不存在");
		}
		return generator.getNext();
	}

	@Override
	public long[] getLimits(short operator, short area) {
		return AccountIdGenerator.getLimits(operator, area);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy