Переглянути джерело

hos-admin shell 执行结果回调

demon 8 роки тому
батько
коміт
c1c60aa63a

+ 0 - 5
hos-arbiter/pom.xml

@ -40,11 +40,6 @@
            <artifactId>hos-web-framework</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.53</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.zbus/zbus -->
        <dependency>
            <groupId>org.zbus</groupId>

+ 9 - 4
hos-arbiter/src/main/java/com/yihu/hos/arbiter/HosArbiterApplication.java

@ -2,7 +2,7 @@ package com.yihu.hos.arbiter;
import com.yihu.hos.arbiter.configuration.ArbiterServerConfiguration;
import com.yihu.hos.arbiter.services.ProxyService;
import com.yihu.hos.web.framework.constant.ServiceFlowConstant;
import com.yihu.hos.arbiter.services.ShellService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
@ -17,6 +17,7 @@ import org.zbus.mq.server.MqServerConfig;
public class HosArbiterApplication implements CommandLineRunner {
    private ArbiterServerConfiguration configuration;
    private ProxyService proxyService;
    private ShellService shellService;
    public static void main(String[] args) {
        SpringApplication.run(HosArbiterApplication.class, args);
@ -32,9 +33,8 @@ public class HosArbiterApplication implements CommandLineRunner {
            server.start();
        }
        proxyService.start(ServiceFlowConstant.SSH + "@" + configuration.getTenant());
        proxyService.start(ServiceFlowConstant.SHELL + "@" + configuration.getTenant());
        proxyService.start();
        shellService.start();
    }
    @Autowired
@ -46,4 +46,9 @@ public class HosArbiterApplication implements CommandLineRunner {
    public void setProxyService(ProxyService proxyService) {
        this.proxyService = proxyService;
    }
    @Autowired
    public void setShellService(ShellService shellService) {
        this.shellService = shellService;
    }
}

+ 1 - 1
hos-arbiter/src/main/java/com/yihu/hos/arbiter/routers/LinuxShellRouter.java

@ -33,7 +33,7 @@ public class LinuxShellRouter extends RouteBuilder {
                .choice()
                .when(header("tenant").isNotNull()).to("bean:linuxShellService?method=proxy")
                .when(header("event").isEqualTo(ServiceFlowConstant.ARBITER_SHELL_SEND)).to("bean:linuxShellService?method=sendShell")
                .when(header("event").isEqualTo(ServiceFlowConstant.ARBITER_SHELL_ACEPT)).to("bean:linuxShellService?method=aceptShell")
                .when(header("event").isEqualTo(ServiceFlowConstant.ARBITER_SHELL_ACEPT)).to("bean:linuxShellService?method=shellBack")
                .endChoice();
    }
}

+ 93 - 2
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/LinuxShellService.java

