Execute shell commands from Spring Shell

2019-07-25 18:13发布

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.

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.

Is there some similar solution in Spring Shell so that can let me execute commands from the linux terminal.

1条回答
时光不老,我们不散
2楼-- · 2019-07-25 18:27

For simple scheduled tasks, there's no CLI control out of the box in spring/spring-boot.

You will need to implement it yourself.

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);
    }
}

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 and @ShellMethod are exposing the methods to the Spring Shell process.

查看更多
登录 后发表回答