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

uw.task.TaskScheduler Maven / Gradle / Ivy

Go to download

uw-task包是一个分布式任务框架,通过uw-task可以快速构建基于docker的分布式任务体系,同时支持基于influx的任务运维监控。

The newest version!
package uw.task;

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.postprocessor.GUnzipPostProcessor;
import org.springframework.amqp.support.postprocessor.GZipPostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

import uw.task.mq.TaskConsumer;
import uw.task.util.GlobalSequenceManager;

/**
 * 任务执行器。 通过调用此类,可以实现队列执行,RPC调用,本地调用等功能。
 * 
 * @author axeon
 *
 */
@Component
public class TaskScheduler {

	private static final Logger log = LoggerFactory.getLogger(TaskScheduler.class);

	/**
	 * rabbitTemplate模板
	 */
	@Autowired
	private AmqpTemplate rabbitTemplate;

	/**
	 * 全局sequence序列,主要用于taskLog日志。
	 */
	@Autowired
	private GlobalSequenceManager sequence;

	/**
	 * 用于本地执行任务的taskConsumer。
	 */
	@Autowired
	private TaskConsumer taskConsumer;

	@Autowired
	ObjectMapper objectMapper;

	/**
	 * 线程池。
	 */
	private ExecutorService executorService = Executors
			.newCachedThreadPool(new ThreadFactoryBuilder().setDaemon(true).setNameFormat("TaskScheduler-%d").build());

	/**
	 * 转换器用Jackson2JsonMessageConverter,用于json转换实体类对象。 支持gzip压缩。
	 * 
	 * @param connectionFactory
	 * @return
	 */
	@Bean
	private RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
		RabbitTemplate template = new RabbitTemplate(connectionFactory);
		template.setMessageConverter(new Jackson2JsonMessageConverter());
		template.setBeforePublishPostProcessors(new GZipPostProcessor());
		template.setAfterReceivePostProcessors(new GUnzipPostProcessor());
		template.setReplyTimeout(60000);
		template.afterPropertiesSet();
		return template;
	}

	/**
	 * 把任务发送到队列中
	 * 
	 * @param taskdata
	 *            任务数据
	 */
	public void sendToQueue(TaskData taskdata) {
		sendToQueue("", taskdata);
	}

	/**
	 * 把任务发送到队列中。
	 * 
	 * @param runTarget
	 *            目标主机配置名,如果没有,则为空
	 * @param taskData
	 */
	public void sendToQueue(String runTarget, TaskData taskData) {
		taskData.setId(sequence.nextId("task_runner_log"));
		taskData.setQueueDate(new Date());
		taskData.setRunType(TaskData.RUN_TYPE_GLOBAL);
		String queue = taskData.getTaskClass() + "$" + (runTarget == null ? "" : runTarget);
		rabbitTemplate.convertAndSend(queue + "@exchange", queue + "@route", taskData);
	}

	/**
	 * 远程运行任务,并返回future>。 如果需要获得数据,可以使用futrue.get()来获得。
	 * 
	 * @param taskData
	 *            任务数据
	 * @return
	 */
	public  Future> runTask(TaskData taskData,
			TypeReference> typeRef) {
		return runTask("", taskData, typeRef);
	}

	/**
	 * 远程运行任务,并返回future>。 如果需要获得数据,可以使用futrue.get()来获得。
	 * 
	 * @param runTarget
	 *            目标主机配置名,如果没有,则为空
	 * @param taskData
	 *            任务数据
	 * @return
	 */
	public  Future> runTask(String runTarget, TaskData taskData,
			TypeReference> typeRef) {
		taskData.setId(sequence.nextId("task_runner_log"));
		taskData.setQueueDate(new Date());
		taskData.setRunType(TaskData.RUN_TYPE_GLOBAL_RPC);
		Future> future = executorService.submit(new Callable>() {
			@SuppressWarnings("unchecked")
			public TaskData call() {
				// 返回数据
				String queue = taskData.getTaskClass() + "$" + (runTarget == null ? "" : runTarget);
				TaskData retdata = (TaskData) rabbitTemplate.convertSendAndReceive(queue + "@exchange",
						queue + "@route", taskData);
				if (typeRef != null) {
					try {
						retdata = objectMapper.convertValue(retdata, typeRef);
					} catch (Exception e) {
						log.error(e.getMessage(), e);
					}
				}
				return retdata;
			}
		});
		return future;
	}

	/**
	 * 异步方式本地直接运行任务。
	 * 
	 * @param taskData
	 */
	public  Future> runTaskLocal(TaskData taskData) {
		Future> future = executorService.submit(new Callable>() {
			public TaskData call() {
				taskData.setId(sequence.nextId("task_runner_log"));
				taskData.setQueueDate(new Date());
				taskData.setRunType(TaskData.RUN_TYPE_LOCAL);
				return taskData;
			}
		});
		return future;
	}

	/**
	 * 本地直接运行任务。 在此执行任务,可能会导致阻塞。
	 * 
	 * @param taskData
	 */
	public  TaskData runTaskLocalSync(TaskData taskData) {
		taskData.setId(sequence.nextId("task_runner_log"));
		taskData.setQueueDate(new Date());
		taskData.setRunType(TaskData.RUN_TYPE_LOCAL);
		taskConsumer.process(taskData);
		return taskData;

	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy