如何使用Spring Shell在Spring Boot Web应用程序中构建控制台命令? [英] how to build console command in spring boot web application using spring shell?
问题描述
我已经使用Spring Boot Web Starter创建了restfull Web应用程序,效果很好.我可以通过网址访问它.
I have created restfull web application using spring boot web starter which works well. I am able to access it through urls.
但是我需要创建控制台命令,该命令可以在后端计算和存储一些值.我希望能够手动或通过bash脚本运行控制台命令.
But I have requirement to create console command which can compute and store some values at the backend. I want to be able to run console command manually or through bash script.
我找不到任何有关如何在Spring Boot Web应用程序中集成spring-shell项目的文档.
I could not find any documentation on how to integrate spring-shell project in spring boot web application.
在spring boot starter中也没有选择spring-shell依赖的选项 https://start.spring.io/
Also there is no option to choose spring-shell dependency in spring boot starter https://start.spring.io/
1)webapp和控制台是否需要是两个单独的应用程序,我需要分别部署它们吗?
1) Do webapp and console need to be two separate applications and I need to deploy them separately ?
2)是否可以在同一应用程序中部署Web应用程序并运行控制台命令?
2) Is it possible to deploy web app and run console commands in the same app ?
3)在Shell和Web应用程序之间共享通用代码(模型,服务,实体,业务逻辑)的最佳方法是什么?
3) What is the best approach to share common code (model, services, entities, business logic) between shell and web applications ?
任何人都可以帮忙吗?
推荐答案
这里有2个选项:
(1)从命令行调用Rest API
您可以创建一个Spring @RestController
,然后从命令行中调用它吗?
You could create a Spring @RestController
, which you then call from the command line ?
curl -X POST -i -H "Content-type: application/json" -c cookies.txt -X POST http://hostname:8080/service -d '
{
"field":"value",
"field2":"value2"
}
'
您可以轻松地将其嵌入到一个不错的shell脚本中.
You can easily embed this in a nice shell script.
(2)使用spring-boot-remote-shell(已弃用)
Though it is mainly for monitoring/administration purposes, you may use the spring-boot-remote-shell for that.
依赖项
您需要以下依赖项才能启用远程外壳:
You need the following dependencies to enable the remote-shell:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-remote-shell</artifactId>
</dependency>
<dependency>
<groupId>org.crsh</groupId>
<artifactId>crsh.shell.telnet</artifactId>
<version>1.3.0-beta2</version>
</dependency>
Groovy脚本:
在src/main/resources/custom.groovy
中添加以下脚本:
package commands
import org.crsh.cli.Command
import org.crsh.cli.Usage
import org.crsh.command.InvocationContext
class custom {
@Usage("Custom command")
@Command
def main(InvocationContext context) {
return "Hello"
}
}
要从该groovy脚本中获取Spring bean(来源: https://stackoverflow.com/a/24300534/641627 ):
To get a hold of a Spring bean from this groovy script (source: https://stackoverflow.com/a/24300534/641627):
BeanFactory beanFactory = (BeanFactory) context.getAttributes().get("spring.beanfactory");
MyController myController = beanFactory.getBean(MyController.class);
启动您的SpringBootApp
在类路径上使用spring-boot-remote-shell时,Spring Boot应用程序在端口5000上侦听(默认情况下). 您现在可以执行以下操作:
With spring-boot-remote-shell on the classpath, the Spring Boot Application listens on port 5000 (by default). You can now do this:
$ telnet localhost 5000
Trying ::1...
Connected to localhost.
Escape character is '^]'.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.3.5.RELEASE)
帮助
您可以键入help
以查看可用命令的列表:
You can type help
to see the list of available commands:
NAME DESCRIPTION
autoconfig Display auto configuration report from ApplicationContext
beans Display beans in ApplicationContext
cron manages the cron plugin
custom Custom command
dashboard
egrep search file(s) for lines that match a pattern
endpoint Invoke actuator endpoints
env display the term env
filter A filter for a stream of map
help provides basic help
java various java language commands
jmx Java Management Extensions
jul java.util.logging commands
jvm JVM informations
less opposite of more
log logging commands
mail interact with emails
man format and display the on-line manual pages
metrics Display metrics provided by Spring Boot
shell shell related command
sleep sleep for some time
sort Sort a map
system vm system properties commands
thread JVM thread commands
调用我们的自定义命令
列出了我们的自定义命令(自上而下的第四个),您可以调用它:
Our custom command is listed (the fourth from the top), you can call it:
> custom
Hello
因此,从本质上讲,您的crontab将执行telnet 5000
并执行custom
So, essentially, your crontab would do a telnet 5000
and execute custom
(3)如何使用参数和选项(在评论中回答问题)
参数
要使用参数,可以查看文档:
class date {
@Usage("show the current time")
@Command
Object main(
@Usage("the time format")
@Option(names=["f","format"])
String format) {
if (format == null)
format = "EEE MMM d HH:mm:ss z yyyy";
def date = new Date();
return date.format(format);
}
}
% date -h
% usage: date [-h | --help] [-f | --format]
% [-h | --help] command usage
% [-f | --format] the time format
% date -f yyyyMMdd
子命令(或选项)
摘自其文档:
@Usage("JDBC connection")
class jdbc {
@Usage("connect to database with a JDBC connection string")
@Command
public String connect(
@Usage("The username")
@Option(names=["u","username"])
String user,
@Usage("The password")
@Option(names=["p","password"])
String password,
@Usage("The extra properties")
@Option(names=["properties"])
Properties properties,
@Usage("The connection string")
@Argument
String connectionString) {
...
}
@Usage("close the current connection")
@Command
public String close() {
...
}
}
% jdbc connect jdbc:derby:memory:EmbeddedDB;create=true
最后一条命令执行:
- 命令
jdbc
- 使用子命令
connect
- 和参数
jdbc:derby:memory:EmbeddedDB;create=true
- the command
jdbc
- with subcommand
connect
- and the argument
jdbc:derby:memory:EmbeddedDB;create=true
以下内容包括:
- 构造函数;
- 带有参数的命令;
- 春天管理的豆子;
- 带有参数的子命令.
代码:
package commands
import org.crsh.cli.Command
import org.crsh.cli.Usage
import org.crsh.command.InvocationContext
import org.springframework.beans.factory.BeanFactory
import com.alexbt.goodies.MyBean
class SayMessage {
String message;
SayMessage(){
this.message = "Hello";
}
@Usage("Default command")
@Command
def main(InvocationContext context, @Usage("A Parameter") @Option(names=["p","param"]) String param) {
BeanFactory beanFactory = (BeanFactory) context.getAttributes().get("spring.beanfactory");
MyBean bean = beanFactory.getBean(MyBean.class);
return message + " " + bean.getValue() + " " + param;
}
@Usage("Hi subcommand")
@Command
def hi(InvocationContext context, @Usage("A Parameter") @Option(names=["p","param"]) String param) {
BeanFactory beanFactory = (BeanFactory) context.getAttributes().get("spring.beanfactory");
MyBean bean = beanFactory.getBean(MyBean.class);
return "Hi " + bean.getValue() + " " + param;
}
}
> saymsg -p Johnny
> Hello my friend Johnny
> saymsg hi -p Johnny
> Hi my friend Johnny
这篇关于如何使用Spring Shell在Spring Boot Web应用程序中构建控制台命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!