Java 如何使用SpringShell在SpringBootWeb应用程序中构建控制台命令?

Java 如何使用SpringShell在SpringBootWeb应用程序中构建控制台命令?,java,spring,spring-boot,spring-web,spring-shell,Java,Spring,Spring Boot,Spring Web,Spring Shell,我使用SpringBootWebStarter创建了RESTfullWeb应用程序,效果很好。我可以通过URL访问它 但我需要创建控制台命令,它可以在后端计算和存储一些值。我希望能够手动或通过bash脚本运行console命令 我找不到任何关于如何在SpringBootWeb应用程序中集成SpringShell项目的文档 在SpringBootStarter中也没有选择SpringShell依赖项的选项 1) webapp和console是否需要是两个独立的应用程序,而我需要分别部署它们 2)

我使用SpringBootWebStarter创建了RESTfullWeb应用程序,效果很好。我可以通过URL访问它

但我需要创建控制台命令,它可以在后端计算和存储一些值。我希望能够手动或通过bash脚本运行console命令

我找不到任何关于如何在SpringBootWeb应用程序中集成SpringShell项目的文档

在SpringBootStarter中也没有选择SpringShell依赖项的选项

1) webapp和console是否需要是两个独立的应用程序,而我需要分别部署它们

2) 是否可以在同一个应用程序中部署web应用程序并运行控制台命令

3) 在shell和web应用程序之间共享公共代码(模型、服务、实体、业务逻辑)的最佳方法是什么


有人能在这方面提供帮助吗?

听起来这里有两个不同的用例:运行计划任务和手动运行命令。据我所知,SpringShell不是Boot生态系统的一部分。您可以编写一个SpringShell应用程序,它位于启动Web应用程序的外部,但不会嵌入其中。至少从我的经验来看

对于计划任务的第一种情况,您应该查看。您应该能够配置一个包含任务调度器的Spring应用程序(启动或正常)。然后,您可以配置可以调度的任务,让调度程序完成工作

对于手动执行命令,这里有几个选项。如果使用SpringShell,则假定它在自己的进程中运行,在SpringBoot进程之外。您需要使用远程方法调用技术(如RMI、REST等)将Shell应用程序调用到启动应用程序中(假定您希望在其中工作)

SpringShell的另一种选择是将远程Shell嵌入到启动应用程序中。本质上,您可以使用SSH连接到启动应用程序,并以与SpringShell类似的方式定义命令。其好处是,这与引导应用程序处于相同的过程中。因此,您可以插入任务调度器并手动运行与计划相同的任务。如果您想手动启动正在计划的相同任务,这可能是一个很好的选择。远程控制台的Doco是

希望这有帮助这里有两个选项:

(1)从命令行调用Rest API

您可以创建一个Spring
@RestController
,然后从命令行调用它

curl -X POST -i -H "Content-type: application/json" -c cookies.txt -X POST http://hostname:8080/service -d '
    {
        "field":"value",
        "field2":"value2"
    }
    '
您可以轻松地将其嵌入到一个漂亮的shell脚本中

(2)使用spring引导远程shell(已弃用)

虽然它主要用于监视/管理目的,但您可以使用

依赖关系

您需要以下依赖项才能启用远程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脚本(源代码:)获取Springbean,请执行以下操作:

启动您的SpringBootApp

通过类路径上的spring boot remote shell,spring boot应用程序将侦听端口5000(默认情况下)。 您现在可以执行以下操作:

$ telnet localhost 5000
Trying ::1...
Connected to localhost.
Escape character is '^]'.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v1.3.5.RELEASE)
帮助

您可以键入
help
查看可用命令的列表:

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 
调用我们的自定义命令

我们的自定义命令已列出(顶部第四个),您可以将其称为:

> custom
Hello
因此,基本上,您的crontab将执行
telnet 5000
并执行
custom

(3) 如何使用参数和选项(回答评论中的问题) 论据 要使用参数,您可以查看:

子命令(或选项) 仍然来自他们的:

最后一个命令执行:

  • 命令
    jdbc
  • 使用子命令
    connect
  • 参数
    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

谢谢@Edh,我不想有两个单独的应用程序(web和cli),因为所有业务逻辑都是通用的,我不想在两个应用程序中重复这一点。远程shell听起来很像我想要的。将研究它。如何将参数和选项传递给命令?文档中并没有提到这一点。我也这么做了,但出现了异常“无法创建命令实例”。我的命令中有构造函数。我在这里问了下面的问题,我在这个线程和另一个线程中都回答了。您的问题在于@Autowiring,没有将参数传递给您的命令。不幸的是,spring remote shell在spring boot 1.5中已被弃用
> custom
Hello
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
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