Вот 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"
}
'
Вы можете легко встроить это в хороший сценарий оболочки.
(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"
}
}
Чтобы получить bean-компонент Spring из этого отличного скрипта (источник: 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
Итак, по сути, ваш 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
Полный пример
Следующее содержит:
- конструктор;
- команда с аргументами;
- фасоль управляемая весной;
- подкоманда с аргументами.
Код:
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
person
alexbt
schedule
05.09.2016