Universal database primary key generator widget

1. Solve the problem

1.1. When the amount of data rises to a certain level, the data needs to be stored in separate tables and cached (generally common in redis);

1.2. The data generally has a unique primary key. After the table is divided, it is generally necessary to ensure that the ids of all tables are not conflicted and consistent.

2. How to use and features:

2.1. How to use:

public class Util extends RedisSequenceFactory {

    
}

At the same time, you can complete the code writing of Util. generateLongKey() returns the Id primary key, and getStepLength() returns the step length by the subclass;

2.2. Features: The extended class needs to be initialized, otherwise it cannot be compiled by the compiler;

3. Simplified design code

import redis.clients.jedis.JedisCommands;

public abstract class RedisSequenceFactory {
    private  boolean inited = false;
    private  Long starterIndex;
    private  JedisCommands jedis;
    private  Class clazz;
    private RedisSequenceFactory() {

    }
    protected RedisSequenceFactory(Long starterIndex, JedisCommands jedis, Class clazz) {
        this.starterIndex = starterIndex;
        this.jedis = jedis;
        this.clazz = clazz;
        inited = true;
    }
    public Long generateLongKey() {
        String key = clazz.getName();
        long nextIndex;
        synchronized (jedis) {
            nextIndex = jedis.incrBy(key, getStepLength());
        }
        return nextIndex;
    }
    public abstract int getStepLength();
}

4.TIP:

The relevant code to improve performance can be implemented by itself, and the company currently has enough. Modifying while waiting for the card

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324897432&siteId=291194637