栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用Spring Shell在Spring Boot Web应用程序中构建控制台命令?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用Spring Shell在Spring Boot Web应用程序中构建控制台命令?

这是2个选项:

(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-boot-remote-shell(已弃用)

尽管它主要用于监视/管理目的,但是您可以使用spring-boot-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 commandsimport org.crsh.cli.Commandimport org.crsh.cli.Usageimport org.crsh.command.InvocationContextclass custom {    @Usage("Custom command")    @Command    def main(InvocationContext context) {        return "Hello"    }}

要从该groovy脚本中获取Springbean:

BeanFactory beanFactory = (BeanFactory) context.getAttributes().get("spring.beanfactory");MyController myController = beanFactory.getBean(MyController.class);

启动您的SpringBootApp

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

$ telnet localhost 5000Trying ::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 commandsthread     JVM thread commands

调用我们的自定义命令

我们的自定义命令已列出(自上而下的第四个),您可以调用它:

> customHello

因此,从本质上讲,您的crontab将

telnet 5000
执行
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

一个完整的例子

以下内容包括:

  • 构造函数;
  • 带参数的命令;
  • spring管理的豆;
  • 带有参数的子命令。

编码:

package commandsimport org.crsh.cli.Commandimport org.crsh.cli.Usageimport org.crsh.command.InvocationContextimport org.springframework.beans.factory.BeanFactoryimport com.alexbt.goodies.MyBeanclass 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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484045.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号