Skip to content

Add getHashTag() to JedisClusterCRC16 for future use #728

@allanwax

Description

@allanwax

The redis cluster spec. specifically allows multi-key operation like MSET as long as the same hashtag is specified for all keys. Currently there is no MSET defined in JedisCluster (and other multi-key functions).

For future development CRC16 should be modified to allow the hashtag to be obtained. Using this, operations like MSET can be implemented with a check for consistent hashtag definitions on the keys and then pipe-lined as a single operation maintaining atomicity.

Here's a suggested implementation:

public class JedisClusterCRC16 {
public final static int polynomial = 0x1021; // Represents x^16+x^12+x^5+1

public static String getHashTag(String key) {
    int s = key.indexOf("{");
    if (s > -1) {
        int e = key.indexOf("}", s + 1);
        if (e > -1 && e != s + 1) {
            key = key.substring(s + 1, e);
        }
    }

    return key;
}

public static int getSlot(String key) {
    return getCRC16(getHashTag(key)) % 16384;
}

private static int getCRC16(String key) {
    int crc = 0x0000;
    for (byte b : key.getBytes()) {
        for (int i = 0; i < 8; i++) {
            boolean bit = ((b >> (7 - i) & 1) == 1);
            boolean c15 = ((crc >> 15 & 1) == 1);
            crc <<= 1;
            // If coefficient of bit and remainder polynomial = 1 xor crc
            // with polynomial
            if (c15 ^ bit)
                crc ^= polynomial;
        }
    }

    return crc &= 0xffff;
}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions