RabbitMQ工厂&工具类

rabbitMq工厂类,封装了创建连接,释放连接等操作

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * rabbit工厂类
 *
 * @since 2018/12/13
 */
@Component
public class RabbitMqConnectionFactory {
    private static final Logger log = LoggerFactory.getLogger(RabbitMqConnectionFactory.class);

    private static ConnectionFactory connectionFactory = new ConnectionFactory();

    private static String addresses;

    private static int port;

    private static String username;

    private static String password;

    private static String virtualHost;

    /**
     * 设置addresses
     *
     * @param addresses addresses
     */
    @Value("${spring.rabbitmq.host}")
    public void setAddresses(String addresses) {
        setAddressesValue(addresses);
    }

    /**
     * 设置port
     *
     * @param port port
     */
    @Value("${spring.rabbitmq.port}")
    public void setPort(int port) {
        setPortValue(port);
    }

    /**
     * 设置username
     *
     * @param username username
     */
    @Value("${spring.rabbitmq.username}")
    public void setUsername(String username) {
        setUsernameValue(username);
    }

    /**
     * 设置password
     *
     * @param password password
     */
    @Value("${spring.rabbitmq.password}")
    public void setPassword(String password) {
        setPasswordValue(password);
    }

    /**
     * 设置virtualHost
     *
     * @param virtualHost virtualHost
     */
    @Value("${spring.rabbitmq.virtual-host}")
    public void setVirtualHost(String virtualHost) {
        setVirtualHostValue(virtualHost);
    }

    /**
     * 只创建一个ConnectionFactory
     * 双重检查加锁
     *
     * @return
     */
    private static ConnectionFactory getSingleInstance() {
        // 设置服务地址
        connectionFactory.setHost(addresses);

        // AMQP 5672
        connectionFactory.setPort(port);
        try {
            connectionFactory.useSslProtocol();
        } catch (NoSuchAlgorithmException e) {
            log.debug("NoSuchAlgorithmException :{}", e);
        } catch (KeyManagementException e) {
            log.debug("KeyManagementException :{}", e);
        }

        // 用户名
        connectionFactory.setUsername(username);

        // 密码
        connectionFactory.setPassword(password);

        // vhost
        connectionFactory.setVirtualHost(virtualHost);

        //  设置自动恢复
        connectionFactory.setAutomaticRecoveryEnabled(true);
        return connectionFactory;
    }

    /**
     * 创建连接
     *
     * @return Connection Connection
     */
    public static synchronized Connection getConnection() {
        getSingleInstance();
        Connection connection = null;

        int connectionNumber = 1;

        log.debug("RabbitMqConnectionFactory getConnection start ========== : {}", connectionNumber);

        do {
            try {
                log.debug("RabbitMqConnectionFactory getConnection :{}", connectionNumber);
                ++connectionNumber;
                connection = connectionFactory.newConnection();

                if (null != connection) {
                    log.debug("RabbitMqConnectionFactory getConnection  connection success");
                    break;
                }
            } catch (IOException e) {
                log.error("RabbitMqConnectionFactory getConnection error , connection bumber : {}",
                        connectionNumber - 1);
                log.error("IOException:{}",e);
            } catch (TimeoutException e) {
                log.error("RabbitMqConnectionFactory getConnection error , connection bumber : {}",
                        connectionNumber - 1);
                log.error("TimeoutException:{}",e);
            }
        } while (connectionNumber < 3);

        log.debug("RabbitMqConnectionFactory getConnection end ========== : {}", connectionNumber - 1);
        return connection;
    }

    /**
     * 关闭资源
     *
     * @param connection connection
     * @param channel    channel
     */
    public static void closeResource(Connection connection, Channel channel) {
        if (null != channel) {
            try {
                channel.close();
            } catch (IOException e) {
                log.error("IO Exception {}", e);
                log.error("IOException:{}",e);
                throw new CommonException("IO Exception");
            } catch (TimeoutException e) {
                log.error("Timeout Exception {}", e);
                log.error("TimeoutException:{}",e);
                throw new CommonException("Timeout Exception");
            }
        }
        if (null != connection) {
            try {
                connection.close();
            } catch (IOException e) {
                log.error("IOException:{}",e);
                log.error("IO Exception {}", e);
                throw new CommonException("IO Exception");
            }
        }
    }

    /**
     * 设置addressesValue
     *
     * @param addressesValue addressesValue
     */
    public static void setAddressesValue(String addressesValue) {
        RabbitMqConnectionFactory.addresses = addressesValue;
    }

    /**
     * 设置portValue
     *
     * @param portValue portValue
     */
    public static void setPortValue(int portValue) {
        RabbitMqConnectionFactory.port = portValue;
    }

    /**
     * 设置 passwordValue
     *
     * @param passwordValue passwordValue
     */
    public static void setPasswordValue(String passwordValue) {
        RabbitMqConnectionFactory.password = passwordValue;
    }

    /**
     * 设置 virtualHostValue
     *
     * @param virtualHostValue virtualHostValue
     */
    public static void setVirtualHostValue(String virtualHostValue) {
        RabbitMqConnectionFactory.virtualHost = virtualHostValue;
    }

    /**
     * 设置usernameValue
     *
     * @param usernameValue usernameValue
     */
    public static void setUsernameValue(String usernameValue) {
        RabbitMqConnectionFactory.username = usernameValue;
    }

    /**
     * 获取ip
     *
     * @return str ip地址
     */
    public static String getAddresses() {
        return addresses;
    }

    /**
     * 获取端口
     *
     * @return port 获取端口
     */
    public static int getPort() {
        return port;
    }

    /**
     * 获取登录用户名
     *
     * @return username 登录用户名
     */
    public static String getUsername() {
        return username;
    }

    /**
     * 获取登录用户密码
     *
     * @return username 登录用户密码
     */
    public static String getPassword() {
        return password;
    }
}

工具类:
封装了从mq上拉取消息,以及发送消息到mq上

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.GetResponse;
import com.rabbitmq.client.impl.recovery.RecordedQueue;

/**
 * McdRabbitMqUtil
 *
 * @since 2019/12/3
 */
@Component
public final class RabbitMqUtil {
    private static final Logger logger = LoggerFactory.getLogger(RabbitMqUtil.class);

    private RabbitMqUtil() {
    }

    /**
     * 根据序列名称、taskinfo字符串发送rabbit信息
     *
     * @param queueName queueName
     * @param taskInfo  taskInfo
     * @throws IOException      IOException
     * @throws TimeoutException TimeoutException
     */
    public static void sendMessageByQueueNameAndTaskInfo(String queueName, String taskInfo) {
        Connection connection = null;
        Channel channel = null;
        try {
            //  获取一个连接
            connection = RabbitMqConnectionFactory.getConnection();
            //  从连接中获取一个通道
            channel = connection.createChannel();
            //  创建队列声明。第二个参数为true,表示序列持久化; 第二个参数为false,表示不进行序列持久化
            channel.queueDeclare(queueName, true, false, false, null);

            //  发送消息。第三个参数设置为MessageProperties.PERSISTENT_TEXT_PLAIN,表示消息持久化
            channel.basicPublish(RecordedQueue.EMPTY_STRING, queueName, null, taskInfo.getBytes("utf-8"));
            logger.info(" [x] Sent '{}'", taskInfo);
        } catch (IOException e) {
            logger.error("IO Exception {}", e);
            throw new CommonException("IO Exception");
        } finally {
            RabbitMqConnectionFactory.closeResource(connection, channel);
        }
    }

    /**
     * 根据队列名称消费消息
     *
     * @param queueName queueName
     * @return String message
     */
    public static String receiveMessageByQueueName(String queueName) {

        GetResponse responseMessage = null;
        Connection connection = null;
        Channel channel = null;
        try {
            //  获取连接
            connection = RabbitMqConnectionFactory.getConnection();
            //  创建频道
            channel = connection.createChannel();
            //  自动确认消息
            boolean autoAck = true;

            //  队列声明
            channel.queueDeclare(queueName, true, false, false, null);

            responseMessage = channel.basicGet(queueName, autoAck);

        } catch (IOException e) {
            logger.error("IO Exception {}", e);
            throw new CommonException("IO Exception");
        } finally {
            RabbitMqConnectionFactory.closeResource(connection, channel);
        }

        //  定义返回结果数据
        String result = "";
        if (null != responseMessage) {
            try {
                result = new String(responseMessage.getBody(), "UTF-8");
                String ip = null;
                String host = null;
                try {
                    InetAddress ia = InetAddress.getLocalHost();
                    //  获取计算机主机名
                    host = ia.getHostName();
                    //  获取计算机IP
                    ip = ia.getHostAddress();
                } catch (UnknownHostException e) {
                    logger.error("UnknownHost Exception {}", e);
                }
                sendMessageByQueueNameAndTaskInfo("MESSAGE-MONITOR", result + "|" + ip + "|" + host);
            } catch (UnsupportedEncodingException e) {
                logger.error("UnsupportedEncoding Exception {}", e);
                throw new CommonException("UnsupportedEncoding Exception");
            }

        }
        return result;

    }
}

使用:
设置定时任务,定时去mq上取消息,然后处理

import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * 子任务队列中接收消息,进行处理
 *
 * @author ryz
 * @since 2020-05-11
 */
@Component
public class SubTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(SubTask.class);

    @Value("${engine.version.name}")
    private String EngineVersionName;

    @Value("${engine.version.code}")
    private String EngineVersionCode;


    @Autowired
    private AnalysisEngineService analysisEngineService;
	//30秒执行一次
    @Scheduled(fixedRate = 30000)
    public void process() throws IOException {
        String queueName = EngineVersionName + "-" + EngineVersionCode;
        String msg = RabbitMqUtil.receiveMessageByQueueName(queueName);
        if (StringUtil.isEmpty(msg)) {
            LOGGER.info(queueName + " is empty...");
            return;
        }
        //消息转成对应的bean
        TaskDto hapInfo = new ObjectMapper().readValue(msg, TaskDto.class);
        analysisEngineService.doService(hapInfo);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>