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

com.alibaba.tmq.common.util.IdAndKeyUtil Maven / Gradle / Ivy

package com.alibaba.tmq.common.util;

import java.util.List;
import java.util.UUID;

import com.alibaba.tmq.client.util.StringUtil;
import com.alibaba.tmq.common.constants.Constants;
import com.alibaba.tmq.common.domain.Message;
import com.alibaba.tmq.common.exception.TMQClientException;
import com.alibaba.tmq.common.exception.TMQException;

/**
 * IdAndKey相关工具
 * @author tianyao.myc
 *
 */
public class IdAndKeyUtil implements Constants {
	
	/**
	 * 获取全局唯一ID
	 *
	 */
	public static String acquireUniqueId() {
		return UUID.randomUUID().toString().toUpperCase().replace(HORIZONTAL_LINE, "");
	}
	
	/**
	 * 获取业务全局唯一Key
	 *  messageId
	 *  message
	 *
	 *  TMQException
	 */
	public static String acquireUniqueKey(String messageId, Message message) throws TMQException {
		
		//如果用户未设置业务全局唯一Key 就系统生成的消息ID
		if(StringUtil.isBlank(message.getMessageKey())) {
			return message.getTopic() + SPLIT_STRING + messageId;
		}
		
		if(! RegularExpressionUtil.correctName(message.getMessageKey())) {
			throw new TMQClientException("messageKey can only contains a-z or A-Z or 0-9 or . or - or _ ");
		}
		
		return message.getTopic() + SPLIT_STRING + message.getMessageKey();
		
	}
	
	/**
	 * 渲染MessageKey
	 *  producerId
	 *  message
	 *  TMQException
	 */
	public static void renderingMessageKey(String producerId, Message message) throws TMQException {
		
		message.setProducerId(producerId);//设置producerId
		
		//如果用户未设置业务全局唯一Key 就用系统生成的消息ID
		if(StringUtil.isBlank(message.getMessageKey())) {
			message.setMessageKey(message.getTopic() + SPLIT_STRING + message.getMessageId());
			return ;
		}
		
		if(! RegularExpressionUtil.correctName(message.getMessageKey())) {
			throw new TMQClientException("messageKey can only contains a-z or A-Z or 0-9 or . or - or _ ");
		}
		
		message.setMessageKey(message.getTopic() + SPLIT_STRING + message.getMessageKey());
	}
	
	/**
	 * 批量渲染MessageKey
	 *  producerId
	 *  messageList
	 *  TMQException
	 */
	public static void renderingMessageKey(String producerId, List messageList) throws TMQException {
		
		for(Message message : messageList) {
			
			//渲染MessageKey
			renderingMessageKey(producerId, message);
		}
		
	}
	
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy