最近接到需求,分布式部署下要求在指定服务器机器通过命令行的方式执行Java程序。
经过几天的查询资料,分析讨论。最终确定方案:集成Spring shell将要执行的类和方法命令化。
关于Spring shell的介绍详见:
https://www.cnblogs.com/nuccch/p/11067342.html
主要使用其注解@ShellComponent,@ShellMethod
@ShellComponent
public class HelloWorld {
@ShellMethod("Say hello")
public void hello(String name) {
System.out.println("hello, " + name + "!");
}
}
集成后,启动项目控制台停留在命令交互界面,等待用户输入;
输入命令,即可实现方法的调用:
shell:>help
AVAILABLE COMMANDS
Built-In Commands
clear: Clear the shell screen.
exit, quit: Exit the shell.
help: Display help about available commands.
script: Read and execute commands from a file.
stacktrace: Display the full stacktrace of the last error.
Calculator
addition, sum: Add numbers.
shell:>addition 1 2
1 + 2 = 3
shell:>sum 1 2
1 + 2 = 3
shell:>sum --a 1 --b 2 # 使用带命令参数前缀的方式
1 + 2 = 3
shell:>
附:服务器打开tomcat控制台
先cd到tomcat的安装目录的bin目录下,然后这样启动tomcat:
$ ./catalina.sh run
就可以了。
debug模式:
$ ./catalina.sh debug
......
help (查看帮助)
exit(退出、终止tomcat)catalina.sh [para]
para:
debug start Catalina in a debugger
debug -security debug catalina with a security manager.
run start Catalina in the current window.
run -security start Catalina in the current window with security manager.
start start Catalina in the separate window
start -security start Catalina in the separate window with security manager.
stop stop catalina.
stop -force stop catalina (followed by kill -KILL).
version version of tomcat
遇到一个问题:
spring boot项目集成spring shell之后,本地项目正常启动。但是上了服务器之后,项目启动失败,严重警告:项目启动的xxx线程,但没有正常关闭,可能会导致内存泄露。然后死循环打印堆栈。暂未找到解决办法,研究中。mark一下。