关于官方文档上对于使用的基本配置已经有所描述,案例中使用 Groovy 创建自定义命令交互;
在这里将主要使用 Java 再实现一次,并结合 maven 使用,可供参考。
本篇前提默认大家对 spring boot 有了基本了解,如何引入基础依赖,启动服务等就不详细介绍。
基础配置
pom 文件中添加以下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-remote-shell</artifactId>
</dependency>
以下配置用于不编译 commands 目录下 java 文件,并将 java 文件 copy 至 classpath*:/commands 目录下
<build>
<resources>
<resource>
<directory>src/main/java/commands</directory>
<targetPath>commands</targetPath>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<excludes>
<exclude>/commands/*</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
application.properties 添加以下配置内容:
shell.auth.simple.user.name=test
shell.auth.simple.user.password=test
自定义命令
创建 TestCommand.java
package commands;
import org.crsh.cli.Command;
import org.crsh.cli.Usage;
import org.crsh.command.BaseCommand;
@Usage("Test Command")
public class TestCommand extends BaseCommand{
@Command
@Usage("Useage main Command")
public String main (){
return "main command";
}
}
启动 springboot 服务:
mvn spring-boot:run
看一下 log
现在可以尝试登录上去:
ssh -p 2000 test@localhost
执行 help:
执行命令 TestCommand
可以看到 main command 返回,证明调用成功
单纯这种调用相信大家都觉得并没有什么太大意思,往往希望通过这种后门能够帮助应用做一些补救措施;
例如直接操作 spring context ,获取到具体的 bean ,并处理执行相关业务逻辑;
往下看,在这里会使用到 InvocationContext 接口来获取上下文,修改一下 TestCommand 文件,如下:
package commands;
import org.crsh.cli.Command;
import org.crsh.cli.Usage;
import org.crsh.command.BaseCommand;
import org.crsh.command.InvocationContext;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
@Usage("Test Command")
public class TestCommand extends BaseCommand {
@Command
@Usage("Useage main Command")
public String main(InvocationContext context) {
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) context.getAttributes().get("spring.beanfactory");
for (String name : defaultListableBeanFactory.getBeanDefinitionNames()) {
System.out.println(name);
context.getWriter().write(name);
context.getWriter().write("\n");
}
return "main command";
}
}
再次启动服务,执行 TestCommand 命令,会有如下返回:
就这样可以方便使用自定义的命令,调用 spring context 中方法;
当然看到这里,再往前思考一步,肯定还有问题引出,shell 可以调用 spring context 中相关 bean 的方法了,那方法参数传递怎么搞定?
后面的续篇中,再和大家分享,把搬运工作进行到底!
spring boot remote shell 是集成 CRsSH
如果迫不及待的朋友可以先阅读 CRaSH Reference Guide
希望能给大家一定帮助