springboot remote shell简单实例

springboot项目可以使用远程shell进行监控和管理(在2.0版本就不可以使用了,此处要注意)

使用时先添加spring boot remote shell 的依赖,gradle项目自己去搜一下就好了

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-remote-shell</artifactId>
 </dependency>

使用时通过
ssh -p 2000 user@localhost登录,其默认端口号是2000,可以在springboot项目资源文件application.properties里修改。登陆后输入help可以获取一系列命令的帮助

#设置用户名
management.shell.auth.simple.user.name=xxx  
#设置密码
management.shell.auth.simple.user.password=xxx

其余配置用的时候查一下就可以了

自定义命令需要写一个groovy文件,示例如下,groovy文件要放在项目根目录的commands文件夹下(可以在项目的resource目录下建一个commands文件夹用以存放自定义命令),文件名为xxxx.groovy,

    package commands
  
    import com.test.CommandJob
    import org.crsh.cli.Command
    import org.crsh.cli.Usage
    import org.crsh.command.InvocationContext
    
    @Usage("customer command")
    class ModifyStockCustomer {
    
        @Usage("customer commandr")
        @Command
        def apply(InvocationContext context){
    
    //获取任务执行的实际类
        def commandJob =   context.attributes['spring.beanfactory'].getBean(CommandJob.class)  
    
    //读取外部输入确认执行函数
         def confirm = context.readLine("确认执行任任务? y/n: ", true)
         if (!"y".equalsIgnoreCase(confirm)) {
             return "放弃本次修改?想好了再来吧!"
         }
 
          try {
          //执行任任务,并处理返回结果
              def result = commandJob .execute()
              if(2 == result){
                  return "任务执行,请重新执行一次"
              }else if(1 == result){
                  return "执行完毕,( ^_^ )/~~拜拜"
              }else{
                  return "出现未知结果,请重新执行"
              }
          } catch (Exception e) {
              return "任务执行失败,出现异常"+e.getStackTrace()
          }
      }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值