从Spring Shell执行Shell命令 [英] Execute shell commands from Spring Shell
问题描述
我有一个要问的问题,我可以用Spring Shell解决吗? 我有一个main.jar应用程序,该应用程序在Wildly服务器上部署了几个Scheduled Spring Jobs.就我而言,我无法停止或重新部署main.jar,因为必须不间断地提供服务.
I have a case which I want to ask can I solve with Spring Shell. I have a main.jar application which have several Scheduled Spring Jobs deployed on Wildly server. In my case I can't stop or redeploy the main.jar because the service must be provided non-stop.
我需要一种从终端启动/停止/重新启动计划的春季作业的方法.例如,在Apache Karaf中,有一个我可以通过telnet使用的外壳.
I need a way to start/stop/restart the Scheduled Spring Jobs from the terminal. For example in Apache Karaf there is a shell which I can use via telnet.
Spring Shell中是否有一些类似的解决方案,因此可以让我从linux终端执行命令.
Is there some similar solution in Spring Shell so that can let me execute commands from the linux terminal.
推荐答案
对于简单的计划任务,spring/spring-boot中没有开箱即用的CLI控件.
For simple scheduled tasks, there's no CLI control out of the box in spring/spring-boot.
您将需要自己实施.
下面是一个简单的示例,说明如何使用Spring Shell控制计划的任务以及如何在命令行中显示start/stop方法.
Below is a simple example of how you can control your scheduled tasks and expose the start/stop methods to the command line using spring shell.
让我们考虑一下所有计划任务的通用界面:
Let's consider you have a common interface for all scheduled tasks:
public interface WithCliControl {
void start();
void stop();
}
因此,一个简单的计划任务将如下所示:
So a simple scheduled task will look like:
@Component
public class MyScheduledTask implements WithCliControl {
private AtomicBoolean enabled = new AtomicBoolean(true);
@Scheduled(fixedRate = 5000L)
public void doJob() {
if (enabled.get()) {
System.out.println("job is enabled");
//do your thing
}
}
@Override
public void start() {
enabled.set(true);
}
@Override
public void stop() {
enabled.set(false);
}
}
以及相应的CLI组件如下所示:
and the corresponding CLI component will look like:
@ShellComponent
public class MyScheduledTaskCommands {
private final MyScheduledTask myScheduledTask;
public MyScheduledTaskCommands(final MyScheduledTask myScheduledTask) {
this.myScheduledTask = myScheduledTask;
}
@ShellMethod("start task")
public void start() {
myScheduledTask.start();
}
@ShellMethod("stop task")
public void stop() {
myScheduledTask.stop();
}
}
@ShellComponent
和@ShellMethod
将这些方法公开给Spring Shell进程.
@ShellComponent
and @ShellMethod
are exposing the methods to the Spring Shell process.
这篇关于从Spring Shell执行Shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!