单线程service服务
1.@Service修饰类名,同时类继承Thread类
@Service
public class MasterSchedulerService extends Thread {
/**
* logger of MasterSchedulerService
*/
private static final Logger logger = LoggerFactory.getLogger(MasterSchedulerService.class);
@Autowired
private ServerConfig serverConfig;
/**
* dolphinscheduler database interface
*/
@Autowired
private ProcessService processService;
/**
* zookeeper master client
*/
@Autowired
private ZKClient zkClient;
/**
* master exec service
*/
private ThreadPoolExecutor masterExecService;
@Autowired
private FamaVmMapper vmMapper;
/**
* constructor of MasterSchedulerService
*/
@PostConstruct
public void init(){
this.masterExecService = (ThreadPoolExecutor) ThreadUtils.newDaemonFixedThreadExecutor("Server-Thread"
, serverConfig.getMasterExecThreads());
}
@Override
public synchronized void start(){
super.setName("MasterSchedulerService");
super.start();
}
public void close() {
masterExecService.shutdown();
boolean terminated = false;
try {
terminated = masterExecService.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException ignore) {
Thread.currentThread().interrupt();
}
if(!terminated){
logger.warn("masterExecService shutdown without terminated, increase await time");
}
logger.info("master schedule service stopped...");
}
/**
* run of MasterSchedulerService
*/
@Override
public void run() {
logger.info("master scheduler started");
while (Stopper.isRunning()){
try {
if (zkClient.getZkClient().getState() == CuratorFrameworkState.STARTED) {
scheduleProcess();
}
} catch (Exception e) {
logger.error("master scheduler thread error", e);
}
}
}
private void scheduleProcess() throws Exception {
InterProcessMutex mutex = null;
try {
mutex = zkClient.blockAcquireMutex();
// make sure to scan and delete command table in one transaction
Command command = processService.findOneCommand();
if (command != null) {
logger.info("find one command: {}", JsonUtils.toJSONString(command));
try {
String address = getLocalAddress();
ResourceInstance processInstance = processService.handleCommand(address,command);
logger.info("processInstance: {}", JsonUtils.toJSONString(processInstance));
if (processInstance != null) {
MapperContext context = new MapperContext();
context.vmMapper = vmMapper;
MasterExecThread execThread = new MasterExecThread(
processInstance
, processService
, serverConfig
, context);
masterExecService.execute(execThread);
}
} catch (Exception e) {
logger.error("Command consumer error ", e);
// processService.moveToErrorCommand(command, e.toString());
}
} else {
//indicate that no command ,sleep for 1s
Thread.sleep(Constants.SLEEP_TIME_MILLIS);
}
} finally {
zkClient.releaseMutex(mutex);
}
}
private String getLocalAddress() {
return NetUtils.getAddr(serverConfig.getListenPort());
}
}
2.执行时,直接执行start方法
@ComponentScan(value = {"fama.cost"})
public class FamaServerApplication implements IStoppable {
private static final Logger logger = LoggerFactory.getLogger(FamaServerApplication.class);
@Autowired
private MasterSchedulerService schedulerService;
@Autowired
private SpringApplicationContext springApplicationContext;
@Autowired
private BeanContext beanContext;
@Autowired
private ZKClient zkClient;
public static void main(String[] args) {
Thread.currentThread().setName("Schedule-Server");
new SpringApplicationBuilder(FamaServerApplication.class).web(WebApplicationType.NONE).run(args);
int currentProcessPid = getProcessID();
logger.info("Current Process Pid : {}",currentProcessPid);
}
@PostConstruct
public void run() {
this.zkClient.start(this);
this.schedulerService.start();
try {
logger.info("start Quartz server...");
QuartzExecutors.getInstance().start();
} catch (Exception e) {
try {
QuartzExecutors.getInstance().shutdown();
} catch (SchedulerException e1) {
logger.error("QuartzExecutors shutdown failed : " + e1.getMessage(), e1);
}
logger.error("start Quartz failed", e);
}
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
if (Stopper.isRunning()) {
close("shutdownHook");
}
}
}));
}
public void close(String cause) {
try {
//execute only once
if (Stopper.isStopped()) {
return;
}
logger.info("master server is stopping ..., cause : {}", cause);
// set stop signal is true
Stopper.stop();
try {
//thread sleep 3 seconds for thread quietly stop
Thread.sleep(3000L);
} catch (Exception e) {
logger.warn("thread sleep exception ", e);
}
//close
this.schedulerService.close();
this.zkClient.close();
//close quartz
try {
QuartzExecutors.getInstance().shutdown();
logger.info("Quartz service stopped");
} catch (Exception e) {
logger.warn("Quartz service stopped exception:{}", e.getMessage());
}
} catch (Exception e) {
logger.error("master server stop exception ", e);
} finally {
// System.exit(-1);
}
}
@Override
public void stop(String cause) {
close(cause);
}
public static final int getProcessID() {
try {
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
return Integer.valueOf(runtimeMXBean.getName().split("@")[0]).intValue();
}catch (Exception ex){
logger.error(ex.getMessage(),ex);
return 0;
}
}
}
单线程service服务的更多相关文章
- 解决VMWARE NAT SERVICE服务无法启动或服务消失的问题
解决VMWARE NAT SERVICE服务无法启动或服务消失的问题 2016-02-02 11:18 2012人阅读 评论(2) 收藏 举报 分类: 网络通信(3) 今日使用VMware中的Wi ...
- 使用axis开发web service服务端
一.axis环境搭建 1.安装环境 JDK.Tomcat或Resin.eclipse等. 2.到 http://www.apache.org/dyn/closer.cgi/ws/axis/1_4下载A ...
- win7提示“User Profile Service服务未能登录”
注:本文由Colin撰写,版权所有!转载请注明原文地址,谢谢合作! 最近,有个同事打电话告诉我说他的用户名无法登陆到系统,提示“User Profile Service服务未能登录,无法加载用户配置文 ...
- Android 通过JNI实现守护进程,使得Service服务不被杀死
来自: http://finalshares.com/read-7306 转载请注明出处: http://blog.csdn.net/yyh352091626/article/details/5054 ...
- Service服务
Android多线程: 定义线程的2种方式: 1.继承Thread类,重写run()方法,new一个实例,用start()方法启动:new MyThread().start(); 2.实现Runnab ...
- Centos6.5 设置Tomcat8 service服务实现自启动和服务管理
Centos6.5 设置Tomcat8 service服务实现自启动和服务管理 将tomcat设置成像apache,nginx一样. 用serviec xxxx start/stop/restart ...
- Android 综合揭秘 —— 全面剖释 Service 服务
引言 Service 服务是 Android 系统最常用的四大部件之一,Android 支持 Service 服务的原因主要目的有两个,一是简化后台任务的实现,二是实现在同一台设备当中跨进程的远程信息 ...
- win8.1 user profile service 服务登录失败
在Win 8.1 上新建个用户后,不能登录. 出现 user profile service 服务登录失败. 无法加载用户配置文件. 网上大部分相同提示的问题是有关已有账号不能再次登陆的. 解决方式是 ...
- Android中Service(服务)详解
http://blog.csdn.net/ryantang03/article/details/7770939 Android中Service(服务)详解 标签: serviceandroidappl ...
随机推荐
- c协程库libco几点体会
https://www.cnblogs.com/dearplain/p/9820913.html 这里说的是Tencent开源的libco. libco的用途和依赖 主要还是c/c++服务端,相比li ...
- wordpress current_user_can 判断角色
current_user_can 使用说明: current_user_can( $capability, $args ); $capability参数是必须的,是指给予什么样的能力,或者说给他可以做 ...
- hdu3715 二分+2sat+建图
题意: 给你一个递归公式,每多一层就多一个限制,问你最多能递归多少层. 思路: 先分析每一层的限制 x[a[i]] + x[b[i]] != c[i],这里面x[] = 0,1, ...
- Python编写基于socket的非阻塞多人聊天室程序(单线程&多线程)
前置知识:socket非阻塞函数(socket.setblocking(False)),简单多线程编程 代码示例: 1. 单线程非阻塞版本: 服务端: #!/usr/bin/env python # ...
- Sublim text3汉化
Sublime text3汉化步骤: 一.打开已安装好的Sublime text3 二.打开后点击"Preferences",在弹出的选项中找到package Control. 三 ...
- raft协议
一.Raft一致性算法 Eureka:Peer To Peer,每个节点的地位都是均等的,每个节点都可以接收写入请求,每个节点接收请求之后,进行请求打包处理,异步化延迟一点时间,将数据同步给 Eure ...
- 是时候学习Linux了
前言: Linux是一个开源.免费的操作系统.其稳定性.安全性.处理多并发已经得到业界的认可,目前很多企业级的项目都会部署到Linux/unix系统上.如果你还不太了解Linux,希望本篇文章能够带你 ...
- centos7安装es6.4.0
一.首先进入到opt文件夹cd opt二.然后下载es安装包wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearc ...
- Linux上的Shebang符号(#!)
使用Linux或者unix系统的同学可能都对#!这个符号并不陌生,但是你真的了解它吗? 本文了将给你简单介绍一下Shebang("#!")这个符号. 首先,这个符号(#!)的名称, ...
- osg纯手工画球+贴纹理
手动计算球面顶点的坐标,纹理坐标,来画球并贴纹理 其中createSphereGeom()函数的的二个参数为18,意思是在经纬度上每10度设一个点,因为经度一共是180度,180/18=10,相当于横 ...