web-dev-qa-db-ja.com

Spring Shellを使用してSpring Boot Webアプリケーションでコンソールコマンドを構築するにはどうすればよいですか?

Spring Boot Web Starterを使用してうまく機能するRestfull Webアプリケーションを作成しました。 URLからアクセスできます。

しかし、バックエンドでいくつかの値を計算して保存できるコンソールコマンドを作成する必要があります。コンソールコマンドを手動またはbashスクリプトで実行できるようにしたい。

Spring-ShellプロジェクトをSpring Boot Webアプリケーションに統合する方法に関するドキュメントは見つかりませんでした。

また、Spring Boot Starter https://start.spring.io/ でspring-Shell依存関係を選択するオプションはありません

1)webappとconsoleは2つの別々のアプリケーションである必要がありますか?それらを別々にデプロイする必要がありますか?

2)同じアプリでWebアプリをデプロイしてコンソールコマンドを実行することはできますか?

3)シェルとWebアプリケーション間で共通のコード(モデル、サービス、エンティティ、ビジネスロジック)を共有するための最良のアプローチは何ですか?

誰かこれを手伝ってくれませんか?

13
vishal

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"
    }
    '

これは、Nice 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 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 ):

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

SpringBootAppを起動します

クラスパスにspring-boot-remote-Shellを使用すると、Spring Boot Applicationはポート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 

カスタムコマンドを呼び出します

カスタムコマンドが一覧表示され(上から4番目)、それを呼び出すことができます。

> custom
Hello

したがって、基本的には、crontabはtelnet 5000を実行してcustomを実行します

(3)引数とオプションの使用方法(コメントで質問に答えるため)

議論

引数を使用するには、 documentation を見てください。

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

完全な例

以下が含まれます:

  • コンストラクタ;
  • 引数付きのコマンド。
  • 春の管理された豆;
  • 引数付きのサブコマンド。

コード:

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
8
alexbt

ここでは、スケジュールされたタスクの実行とコマンドの手動実行という2つの異なる使用例があるようです。私の理解では、Spring ShellはBootエコシステムの一部ではありません。 Boot Webアプリの外部にあるSpring Shellアプリケーションを作成することはできますが、その中に埋め込まれることはありません。少なくとも私の経験から。

スケジュールされたタスクの最初のケースでは、 Spring's Scheduler を確認する必要があります。タスクスケジューラが組み込まれたSpringアプリケーション(ブートまたは通常)を構成できるはずです。次に、スケジュールできるタスクを構成して、スケジューラーに作業を任せることができます。

コマンドを手動で実行するには、ここにいくつかのオプションがあります。 Spring Shellを使用する場合は、Spring Bootプロセスの外部にある独自のプロセスで実行されていると想定します。リモートメソッドの呼び出しテクノロジ(RMI、RESTなど)を使用して、シェルアプリをブートアプリケーションに呼び出す必要があります(それを実行する場所を想定しています)。

Spring Shellの代わりに、リモートShellをBootアプリケーションに埋め込むことができます。基本的に、SSHを使用してBootアプリケーションに接続し、Spring Shellと同様の方法でコマンドを定義できます。利点は、これがブートアプリケーションと同じプロセスにあることです。そのため、タスクスケジューラを挿入して、スケジュールされているのと同じタスクを手動で実行できます。これは、スケジュールされている同じタスクを手動でキックする場合に適したオプションです。リモートコンソールのDocoは here です。

お役に立てれば

2
EdH