叢集環境下指定機器執行後臺定時任務
阿新 • • 發佈:2022-04-04
叢集環境下,機器會有多個,需要執行某個或者多個機器執行後臺任務,否則可能會一個數據多個機器同時處理導致bug。這在實際工作中很常見。最近專案中也有類似需求,下面是一種實現方式,供大家參考。
使用 @Conditional 註解,判斷是本機ip才載入對應的任務的service,非配置的ip的機器則不會載入到spring容器。
IP判斷類
package cn.xiaowenjie.iptask;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import java.net.InetAddress;
/**
* 判斷是否為本機ip
*
* @author 曉風輕
*/
@Slf4j
public class IPCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
String runTaskIP = conditionContext.getEnvironment().getProperty("run.task.ip");
String localIP = this.getLocalIP();
log.info("local ip: {} , run Task IP: {}" ,localIP , runTaskIP);
return runTaskIP.equals(localIP);
}
@SneakyThrows
public String getLocalIP(){
InetAddress address = InetAddress.getLocalHost();
return address.getHostAddress();
}
}
後臺任務類
package cn.xiaowenjie.iptask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Conditional;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
/**
* 後臺定時任務
*
* @author 曉風輕
*/
@Service
@Slf4j
@Conditional(IPCondition.class)
public class BackService {
@PostConstruct
public void init(){
log.info("i run task...");
}
@Scheduled(cron = "0/10 * * * * *")
public void scheduleTask(){
log.info("task running....");
}
}
實際效果
[ main] cn.xiaowenjie.iptask.IPCondition : local ip: 192.168.1.101 , run Task IP: 192.168.1.101 [ main] cn.xiaowenjie.iptask.IPCondition : local ip: 192.168.1.101 , run Task IP: 192.168.1.101 [ main] cn.xiaowenjie.iptask.IPCondition : local ip: 192.168.1.101 , run Task IP: 192.168.1.101 [ main] cn.xiaowenjie.iptask.BackService : i run task... [ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'taskScheduler' [ main] cn.xiaowenjie.iptask.IptaskApplication : Started IptaskApplication in 1.364 seconds (JVM running for 2.098) [ scheduling-1] cn.xiaowenjie.iptask.BackService : task running.... [ scheduling-1] cn.xiaowenjie.iptask.BackService : task running.... [ scheduling-1] cn.xiaowenjie.iptask.BackService : task running.... [ scheduling-1] cn.xiaowenjie.iptask.BackService : task running....