Execute shell commands from Spring Shell

混江龙づ霸主 提交于 2020-01-04 09:49:32

问题


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:


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.



来源:https://stackoverflow.com/questions/55626845/execute-shell-commands-from-spring-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!