RequestIdGenerator - minbox-projects/message-pipe GitHub Wiki

服务端(Server)每一次分发消息到客户端(Client)时,都会生成一个唯一的请求ID,默认则使用 minbox-sequence 方式。

1. 自定义生成请求ID

消息ID是通过RequestIdGenerator接口进行定义生成的,所以我们只需要实现该接口就可以实现我们自定义的生成逻辑,如下所示:

/**
 * 自定义请求ID生成方式
 *
 * @author 恒宇少年
 */
public class CustomRequestIdGenerator implements RequestIdGenerator {
    @Override
    public String generate() {
        // 获取uuid处理后的hash值
        long hash = this.nextShortId();
        // 转换后返回
        return Long.toUnsignedString(hash, 32);
    }

    private long nextShortId() {
        UUID uuid = UUID.randomUUID();
        long h = uuid.getMostSignificantBits();
        long l = uuid.getLeastSignificantBits();

        byte[] bytes = new byte[16];
        bytes[0] = (byte) ((h >>> 56) & 0xFF);
        bytes[1] = (byte) ((h >>> 48) & 0xFF);
        bytes[2] = (byte) ((h >>> 40) & 0xFF);
        bytes[3] = (byte) ((h >>> 32) & 0xFF);
        bytes[4] = (byte) ((h >>> 24) & 0xFF);
        bytes[5] = (byte) ((h >>> 16) & 0xFF);
        bytes[6] = (byte) ((h >>> 8) & 0xFF);
        bytes[7] = (byte) (h & 0xFF);

        bytes[8] = (byte) ((l >>> 56) & 0xFF);
        bytes[9] = (byte) ((l >>> 48) & 0xFF);
        bytes[10] = (byte) ((l >>> 40) & 0xFF);
        bytes[11] = (byte) ((l >>> 32) & 0xFF);
        bytes[12] = (byte) ((l >>> 24) & 0xFF);
        bytes[13] = (byte) ((l >>> 16) & 0xFF);
        bytes[14] = (byte) ((l >>> 8) & 0xFF);
        bytes[15] = (byte) (l & 0xFF);

        return Hashing.murmur3_128().hashBytes(bytes).asLong();
    }
}

2. 启用自定义生成请求ID方式

@Bean
public MessagePipeConfiguration messagePipeConfiguration() {
    MessagePipeConfiguration configuration = MessagePipeConfiguration.defaultConfiguration();
    // 替换默认的生成方式
    configuration
            .setRequestIdGenerator(new CustomRequestIdGenerator());
    return configuration;
}

请求过程中也是需要消耗时间的,所以尽可能的采用较短的ID。