@ -1,6 +1,11 @@
package com.yihu.hos.arbiter.services;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.arbiter.models.BrokerServer;
import com.yihu.hos.core.http.HTTPResponse;
import com.yihu.hos.core.http.HttpClientKit;
import com.yihu.hos.web.framework.constant.ServiceFlowConstant;
import com.yihu.hos.web.framework.model.bo.ServiceShell;
import org.apache.camel.Body;
import org.apache.camel.Headers;
import org.apache.log4j.LogManager;
@ -12,6 +17,7 @@ import org.zbus.mq.Producer;
import org.zbus.net.http.Message;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
@ -23,8 +29,11 @@ import java.util.Map;
public class LinuxShellService {
    private static final Logger logger = LogManager.getLogger(LinuxShellService.class);
    @Autowired
    private BrokerServerService brokerServerService;
    private ZbusBroker zbusBroker;
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * SAAS化的管理端过来的消息会被proxy进行中转,之后发送到终端的Arbiter对Broker进行实际的控制。
@ -40,7 +49,7 @@ public class LinuxShellService {
        try {
            //TODO 设置shell发起用户
            Producer producer = new Producer(zbusBroker, ServiceFlowConstant.SHELL + "@" + header.get("tenant"));
            Producer producer = new Producer(zbusBroker, ServiceFlowConstant.SHELL_ARBITER + "@" + header.get("tenant"));
            producer.createMQ();    //确定为创建消息队列需要显示调用
            Message message = new Message();
            message.setHead("event", header.get("event"));
@ -57,6 +66,88 @@ public class LinuxShellService {
    }
    /**
     * 发送shell命令请求到broker
     * @param msg    命令消息内容
     */
    public void sendShell(String msg) {
        try {
            List<BrokerServer> brokerServerList  = brokerServerService.get(false);
            for (BrokerServer broker : brokerServerList) {
                String result = sendMessage(broker, "post", "/esb/serviceShell/send", msg);
                if (result==null) {
                    logger.error("sendMessage to broker server failed, broker:" + broker.getURL() + ", msg:" + msg);
                    continue;
                }else {
                    System.out.println("发送shell请求到broker成功!!!");
                    //TODO shell执行成功,见执行结果返回到中心显示。
                    ServiceShell serviceShell = objectMapper.readValue(msg,ServiceShell.class);
                    Producer producer = new Producer(zbusBroker, ServiceFlowConstant.SHELL_ADMIN + "@" + serviceShell.getTenant());
                    producer.createMQ();    //确定为创建消息队列需要显示调用
                    Message message = new Message();
                    message.setHead("event", serviceShell.getType());
                    message.setHead("tenant", serviceShell.getTenant());
                    message.setMethod("POST");
                    message.setBody(result);
                    message = producer.sendSync(message);
                    System.out.println("发送到中心zubs的shell结果!"+message);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }
    private String sendMessage(BrokerServer brokerServer, String method, String path, String msg) {
        if (brokerServer == null) {
            return null;
        }
        switch (method) {
            case "post": {
                HTTPResponse response = HttpClientKit.post(brokerServer.getURL() + path, msg);
                if (response.getStatusCode() == 200) {
                    String body = response.getBody();
                    System.out.println(body);
                    return body;
                }
                return null;
            }
            case "put": {
                HTTPResponse response = HttpClientKit.put(brokerServer.getURL() + path, msg);
                if (response.getStatusCode() == 200) {
                    String body = response.getBody();
                    logger.debug(body);
                    return body;
                }
                return null;
            }
            case "delete": {
                HTTPResponse response = HttpClientKit.delete(brokerServer.getURL() + path, msg);
                if (response.getStatusCode() == 200) {
                    String body = response.getBody();
                    logger.debug(body);
                    return body;
                }
                return null;
            }
            default:
                break;
        }
        return null;
    }
    @Autowired
    public void setZbusBroker(ZbusBroker zbusBroker) {
        this.zbusBroker = zbusBroker;

+ 8 - 2
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ProxyService.java

@ -1,5 +1,6 @@
package com.yihu.hos.arbiter.services;
import com.yihu.hos.arbiter.configuration.ArbiterServerConfiguration;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.constant.ServiceFlowConstant;
@ -24,6 +25,7 @@ public class ProxyService {
    private static final Logger logger = LoggerFactory.getLogger(ProxyService.class);
    private CamelContext camelContext;
    private ArbiterServerConfiguration configuration;
    private ZbusBroker zbusBroker;
    private Consumer consumer;
@ -36,13 +38,13 @@ public class ProxyService {
        producerTemplate.sendBodyAndHeaders(ServiceFlowConstant.FLOW_EVENT_ENDPOINT, message.getBodyString(), header);
    }
    public void start(String queueName) {
    public void start() {
        if (zbusBroker == null) {
            logger.error("zbusBroker is null");
            return;
        }
        consumer = new Consumer(zbusBroker,queueName);
        consumer = new Consumer(zbusBroker, ServiceFlowConstant.SSH + "@" + configuration.getTenant());
        try {
            consumer.start(this::proxy);
        } catch (IOException e) {
@ -62,6 +64,10 @@ public class ProxyService {
        this.camelContext = camelContext;
    }
    @Autowired
    public void setConfiguration(ArbiterServerConfiguration configuration) {
        this.configuration = configuration;
    }
    @Override
    protected void finalize() throws Throwable {

+ 78 - 0
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ShellService.java

@ -0,0 +1,78 @@
package com.yihu.hos.arbiter.services;
import com.yihu.hos.arbiter.configuration.ArbiterServerConfiguration;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.constant.ServiceFlowConstant;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zbus.broker.ZbusBroker;
import org.zbus.mq.Consumer;
import org.zbus.net.http.Message;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/1/6.
 */
@Service
public class ShellService {
    private static final Logger logger = LoggerFactory.getLogger(ShellService.class);
    private CamelContext camelContext;
    private ArbiterServerConfiguration configuration;
    private ZbusBroker zbusBroker;
    private Consumer consumer;
    public void proxy(Message message, Consumer consumer) {
        Map<String, Object> header = new HashMap<>();
        header.put("event", message.getHead("event"));
        ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
        producerTemplate.sendBodyAndHeaders(ServiceFlowConstant.SHELL_EVENT_ENDPOINT, message.getBodyString(), header);
    }
    public void start() {
        if (zbusBroker == null) {
            logger.error("zbusBroker is null");
            return;
        }
        consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_ARBITER + "@" + configuration.getTenant());
        try {
            consumer.start(this::proxy);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }
    @Autowired
    public void setZbusBroker(ZbusBroker zbusBroker) {
        this.zbusBroker = zbusBroker;
    }
    @Autowired
    public void setCamelContext(CamelContext camelContext) {
        this.camelContext = camelContext;
    }
    @Autowired
    public void setConfiguration(ArbiterServerConfiguration configuration) {
        this.configuration = configuration;
    }
    @Override
    protected void finalize() throws Throwable {
        consumer.close();
        super.finalize();
    }
}

+ 0 - 6
hos-arbiter/src/main/resources/application.yml

@ -29,12 +29,6 @@ arbiter:
    url: 192.168.131.119:15555
  tenant:
    name: jkzl
#jcraft shell操作
jcraft:
  host: 172.19.103.57
  port: 22
  user: root
  password: ceshi
---
spring:
  profiles: test

+ 6 - 0
hos-broker/pom.xml

@ -95,6 +95,12 @@
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.53</version>
        </dependency>
    </dependencies>

+ 27 - 26
hos-arbiter/src/main/java/com/yihu/hos/arbiter/shell/SSHLinuxTool.java

@ -1,11 +1,12 @@
package com.yihu.hos.arbiter.shell;
package com.yihu.hos.broker.common.shell;
import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@ -21,13 +22,13 @@ public class SSHLinuxTool {
    public static final String BEAN_ID = "SSHLinuxTool";
    @Value("${jcraft.host}")
    @Value("${hos.jcraft.host}")
    private String host;
    @Value("${jcraft.port}")
    @Value("${hos.jcraft.port}")
    private Integer port;
    @Value("${jcraft.user}")
    @Value("${hos.jcraft.user}")
    private String user;
    @Value("${jcraft.password}")
    @Value("${hos.jcraft.password}")
    private String password;
    public static Channel channel = null;
@ -53,23 +54,23 @@ public class SSHLinuxTool {
    }
    public String exeCommand(Session session, String command, boolean exit) throws JSchException, IOException {
        if (!session.isConnected()) {
            session = getsessionConn();
        }
        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand(command);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        String out = IOUtils.toString(in, "UTF-8");
        if (exit) {
            channelExec.disconnect();
        }
        return out;
    }
//    public String exeCommand(Session session, String command, boolean exit) throws JSchException, IOException {
//
//        if (!session.isConnected()) {
//            session = getsessionConn();
//        }
//
//        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
//        InputStream in = channelExec.getInputStream();
//        channelExec.setCommand(command);
//        channelExec.setErrStream(System.err);
//        channelExec.connect();
//        String out = IOUtils.toString(in, "UTF-8");
//        if (exit) {
//            channelExec.disconnect();
//        }
//        return out;
//    }
    /**
@ -85,7 +86,7 @@ public class SSHLinuxTool {
            //创建sftp通信通道
            if (channel == null) {
                channel = session.openChannel("shell");
                channel.connect(1000);
                channel.connect(3000);
            }
            //获取输入流和输出流
            InputStream instream = channel.getInputStream();

+ 35 - 0
hos-broker/src/main/java/com/yihu/hos/broker/controllers/ESBShellController.java

@ -0,0 +1,35 @@
package com.yihu.hos.broker.controllers;
import com.yihu.hos.broker.services.ServerShellService;
import com.yihu.hos.web.framework.model.Result;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/1/6.
 */
@RestController
@RequestMapping("/esb")
public class ESBShellController {
    @Resource(name = ServerShellService.BEAN_ID)
    private ServerShellService serverShellService;
    @RequestMapping(value = "/serviceShell/send", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation(value = "shell命令执行", produces = "application/json", notes = "执行shell命令并返回结果")
    public Result onServiceFlowModifyAdd(
            @ApiParam(name = "msg", value = "消息", required = true)
            @RequestBody() String msg) {
        return serverShellService.executeShell(msg);
    }
}

+ 61 - 0
hos-broker/src/main/java/com/yihu/hos/broker/services/ServerShellService.java

@ -0,0 +1,61 @@
package com.yihu.hos.broker.services;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jcraft.jsch.Session;
import com.yihu.hos.broker.common.shell.SSHLinuxTool;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.model.bo.ServiceShell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/1/6.
 */
@Service("ServerShellService")
public class ServerShellService {
    public static final String BEAN_ID = "ServerShellService";
    @Resource(name = SSHLinuxTool.BEAN_ID)
    private SSHLinuxTool sshLinuxTool;
    @Autowired
    private ObjectMapper objectMapper;
    public static Session session ;
    public Result executeShell(String msg) {
        String result="";
        try {
            ServiceShell serviceShell = objectMapper.readValue(msg , ServiceShell.class);
            if (session==null){
                session = sshLinuxTool.getsessionConn();
            }
            if (!serviceShell.isDisconnect()) {
                //保持通道连接
                System.out.println("执行命令,并保持当前会话==================");
                result = sshLinuxTool.sshShell(session, serviceShell.getCommand(), false);
                System.out.println("结果:"+result);
                return Result.success(result);
            } else {
                //断开通道连接,会话
                System.out.println("执行命令,并结束当前会话==================");
                result = sshLinuxTool.sshShell(session, serviceShell.getCommand(), true);
                session = null;
                System.out.println("结果:"+result);
                return Result.success(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("shell命令执行失败!");
    }
}

+ 12 - 0
hos-broker/src/main/resources/application.yml

@ -58,6 +58,12 @@ hos:
      period: 10000
  tenant:
    name: jkzl
  #jcraft shell操作
  jcraft:
    host: 172.19.103.57
    port: 22
    user: root
    password: ceshi
---
spring:
@ -148,3 +154,9 @@ hos:
      period: 10000
  tenant:
    name: yichang
  #jcraft shell操作
  jcraft:
    host: 172.19.103.57
    port: 22
    user: root
    password: ceshi

+ 4 - 2
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ServiceFlowConstant.java

@ -47,7 +47,9 @@ public interface ServiceFlowConstant {
    //Arbiter shell
    String ARBITER_SHELL_SEND = "arbiterShellSend"; //shell 命令执行消息
    String ARBITER_SHELL_ACEPT = "arbiterShellAcept"; //shell 执行结果消息
    String SHELL = "shell";
    //arbiter 发送shell命令 消息队列
    String SHELL_ARBITER = "shell_arbiter";
    // hos-admin 接收shell执行结果
    String SHELL_ADMIN = "shell_admin";
}

+ 5 - 0
pom.xml

@ -143,6 +143,11 @@
            <artifactId>json</artifactId>
            <version>20140107</version>
        </dependency>
        <dependency>
            <groupId>org.zbus</groupId>
            <artifactId>zbus</artifactId>
            <version>7.2.0</version>
        </dependency>
    </dependencies>
    <build>

+ 33 - 47
src/main/java/com/yihu/hos/config/BeanConfig.java

@ -3,13 +3,11 @@ package com.yihu.hos.config;
import com.yihu.hos.interceptor.AuditInterceptor;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
@ -21,10 +19,11 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.zbus.broker.ZbusBroker;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
/**
@ -36,57 +35,45 @@ import java.util.Properties;
@EnableTransactionManagement
@ComponentScan("com.yihu.hos")
//@ImportResource({"classpath:spring/applicationContext.xml"}) //applicationContext相关bean创建
public class BeanConfig  implements EnvironmentAware {
public class BeanConfig {
    @Autowired
    BasicDataSource dataSource;
//    @Value("${spring.jpa.hibernate.dialect}")
//    private String dialect;
//    @Value("${spring.jpa.format-sql}")
//    private String formatSql;
//    @Value("${spring.jpa.show-sql}")
//    private String showSql;
    @Value("${hos.zbus.url}")
    private String zbusUrl;
    private ZbusBroker zbusBroker;
    private Environment environment;
    private Map<String , Object> hibernatePropertyResolver;
    private Map<String , Object> datasourcePropertyResolver;
    //从application.yml中读取资源
    @Bean
    public ZbusBroker getZbusBroker() {
        try {
            zbusBroker = new ZbusBroker(this.zbusUrl);
            return zbusBroker;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
        datasourcePropertyResolver = new RelaxedPropertyResolver(environment).getSubProperties("spring.datasource.");
        this.hibernatePropertyResolver = new RelaxedPropertyResolver(environment).getSubProperties("spring.jpa.");
    protected void finalize() throws Throwable {
        if (zbusBroker != null) {
            zbusBroker.close();
        }
        super.finalize();
    }
    //sessionFactory
//    @Bean
//    public LocalSessionFactoryBean sessionFactory() throws SQLException {
//        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
//        localSessionFactoryBean.setDataSource(this.dataSource);
//        Properties properties1 = new Properties();
//        properties1.setProperty("hibernate.dialect",hibernatePropertyResolver.get("hibernate.dialect").toString());
//        properties1.setProperty("hibernate.show_sql",hibernatePropertyResolver.get("show-sql").toString());
//        properties1.setProperty("hibernate.format_sql",hibernatePropertyResolver.get("format-sql").toString());
//        localSessionFactoryBean.setHibernateProperties(properties1);
//        localSessionFactoryBean.setPackagesToScan("com.yihu.hos.*.model");
//        ResourceLoader resourceLoader = new DefaultResourceLoader();
//        Resource resource = resourceLoader.getResource("classpath:resource/");
//        localSessionFactoryBean.setMappingDirectoryLocations(resource);
////        localSessionFactoryBean.setPackagesToScan("*");
//        return localSessionFactoryBean;
//    }
    @Bean
    public LocalSessionFactoryBean sessionFactory()   {
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
        localSessionFactoryBean.setDataSource(this.dataSource);
        Properties properties1 = new Properties();
        properties1.setProperty("hibernate.dialect","org.hibernate.dialect.MySQL5Dialect");
        properties1.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        properties1.setProperty("hibernate.show_sql", "false");
        properties1.setProperty("hibernate.format_sql","true");
        properties1.setProperty("hibernate.format_sql", "true");
        localSessionFactoryBean.setHibernateProperties(properties1);
        localSessionFactoryBean.setPackagesToScan("com.yihu.hos.*.model");
        ResourceLoader resourceLoader = new DefaultResourceLoader();
@ -131,23 +118,22 @@ public class BeanConfig  implements EnvironmentAware {
    //文经上传
    @Bean
    public CommonsMultipartResolver multipartResolver(){
    public CommonsMultipartResolver multipartResolver() {
        return new CommonsMultipartResolver();
    }
    //国际化配置
    @Bean
    public ResourceBundleMessageSource messageSource(){
        ResourceBundleMessageSource messageSource =new ResourceBundleMessageSource();
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasenames("text/message");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
    @Bean
    public CookieLocaleResolver localeResolver(){
    public CookieLocaleResolver localeResolver() {
        CookieLocaleResolver localeResolver = new CookieLocaleResolver();
        localeResolver.setCookieName("Language");
        localeResolver.setCookieMaxAge(604800);
@ -156,12 +142,12 @@ public class BeanConfig  implements EnvironmentAware {
    }
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor(){
    public LocaleChangeInterceptor localeChangeInterceptor() {
        return new LocaleChangeInterceptor();
    }
    @Bean
    public JdbcTemplate jdbcTemplate(){
    public JdbcTemplate jdbcTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        try {
            jdbcTemplate.setDataSource(this.dataSource);
@ -182,7 +168,7 @@ public class BeanConfig  implements EnvironmentAware {
    }
    @Bean
    public AuditInterceptor auditInterceptor(){
    public AuditInterceptor auditInterceptor() {
        return new AuditInterceptor();
    }

+ 3 - 0
src/main/java/com/yihu/hos/remoteManage/controller/RemoteShellController.java

@ -55,6 +55,9 @@ public class RemoteShellController extends BaseController {
            remoteShellService.sendShell(command, disCon);
            System.out.println("结果1:" + result);
            //TODO 接收shell命令执行结果 消息
            remoteShellService.start();
            result=remoteShellService.backResult;
            System.out.println("接口返回结果:"+result);
        } catch (Exception e) {
            e.printStackTrace();

+ 57 - 2
src/main/java/com/yihu/hos/remoteManage/service/RemoteShellService.java

@ -1,10 +1,18 @@
package com.yihu.hos.remoteManage.service;
import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.interceptor.LocalContext;
import com.yihu.hos.services.ServiceShellEventService;
import com.yihu.hos.web.framework.constant.ServiceFlowConstant;
import com.yihu.hos.web.framework.model.bo.ServiceShell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.zbus.broker.ZbusBroker;
import org.zbus.mq.Consumer;
import org.zbus.net.http.Message;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Date;
@ -17,10 +25,20 @@ import java.util.Date;
public class RemoteShellService {
    public static final String BEAN_ID = "RemoteShellService";
    @Value("${hos.zbus.url}")
    private String zbusUrl;
    @Autowired
    private ServiceShellEventService serviceShellEventService;
    private ZbusBroker zbusBroker;
    private Consumer consumer;
    public static String backResult;
    /**
     * 发送shell命令消息
     * @param command
     * @param disConnection
     * @return
     */
    public boolean sendShell(String command,boolean disConnection){
        InetAddress addr = null;
        try {
@ -36,11 +54,48 @@ public class RemoteShellService {
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    public void proxy(Message message, Consumer consumer) {
        String bodyString = message.getBodyString();
        this.backResult=bodyString;
    }
    public void start() {
        if (zbusBroker == null) {
            System.out.println("zbusBroker is null");
            return;
        }
        String attachment = LocalContext.getContext().getAttachment(ContextAttributes.TENANT_NAME);
        if (attachment==null){
            return;
        }
        consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_ADMIN + "@" + attachment);
        try {
            consumer.start(this::proxy);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
    @Autowired
    public void setZbusBroker(ZbusBroker zbusBroker) {
        this.zbusBroker = zbusBroker;
    }
    @Override
    protected void finalize() throws Throwable {
        consumer.close();
        super.finalize();
    }
}

+ 4 - 0
src/main/resources/application.yml

@ -56,6 +56,10 @@ spring:
    pooled: false
  aop:
    proxy-target-class: true
hos:
  zbus:
    url: 192.168.131.119:15555
---
spring:
  profiles: test