programing

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

instargram 2023. 8. 10. 18:12
반응형

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

저는 스프링부츠 웹 스타터를 사용하여 작동이 잘 되는 레스트풀 웹 애플리케이션을 만들었습니다.나는 URL을 통해 그것에 접속할 수 있습니다.

그러나 백엔드에서 일부 값을 계산하고 저장할 수 있는 콘솔 명령을 만들어야 합니다.콘솔 명령을 수동으로 실행하거나 bash 스크립트를 통해 실행할 수 있기를 원합니다.

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

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

웹 앱과 콘솔이 두 개의 별도 애플리케이션이어야 하며 별도로 배포해야 합니까?

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

셸과 웹 애플리케이션 간에 공통 코드(모델, 서비스, 엔티티, 비즈니스 로직)를 공유하는 가장 좋은 방법은 무엇입니까?

누가 이것에 대해 도와줄 수 있습니까?

다음 두 가지 옵션이 있습니다.

명령줄에서 호출된 Rest API

프을만수있다니습들스링을 만들 수 .@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 사용(사용되지 않음)

주로 모니터링/관리 목적이지만 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"
    }
}

이 그루비 스크립트에서 Springbean을 얻으려면 (출처: 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에서 수신합니다(기본값).이제 다음 작업을 수행할 수 있습니다.

$ 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

으로, 의 크론탭은 서그로, 으적크, 의탭은론을 할 입니다.telnet 5000 행실을 실행합니다.custom

인수 및 옵션 사용 방법(댓글로 질문에 답하기 위해)

논쟁들

인수를 사용하려면 설명서를 참조하십시오.

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

여기에는 예약된 작업 실행과 수동으로 명령 실행이라는 두 가지 사용 사례가 있습니다.제가 알기로는 Spring Shell은 Boot 생태계의 일부가 아닙니다.부팅 웹 앱 외부에 있는 Spring Shell 응용 프로그램을 작성할 수 있지만, 이 응용 프로그램에는 포함되지 않습니다.적어도 내 경험으로는.

예약된 작업의 첫 번째 경우에는 Spring's Scheduler를 살펴봐야 합니다.작업 스케줄러가 포함된 Spring 응용 프로그램(부팅 또는 일반)을 구성할 수 있어야 합니다.그런 다음 스케줄링된 작업을 구성하여 스케줄러가 작업을 수행하도록 할 수 있습니다.

명령을 수동으로 실행하려면 여기에 몇 가지 옵션이 있습니다.Spring Shell을 사용하는 경우 Spring Boot 프로세스 외부에서 자체 프로세스로 실행되고 있다고 가정합니다.원격 메서드 호출 기술(예: RMI, REST 등)을 사용하여 Shell 앱을 부팅 애플리케이션으로 호출해야 합니다.

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

이것이 도움이 되길 바랍니다.

언급URL : https://stackoverflow.com/questions/39329017/how-to-build-console-command-in-spring-boot-web-application-using-spring-shell

반응형