복붙노트

[SPRING] 스프링 쉘을 사용하여 스프링 부트 웹 애플리케이션에서 콘솔 명령을 작성하는 방법은 무엇입니까?

SPRING

스프링 쉘을 사용하여 스프링 부트 웹 애플리케이션에서 콘솔 명령을 작성하는 방법은 무엇입니까?

나는 잘 작동하는 스프링 부트 웹 스타터를 사용하여 편안한 웹 어플리케이션을 만들었습니다. URL을 통해 액세스 할 수 있습니다.

하지만 백엔드에서 일부 값을 계산하고 저장할 수있는 콘솔 명령을 작성해야한다는 요구 사항이 있습니다. 콘솔 명령을 수동으로 또는 bash 스크립트를 통해 실행할 수 있어야합니다.

스프링 부트 웹 애플리케이션에서 스프링 쉘 프로젝트를 통합하는 방법에 대한 문서를 찾을 수 없었습니다.

또한 스프링 부트 스타터 https://start.spring.io/에서 스프링 쉘 종속성을 선택할 수있는 옵션이 없습니다.

1) webapp와 console은 별도의 두 응용 프로그램이되어야하며 별도로 배포해야합니까?

2) 동일한 앱에서 웹 앱을 배포하고 콘솔 명령을 실행할 수 있습니까?

3) 셸과 웹 응용 프로그램간에 공통 코드 (모델, 서비스, 엔터티, 비즈니스 논리)를 공유하는 가장 좋은 방법은 무엇입니까?

아무도 이것에 도움을받을 수 있습니까?

해결법

  1. ==============================

    1.2 가지 옵션이 있습니다.

    2 가지 옵션이 있습니다.

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

    이것을 멋진 쉘 스크립트에 쉽게 내장 할 수 있습니다.

    주로 모니터링 / 관리 목적으로 사용되지만 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>
    

    그루비 스크립트 :

    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 소스 코드 : https://stackoverflow.com/a/24300534/641627)에서 Spring 빈을 얻으려면 :

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

    Spring Boot App 실행

    classpath에 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 
    

    커스텀 커맨드 호출

    사용자 정의 명령이 나열됩니다 (위에서 네 번째). 다음과 같이 호출 할 수 있습니다.

    > custom
    Hello
    

    따라서 본질적으로 crontab은 telnet 5000을 수행하고 사용자 정의를 실행합니다.

    인수를 사용하려면 설명서를 살펴보십시오.

    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
    
  2. ==============================

    2.여기에는 두 가지 별개의 유스 케이스가 있습니다 : 예약 된 작업 실행 및 수동으로 명령 실행. 내 이해에서 스프링 쉘은 부트 생태계의 일부가 아닙니다. Boot Web app의 외부에있는 Spring Shell 애플리케이션을 작성할 수는 있지만, 그 안에 내장하지 않을 것입니다. 적어도 내 경험에서.

    여기에는 두 가지 별개의 유스 케이스가 있습니다 : 예약 된 작업 실행 및 수동으로 명령 실행. 내 이해에서 스프링 쉘은 부트 생태계의 일부가 아닙니다. Boot Web app의 외부에있는 Spring Shell 애플리케이션을 작성할 수는 있지만, 그 안에 내장하지 않을 것입니다. 적어도 내 경험에서.

    예약 된 작업의 첫 번째 경우에는 Spring의 Scheduler를 살펴 봐야합니다. 그 안에 작업 스케줄러가있는 Spring 애플리케이션 (부팅 또는 일반)을 구성 할 수 있어야합니다. 그런 다음 스케줄러가 작업을 수행하도록 스케줄링 할 수있는 태스크를 구성 할 수 있습니다.

    명령을 수동으로 실행하려면 몇 가지 옵션이 필요합니다. Spring Shell을 사용한다면 Spring Boot 프로세스 외부의 자체 프로세스에서 실행되고 있다고 가정합니다. 원격 응용 프로그램 호출 기술 (예 : RMI, REST 등)을 사용하여 셸 응용 프로그램 호출을 부팅 응용 프로그램으로 가져와야합니다.

    Spring Shell의 대안은 원격 쉘을 Boot 애플리케이션에 내장하는 것입니다. 기본적으로 SSH를 사용하여 Boot 응용 프로그램에 연결하고 Spring Shell과 유사한 방식으로 명령을 정의 할 수 있습니다. 이점은 Boot 응용 프로그램과 동일한 프로세스에 있다는 것입니다. 따라서 작업 스케줄러를 주입하고 예약 된 것과 동일한 작업을 수동으로 실행할 수 있습니다. 동일한 작업이 수동으로 실행되도록 예약하려는 경우이 옵션이 좋습니다. 원격 콘솔 용 Doco가 있습니다.

    희망이 도움이

  3. from https://stackoverflow.com/questions/39329017/how-to-build-console-command-in-spring-boot-web-application-using-spring-shell by cc-by-sa and MIT license