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

com.yuweix.kuafu.sequence.dao.SingleSequenceDao Maven / Gradle / Ivy

The newest version!
package com.yuweix.kuafu.sequence.dao;


import javax.sql.DataSource;
import com.yuweix.kuafu.sequence.bean.SequenceHolder;
import com.yuweix.kuafu.sequence.exception.SequenceException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;


/**
 * @author yuwei
 */
public class SingleSequenceDao extends AbstractSequenceDao {
	private static final Logger log = LoggerFactory.getLogger(SingleSequenceDao.class);


	private DataSource dataSource;

	public SingleSequenceDao() {

	}

	@Override
	public void init() {
		Assert.notNull(dataSource, "The [dataSource] is required.");
		super.init();
	}

	@Override
	public void ensure(String seqName, long minValue) {
		if (minValue < 0) {
			minValue = 0;
		}

		Long oldValue = selectSeqValue(0, seqName);
		if (oldValue == null) {
			insertSeq(0, seqName, minValue);
		} else if (oldValue < minValue) {
			updateSeqValue(0, seqName, oldValue, minValue);
		}
	}

	@Override
	public SequenceHolder nextRange(String seqName) {
		Assert.notNull(seqName, "The [seqName] is required.");

		int retryTimes = getRetryTimes();
		for (int i = 0; i < retryTimes + 1; ++i) {
			Long oldValue = selectSeqValue(0, seqName);

			if (oldValue == null || oldValue < 0L || oldValue > Long.MAX_VALUE - 100000000L) {
				throw new SequenceException("Invalid value, seqName = " + seqName + ", value = " + oldValue + ".");
			}

			long newValue = oldValue + getInnerStep();
			try {
				updateSeqValue(0, seqName, oldValue, newValue);
			} catch(Exception e) {
				log.warn("Failure to get next range of [{}], err: {}", seqName, e.getMessage());
				continue;
			}
			return new SequenceHolder(oldValue + 1L, newValue);
		}
		throw new SequenceException("Retried too many times, retryTimes = " + retryTimes);
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	@Override
	protected DataSource getDataSource(int segment) {
		return dataSource;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy