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

gu.simplemq.BaseMQSender Maven / Gradle / Ivy

There is a newer version: 2.3.17
Show newest version
package gu.simplemq;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkArgument;

import java.util.Collection;
import java.util.Collections;

import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.base.Throwables;
import com.google.common.collect.Collections2;
import gu.simplemq.Channel;
import gu.simplemq.IProducer;
import gu.simplemq.json.BaseJsonEncoder;
import gu.simplemq.pool.BaseMQPool;
import gu.simplemq.pool.BaseMQPool.MQPoolException;

/**
 * {@link IProducer},{@link IPublisher} 实现基类
 * @param  消息系统的CLIENT实例类型
 * @author guyadong
 *
 */
public abstract class BaseMQSender  {
	private final static BaseJsonEncoder encoder = BaseJsonEncoder.getEncoder();
	private final static Function jsonFun = new Function(){
		@Override
		public String apply(Object input) {
			return encoder.toJsonString(input);
		}};
	protected final BaseMQPool pool;
	
	public BaseMQSender(BaseMQPool poolLazy) {
		super();
		this.pool = checkNotNull(poolLazy,"poolLazy is null");
	}

	/**
	 * 执行消息发送
	 * @param c
	 * @param channel 频道名
	 * @param messages 待发送的消息集合(不包含为{@code null}的元素)
	 * @throws Exception
	 */
	abstract protected void doSend(C c,String channel,Iterable messages) throws Exception;

	protected  void doProduce(Channel channel, Collectionc) {
		checkArgument(channel != null, "channel is null");
		Collection jsons = asJsons(c);
		if(jsons.isEmpty()){
			return ;
		}
		C client = null;
		try{
			client = pool.apply();
			doSend(client, channel.name, jsons);
		} catch (MQPoolException e) {
			throw new MQConnectionException(e);
		}catch (Throwable e) {
			Throwables.throwIfInstanceOf(e, MQConnectionException.class);
			Throwables.throwIfInstanceOf(e, MQRuntimeException.class);
			throw new MQRuntimeException(e);
		} finally{
			if(client != null){
				pool.free();
			}
		}	
	}

	private static  Collection asJsons(Collectionc){
		if(null == c ) {
			return Collections.emptyList();
		}
		Collection iterable = Collections2.filter(c,Predicates.notNull());
		Collection jsons = Collections2.transform(iterable, jsonFun);
		return jsons;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append(getClass().getSimpleName() + " [pool=");
		builder.append(pool);
		builder.append("]");
		return builder.toString();
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy