apache-activemq使用小结

 

发送消息的基本步骤:

(1)、创建连接使用的工厂类JMS ConnectionFactory

(2)、使用管理对象JMS ConnectionFactory建立连接Connection,并启动

(3)、使用连接Connection 建立会话Session

(4)、使用会话Session和管理对象Destination创建消息生产者MessageSender

(5)、使用消息生产者MessageSender发送消息

代码示例:

package com.suteam.zsyun.mq;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.jms.DeliveryMode;
import javax.jms.MapMessage;
import javax.jms.Queue;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSON;
import com.suteam.zsyun.commonUtil.RandomUtil;
import com.suteam.zsyun.systemOpra.model.MqManagement;

/**
 * 发送消息工具类
 * 
 * @author zsyun_Fangqingzhu
 *
 */
public class MqUtilSend {
    public static Logger log = Logger.getLogger(MqUtilSend.class);

    /**
     * 发送消息
     * 
     * @param session
     * @param sender
     * @param cont
     * @param sendMan
     * @param userName
     * @throws Exception
     */
    public static void sendMessage(QueueSession session, QueueSender sender, String cont, String sendMan,
            String userName, String serviceType, String taskId,String logCode) throws Exception {
        log.info(logCode+"---进入发送消息工具类中,sendMessage方法:");
        MapMessage map = session.createMapMessage();
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        // 把对象转换成json,
        MqManagement mess = new MqManagement();
        mess.setContent(cont);
        mess.setReceiver(userName);
        mess.setSender(sendMan);
        mess.setSendTime(time);
        mess.setServiceType(Integer.parseInt(serviceType));
        mess.setTaskId(taskId);
        String json = JSON.toJSONString(mess);
        // 把要发送的内容,放到map中,说能map传送
        map.setString("receiver", userName);
        map.setString("send", sendMan);
        map.setString("cont", cont);
        map.setString("time", time);
        map.setString("type", "mqReceiver");
        map.setString("json", json);
        log.info(logCode+"---" + map.getString("send") + "-给-" + map.getString("receiver") + "-发送消息:" + map.getString("cont"));
        sender.send(map);
        log.info(logCode+"---发送消息工具类中,sendMessage方法执行完成:");
    }

    /**
     * 建立连接(发送消息)
     * 
     * @param message
     * @param userName
     * @param sendMan
     * @throws Exception
     */
    public static void run(String message, String userName, String sendMan, String serviceType, String taskId,QueueSession session) throws Exception {
        // 日志号
        String logCode = RandomUtil.getRandomKey(20);
        log.info(logCode+"---发送消息工具类,发送消息开始");
        try {
            if(session == null){
                AgentSessionFactory.checkSession=true;
                session = AgentSessionFactory.getSession(null);
            }
            // 创建一个消息队列
            Queue queue = session.createQueue(userName);
            // 发送消息建立的队列名:
            // 创建消息发送者
            javax.jms.QueueSender sender = session.createSender(queue);
            // 设置持久化模式
            sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            sendMessage(session, sender, message, sendMan, userName, serviceType, taskId,logCode);
            // 提交会话
            session.commit();
        } catch (Exception e) {
            //异常后,重新创建连接,保持MQ通信
            log.error("发送消息工具类中抛出异常,重建MQ连接"+e.getMessage());
            AgentSessionFactory.checkSession=true;
            AgentSessionFactory.getSession(null);
            log.error("发送消息工具类中抛出异常,重建MQ连接--完成");
        } 
        log.info(logCode+"---发送消息工具类,发送消息结束");
    }

}

消息接收者从JMS接受消息的步骤:

(1)、创建连接使用的工厂类JMS ConnectionFactory

(2)、使用管理对象JMS ConnectionFactory建立连接Connection,并启动

(3)、使用连接Connection 建立会话Session

(4)、使用会话Session和管理对象Destination创建消息接收者MessageReceiver

(5)、使用消息接收者MessageReceiver接受消息,需要用setMessageListener将MessageListener接口绑定到MessageReceiver消息接收者必须实现了MessageListener接口,需要定义onMessage事件方法。

代码示例:

package com.suteam.zsyun.mq;


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.suteam.zsyun.commonUtil.DateUtil;
import com.suteam.zsyun.commonUtil.EnumServiceTypeCode;
import com.suteam.zsyun.commonUtil.FileUtil;
import com.suteam.zsyun.commonUtil.RandomUtil;
import com.suteam.zsyun.config.Config;
import com.suteam.zsyun.systemInfo.model.basicModel.SysInfo;
import com.suteam.zsyun.systemOpra.model.CommanderJson;
import com.suteam.zsyun.systemOpra.model.MqManagement;
import com.suteam.zsyun.systemOpra.util.ModifyUtil;
import com.suteam.zsyun.xen.util.GetXenInfo;

/**
 * 接受消息
 * 
 * @author zsyun_Fangqingzhu
 *
 */
public class MqUtilReceiver {
    public static Logger log = Logger.getLogger(MqUtilReceiver.class);
    /**
     * 建立连接(接收消息)
     * 
     * @param userName
     * @throws Exception
     */
    public static void run(String userName) throws Exception {
        
        log.info("进入接受消息工具类");
        try {
            // 读取config配置文件和agentUuid配置文件
            String configPath = FileUtil.getConfigPath();
            final Properties configProperties = FileUtil.getConfig(configPath + Config.configName);
            final Properties properties = FileUtil.getConfig(configPath + Config.agentConfigName);
            String zsCloudUUID = configProperties.getProperty("zsCloud_uuid");
            // 获取session
            final QueueSession session = AgentSessionFactory.getSession(null);
            // 创建一个消息队列
            Queue queue = session.createQueue(userName);
            // 接收消息时,所创建的队列名
            // 创建消息制作者
            QueueReceiver receiver = session.createReceiver(queue);
            // 设置接收消息的监听器,并用他的匿名内部类接收消息
            receiver.setMessageListener(new MessageListener() {
                public void onMessage(Message msg) {
                    if (msg != null) {
                        // 日志号
                        String logCode = RandomUtil.getRandomKey(20);
                        MapMessage map = (MapMessage) msg;
                        log.info(logCode+"---收到一条消息,并准备开始解析消息内容:");
                        try {
                            // 1.获取数组位数
                            Integer arrayNum = HycloudUuidCollection.arrayNum;
                            // 2.获取操作hycloud的uuid的工具类中的uuid
                            String adminUuid = HycloudUuidCollection.getUuid(arrayNum);
                            log.info(logCode+"---"+map.getString("receiver") + "-收到-" + map.getString("send") + "-发来的消息为-:"
                                    + map.getString("cont"));
                            String messTOJson = map.getString("json");
                            MqManagement mess = (MqManagement) JSON.parseObject(messTOJson, MqManagement.class);
                            // 3.获取发送内容
                            String cont = mess.getContent();
                            // 4.获取业务类型
                            Integer serviceType = mess.getServiceType();
                            // 5.获取发送人
                            String send = mess.getSender();
                            // 6.获取任务号
                            String taskId = mess.getTaskId();
                            log.info("@@@@@@@@@@@@@@@@@@@@@@@@taskId:"+taskId);
                            
//                            // 7.判断发送人是否为hycloud主机
//                            if(!send.equals(adminUuid)){
//                                log.info(logCode+"---发送人不是hycloud主机,结束操作。");
//                                log.info(logCode+"---send: "+send);
//                                log.info(logCode+"---adminUuid: "+adminUuid);
//                                return;
//                            }
                            // 是hycloud主机,则判断消息类型
                            // 8.判断接受到的消息serviceType  0.通讯校验 1.收到信息确认 2.异常报警提示 3.修改ip 4.修改密码  5.修改用户
                            // serviceType为 0.通讯校验  
                            if(serviceType == 0){
                                log.info(logCode+"---接受到的业务类型为0,为通讯校验");
                            }
                            // serviceType为1.收到信息确认
                            if(serviceType == 1){
                                log.info(logCode+"---接受到的业务类型为1,为信息确认");
                                // 成功接受hycloud的uuid的信息确认   
                                // 将发送状态改为1 已回复
                                HycloudUuidCollection.sendState = 1;
                            }
                            // serviceType为3.修改ip
                            if(serviceType == 3){
                                log.info(logCode+"---接受到的业务类型为3,进行修改ip操作");
                                MqManagement mess1 = new MqManagement();
                                mess1.setServiceType(1);//1.修改ip
                                mess1.setStatus(3);//3.收到信息确认
                                mess1.setTaskId(taskId);
                                String messJson2 = JSON.toJSONString(mess1);
                                MqUtilSend.run(messJson2, adminUuid,
                                        properties.getProperty("agentUuid"),EnumServiceTypeCode.CODE_000003.code,taskId,AgentSessionFactory.getSession(null));
                                //判断是Linux系统还是Windows系统
                                String path = System.getProperty("user.dir");
                                //Linux系统
                                if(path.contains("/")){
                                    log.info(logCode+"---修改Linux的ip:");
                                    //调用修改操作工具类,修改Linux系统的ip
                                    String str = ModifyUtil.chLinuxIp(cont);
                                    //修改ip成功,给hycloud返回信息
                                    if(str.equals("success")){
                                        log.info(logCode+"---修改Linux的ip成功,将修改成功信息返回给hycloud系统:");
                                        MqManagement mess2 = new MqManagement();
                                        mess2.setServiceType(1);//1.修改ip
                                        mess2.setStatus(1);//1.处理成功
                                        mess2.setTaskId(taskId);
                                        String messJson = JSON.toJSONString(mess2);
                                            MqUtilSend.run(messJson, adminUuid,
                                                    properties.getProperty("agentUuid"),EnumServiceTypeCode.CODE_000003.code,taskId,AgentSessionFactory.getSession(null));
                                        log.info(logCode+"---将修改成功信息返回给hycloud系统的操作完成。");
                                    }
                                    //修改密码失败,给hycloud返回信息
                                    if(str.equals("fail")){
                                        log.info(logCode+"---修改Linux的ip失败,将修改失败信息返回给hycloud系统:");
                                        MqManagement mess2 = new MqManagement();
                                        mess2.setServiceType(1);//1.修改ip
                                        mess2.setStatus(2);//2.处理失败
                                        mess2.setTaskId(taskId);
                                        String messJson = JSON.toJSONString(mess2);
                                            MqUtilSend.run(messJson, adminUuid,
                                                    properties.getProperty("agentUuid"),EnumServiceTypeCode.CODE_000003.code,taskId,AgentSessionFactory.getSession(null));
                                        log.info(logCode+"---将修改失败信息返回给hycloud系统的操作完成。");
                                    }
                                }
                                //Windows系统
                                else if(path.contains("\\")){
                                    log.info(logCode+"---修改Windows的ip:");
                                    // Windows系统,调用修改操作工具类,修改Windows系统的ip
                                    String str = ModifyUtil.chWinIp(cont);
                                    // 修改完windowsip后,线程休眠10s
                                    Thread.sleep(10000);
                                    // 修改ip成功,给hycloud返回信息
                                    if(str.equals("success")){
                                        log.info(logCode+"---修改Windows的ip成功,将修改成功信息返回给hycloud系统:");
                                        MqManagement mess2 = new MqManagement();
                                        mess2.setServiceType(1);//1.修改ip
                                        mess2.setStatus(1);//1.处理成功
                                        mess2.setTaskId(taskId);
                                        String messJson = JSON.toJSONString(mess2);
                                        AgentSessionFactory.checkSession=true;
                                        MqUtilSend.run(messJson, adminUuid,
                                                properties.getProperty("agentUuid"),EnumServiceTypeCode.CODE_000003.code,taskId,AgentSessionFactory.getSession("chWindowsIp"));
                                        String date = DateUtil.getTimeStamp();
                                        log.info(logCode+"---将修改成功信息返回给hycloud系统的操作完成。"+date);
                                    }
                                    //修改ip失败,给hycloud返回信息
                                    if(str.equals("fail")){
                                        log.info(logCode+"---修改Windows的ip失败,将修改失败信息返回给hycloud系统:");
                                        MqManagement mess2 = new MqManagement();
                                        mess2.setServiceType(1);//1.修改ip
                                        mess2.setStatus(2);//2.处理失败
                                        mess2.setTaskId(taskId);
                                        String messJson = JSON.toJSONString(mess2);
                                        AgentSessionFactory.checkSession=true;
                                        MqUtilSend.run(messJson, adminUuid,
                                                properties.getProperty("agentUuid"),EnumServiceTypeCode.CODE_000003.code,taskId,AgentSessionFactory.getSession("chWindowsIp"));
                                        log.info(logCode+"---将修改失败信息返回给hycloud系统的操作完成。");
                                    }
                                }
                            }
                            // serviceType为4.修改密码
                            if(serviceType == 4){
                                log.info(logCode+"---接受到的业务类型为4,进行修改密码操作");
                                //判断是Linux系统还是Windows系统
                                String path = System.getProperty("user.dir");
                                //Linux系统
                                if(path.contains("/")){
                                    log.info(logCode+"---修改Linux的密码:");
                                    //Linux系统,调用修改操作工具类,修改Linux系统的密码
                                    String str = ModifyUtil.chLinuxPswd(cont);
                                    //修改密码成功,给hycloud返回信息
                                    if(str.equals("success")){
                                        log.info(logCode+"---修改Linux的密码成功,将修改成功信息返回给hycloud系统:");
                                        MqManagement mess1 = new MqManagement();
                                        mess1.setServiceType(2);//2.修改密码
                                        mess1.setStatus(1);//1.处理成功
                                        mess1.setTaskId(taskId);
                                        String messJson = JSON.toJSONString(mess1);
                                            MqUtilSend.run(messJson, adminUuid,
                                                    properties.getProperty("agentUuid"),EnumServiceTypeCode.CODE_000004.code,taskId,session);
                                        log.info(logCode+"---将修改成功信息返回给hycloud系统操作完成。");
                                    }
                                    //修改密码失败,给hycloud返回信息
                                    if(str.equals("fail")){
                                        log.info(logCode+"---修改Linux的密码失败,将修改失败信息返回给hycloud系统:");
                                        MqManagement mess1 = new MqManagement();
                                        mess1.setServiceType(2);//2.修改密码
                                        mess1.setStatus(2);//2.处理失败
                                        mess1.setTaskId(taskId);
                                        String messJson = JSON.toJSONString(mess1);
                                            MqUtilSend.run(messJson, adminUuid,
                                                    properties.getProperty("agentUuid"),EnumServiceTypeCode.CODE_000004.code,taskId,session);
                                        log.info(logCode+"---将修改失败信息返回给hycloud系统操作完成。");
                                    }
                                }
                                //Windows系统
                                else if(path.contains("\\")){
                                    log.info(logCode+"---修改Windows的密码:");
                                    //Windows系统,调用修改操作工具类,修改Windows系统的密码
                                    String str = ModifyUtil.chWinPswd(cont);
                                    //修改密码成功,给hycloud返回信息
                                    if(str.equals("success")){
                                        log.info(logCode+"---修改Windows的密码成功,将修改成功信息返回给hycloud系统:");
                                        MqManagement mess1 = new MqManagement();
                                        mess1.setServiceType(2);//2.修改密码
                                        mess1.setStatus(1);//1.处理成功
                                        mess1.setTaskId(taskId);
                                        String messJson = JSON.toJSONString(mess1);
                                        log.info("messJson:"+messJson);
                                        MqUtilSend.run(messJson, adminUuid,
                                                properties.getProperty("agentUuid"),EnumServiceTypeCode.CODE_000004.code,taskId,session);
                                        log.info(logCode+"---将修改成功信息返回给hycloud系统操作完成。");
                                    }
                                    //修改密码失败,给hycloud返回信息
                                    if(str.equals("fail")){
                                        log.info(logCode+"---修改Windows的密码失败,将修改失败信息返回给hycloud系统:");
                                        MqManagement mess1 = new MqManagement();
                                        mess1.setServiceType(2);//2.修改密码
                                        mess1.setStatus(2);//2.处理失败
                                        mess1.setTaskId(taskId);
                                        String messJson = JSON.toJSONString(mess1);
                                        MqUtilSend.run(messJson, adminUuid,
                                                properties.getProperty("agentUuid"),EnumServiceTypeCode.CODE_000004.code,taskId,session);
                                        log.info(logCode+"---将修改失败信息返回给hycloud系统操作完成。");
                                    }
                                }
                            }
                            // serviceType为5 修改用户
                            if(serviceType == 5){
                                // 获取要修改的信息
                                SysInfo sysInfo = JSON.parseObject(cont,SysInfo.class);
                                String agentUuid = sysInfo.getAgentUuid();
                                String userNum = sysInfo.getAgentUuid();
                                // 获取配置文件路径
                                String configPath = FileUtil.getConfigPath();
                                // 读取文件
                                String fileName =configPath+"uuid.ini";
                                FileInputStream fis = null;   
                                OutputStream fos ;  
                                Properties pp; 
                                pp = new Properties();  
                                fis = new FileInputStream(fileName);  
                                pp.load(fis); 
                                fos=new FileOutputStream(fileName);//加载读取文件流
                                // 将agentUuid与userId写入ini文件
                                pp.setProperty("agentUuid", agentUuid );  
                                pp.setProperty("userNum", userNum );
                                pp.store(fos, null); 
                                fos.close();  
                                // 回复hycloud修改成功
                                MqManagement mess1 = new MqManagement();
                                mess1.setServiceType(5);//5.修改用户
                                mess1.setStatus(1);//1.处理成功
                                mess1.setTaskId(taskId);
                                String messJson = JSON.toJSONString(mess1);
                                log.info("messJson:"+messJson);
                                log.info(logCode+"---将修改用户成功信息返回给hycloud系统操作开始。");
                                MqUtilSend.run(messJson, adminUuid,
                                        properties.getProperty("agentUuid"),EnumServiceTypeCode.CODE_000005.code,taskId,session);
                                log.info(logCode+"---将修改用户成功信息返回给hycloud系统操作完成。");
                            }
                            
                            // serviceType为6.启动通讯业务
                            if(serviceType == 6){
                                log.info(logCode+"---接受到的业务类型为6,启动通讯业务");
                                // 获取返回内容
                                MqManagement message = JSON.parseObject(cont,MqManagement.class);
                                Integer status = message.getStatus();
                                // 启动通讯业务成功
                                if(status == 1){
                                    HycloudUuidCollection.checkStart = false;
                                }
                            }
                            // serviceType为8.创建云服务
                            if(serviceType == 8){
                                log.info(logCode+"---接受到的业务类型为8,创建云服务");
                                // 获取返回内容
                                MqManagement message = JSON.parseObject(cont,MqManagement.class);
                                // 获取发送者
                                send = message.getSender();
                                // agent发送信息实体类
                                MqManagement mqManagement = new MqManagement();
                                mqManagement.setStatus(0);// 待处理
                                mqManagement.setTaskId(taskId);// taskId对应的为指令记录号
                                mqManagement.setServiceType(8);// 业务类型, 8.创建云服务
                                // 给commander发送确认信息
                                log.info(logCode+"---给commander发送确认信息:");
                                MqUtilSend.run(JSON.toJSONString(mqManagement), send, properties.getProperty("agentUuid"), EnumServiceTypeCode.CODE_000008.code,
                                        taskId, AgentSessionFactory.getSession(null));
                                log.info(logCode+"---给commander发送确认信息完成。");
                                Integer status = message.getStatus();
                                String commandContent = message.getContent();
                                // 解析消息内容,分别获取开机对应指令,磁盘对应指令,以及要创建的虚拟机内存大小等参数
                                CommanderJson commanderJson = JSON.parseObject(commandContent,CommanderJson.class);
                                // 开机指令
                                String xenCommand = commanderJson.getXenCommand();
                                // 数据盘指令
                                List<String> dataDisk = commanderJson.getDataDisk();
                                // 系统盘指令
                                String systemDisk  = commanderJson.getSystemDisk();
                                // 参数
                                List<Object> param  = commanderJson.getParam();
                                // 获取物理机剩余内存大小,以及存储池templatesPoolPath
                                Map<String,String> paramMap = (Map<String, String>) param.get(0);
                                String memCapacity = paramMap.get("memCapacity");
                                String templatesPoolPath = paramMap.get("templatesPoolPath");
                                // 物理机剩余内存的大小
                                String freeCapacity = GetXenInfo.getFreeCapacity();
                                // 比较物理机剩余内存的大小是否大于要创建的虚拟机内存大小
                                if(Integer.parseInt(freeCapacity) <= Integer.parseInt(memCapacity)){
                                    log.info(logCode+"---物理机剩余内存小于要创建的虚拟机内存! ");
                                    MqManagement mqManagement2 = new MqManagement();
                                    mqManagement.setStatus(2);// 处理失败
                                    mqManagement.setTaskId(taskId);// taskId对应的为指令记录号
                                    mqManagement.setServiceType(8);// 业务类型, 8.创建云服务
                                    // 物理机剩余内存小于要创建的虚拟机内存
                                    log.info(logCode+"---物理机剩余内存小于要创建的虚拟机内存,向commander发送创建失败信息。");
                                    MqUtilSend.run(JSON.toJSONString(mqManagement2), send, properties.getProperty("agentUuid"), EnumServiceTypeCode.CODE_000008.code,
                                            taskId, AgentSessionFactory.getSession(null));
                                    log.info(logCode+"---物理机剩余内存小于要创建的虚拟机内存,向commander发送创建失败信息,完成。");
                                    return;
                                }
                                // 说明物理机剩余内存足够创建云服务虚拟机
                                // 如果存在systemDisk
//                                if(null != systemDisk){
//                                    // 解析systemDisk对应的指令
//                                    // 获取参数中的templatesPoolPath,即模板池路径
//                                    // 根据模板池路径去获取一个创建好的(complete)磁盘
//                                    
//                                    String diskName = "" ;
//                                    // 将mv指令中的<templatesPoolPath>替换成参数templatesPoolPath的数据,后跟从模板池路径取到的磁盘名称
//                                    systemDisk = systemDisk.replace("<templatesPoolPath>", templatesPoolPath + diskName);
//                                    // 执行mv指令,将此磁盘移动到要安装的路径
//                                    Process ps = Runtime.getRuntime().exec(systemDisk); 
//                                    BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));  
//                                    StringBuffer sb = new StringBuffer();  
//                                    String line;  
//                                    while ((line = br.readLine()) != null) {  
//                                        sb.append(line).append("\n");  
//                                    } 
//                                    br.close();
//                                    String result = sb.toString(); 
//                                    log.info("mv 指令获取到的数据结果result: "+result);
//                                 
//                                }
//                                // 获取dataDisk对应的指令
//                                // 执行操作磁盘的指令(lv create -L   或 qemu-img create -f raw)
//                                for (int i = 0; i < dataDisk.size(); i++) {
//                                    String dateDiskCommander = dataDisk.get(i);
//                                    Process ps = Runtime.getRuntime().exec(dateDiskCommander); 
//                                    BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));  
//                                    StringBuffer sb = new StringBuffer();  
//                                    String line;  
//                                    while ((line = br.readLine()) != null) {  
//                                        sb.append(line).append("\n");  
//                                    } 
//                                    br.close();
//                                    String result = sb.toString(); 
//                                    log.info("dateDiskCommander 指令获取到的数据结果result: "+result);
//                                }
//                                // 获取xenCommand对应的开机指令
//                                // 执行开机指令(xl create)
//                                Process ps = Runtime.getRuntime().exec(xenCommand); 
//                                BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));  
//                                StringBuffer sb = new StringBuffer();  
//                                String line;  
//                                while ((line = br.readLine()) != null) {  
//                                    sb.append(line).append("\n");  
//                                } 
//                                br.close();
//                                String result = sb.toString(); 
//                                log.info("xenCommand 指令获取到的数据结果result: "+result);
                                
                                
                                
                                // 向Commander返回信息,创建云服务虚拟机成功/失败
//                                MqManagement mqManagement2 = new MqManagement();
//                                mqManagement.setTaskId(taskId);// taskId对应的为指令记录号
//                                mqManagement.setServiceType(8);// 业务类型, 8.创建云服务
//                                MqUtilSend.run(JSON.toJSONString(mqManagement2), send, properties.getProperty("agentUuid"), EnumServiceTypeCode.CODE_000008.code,
//                                        taskId, AgentSessionFactory.getSession(null));
                                
                            }
                            
                            log.info(logCode+"---messList.add(mess);"+mess);
                            //map.acknowledge();
                        } catch (Exception e) {
                            //异常后,重新创建连接,保持MQ通信
                            log.error("接收消息时抛出异常,重建MQ连接"+e.getMessage());
                            AgentSessionFactory.checkSession=true;
                            AgentSessionFactory.getSession(null);
                            log.error("接收消息时抛出异常,重建MQ连接--完成。");
                        }
                    }
                }
            });
            // 休眠1s再关闭
            Thread.sleep(1000);
            // 提交会话
            session.commit();
        } catch (Exception e) {
            //异常后,重新创建连接,保持MQ通信
            log.error(e.getMessage());
        }
        log.info("接受消息工具类结束。");
    }
}

session工厂类示例:

package com.suteam.zsyun.mq;

import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.Logger;

/**
 * MQ连接会话工具类
 * @author zsyun_gongsiai
 *
 */
public class AgentSessionFactory {
    public static Logger log = Logger.getLogger(AgentSessionFactory.class);
    public static QueueSession session;
    public static QueueConnection connection;
    public static boolean checkSession = true;//true代表需要重新建立连接
    /**
     * 获取session
     * @return session
     */
    public synchronized static QueueSession getSession(String str) {
        log.info("进入获取session工具类");
        // 获取数组位数
        Integer arrayNum = MqServerUrl.arrayNum;
        if (checkSession) {
            try {
                // 1.获取Mq连接的url
                String BROKER_URL = MqServerUrl.getMqServerUrl(str);
                log.info("要进行的Mq的连接的url: "+BROKER_URL);
                log.info("获取session工具类中,重建MQ连接,获取session");
                // 2.创建链接工厂
                QueueConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
                        ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);
                // 3.通过工厂创建一个连接
                connection = factory.createQueueConnection();
                // 4.启动连接
                connection.start();
                // 5.创建一个session会话
                session = connection.createQueueSession(true, Session.CLIENT_ACKNOWLEDGE);
                checkSession = false;
                MqServerUrl.MQ_Server_Url = BROKER_URL;
            } catch (Exception e) {
                e.printStackTrace();
                // 连接异常,数组位数加1,为下一次取下一个Mq的url准备
                arrayNum +=1;
                MqServerUrl.arrayNum = arrayNum;
                // 取到最后一个url后,从第一个开始取
                if(arrayNum+1 > MqServerUrl.getIpCount()){
                    MqServerUrl.arrayNum = 0;
                }
            }
        }
        log.info("获取session完成,seession="+ session);
        return session;
    }
}                                
 

 

转载于:https://my.oschina.net/u/3037187/blog/809923

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值