配置xxljob
@AutoConfiguration
@ConditionalOnClass(XxlJobSpringExecutor.class)
@ConditionalOnProperty(prefix = "xxl.job", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties({XxlJobProperties.class})
@EnableScheduling // 开启 Spring 自带的定时任务
@Slf4j
public class SfXxlJobAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public XxlJobExecutor xxlJobExecutor(XxlJobProperties properties) {
log.info("[xxlJobExecutor][初始化 XXL-Job 执行器的配置]");
XxlJobProperties.AdminProperties admin = properties.getAdmin();
XxlJobProperties.ExecutorProperties executor = properties.getExecutor();
// 初始化执行器
XxlJobExecutor xxlJobExecutor = new XxlJobSpringExecutor();
if (StrUtils.isBlank(executor.getIp())) {
log.info("xxl.job.executor.ip 未配置,使用本地 IP({}) 作为执行器的 IP" + IpUtil.getServerIp());
xxlJobExecutor.setIp(IpUtil.getServerIp());
} else {
log.info("xxl.job.executor.ip 配置为 " + executor.getIp() + ",使用配置的 IP 作为执行器的 IP");
xxlJobExecutor.setIp(executor.getIp());
}
xxlJobExecutor.setPort(executor.getPort());
xxlJobExecutor.setAppname(executor.getAppName());
xxlJobExecutor.setLogPath(executor.getLogPath());
xxlJobExecutor.setLogRetentionDays(executor.getLogRetentionDays());
xxlJobExecutor.setAdminAddresses(admin.getAddresses());
xxlJobExecutor.setAccessToken(properties.getAccessToken());
return xxlJobExecutor;
}
}
自己写一个获取ip的方法
@Slf4j
public class IpUtil {
/**
* 获取本地IP地址
*/
public static String getServerIp() {
if (isWindowsOs()) {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
return "";
}
} else {
return getLinuxLocalIp();
}
}
/**
* 判断操作系统是否是Windows
*/
public static boolean isWindowsOs() {
boolean isWindowsOs = false;
String osName = System.getProperty("os.name");
if (osName.toLowerCase().contains("windows")) {
isWindowsOs = true;
}
return isWindowsOs;
}
/**
* 获取Linux下的IP地址
*
* @return IP地址
*/
private static String getLinuxLocalIp() {
String ip = "";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface networkInterface = en.nextElement();
String name = networkInterface.getName();
// 由于自己机器的网卡名称都是ens开头的,在这里获取
if (name.startsWith("ens")) {
for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress.getHostAddress();
if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
ip = ipaddress;
}
}
}
}
}
} catch (SocketException ex) {
log.error("获取ip地址异常", ex);
}
return ip;
}
}