java实现可扩展的检测中间件链接状态

来源:互联网 发布:ccn网络 编辑:程序博客网 时间:2024/05/17 08:44

在某公司实习,前段时间实习遇到一个需求如下:

做一个组件,通过jar引入后,可以在web项目中检测中间件链接状态,如检测kafka,redis,mysql等的链接状态。


解决方案(欢迎读者提出意见):

1.由于公司之前有component组件,这是一个公共组件,里面包括公共工具类的二次封装,常量类等。所以想到把check放到这个组件中,只要加入component时候就可以使用了。

2.一个ICheckService接口,接口中有一个方法,所有被检测的中间件需要实现该接口,重写方法。方法中完成具体的状态检测。(在这里使用接口是为了在以后方便扩展,如果在具体的项目中,还想进行新的中间节扩展,可在具体项目中实现该接口。)

3.CheckMiddlewareService类完成中间件接口的所有实现类中方法的循环执行。在其他项目中,通过调用该类中的方法完成。

4.中间件的参数通过在具体使用jar包项目中的spring配置文件中配置。


实现:



package com.xxx.ad.core.service.check;import com.xxx.ad.core.dto.CheckParam;import java.util.List;import java.util.Map;public interface ICheckService {    /**     * 查询中间件连接状态     * @param reqList     * @return     */    List<Map<String, Object>> checkMiddlewareStatus(List<CheckParam> reqList);}



package com.xxx.ad.core.service.check;import com.google.common.collect.Lists;import com.google.common.collect.Maps;import com.xxx.ad.core.constant.BaseConstant;import com.xxx.ad.core.dto.CheckParam;import com.xxx.ad.core.util.CollectionUtil;import com.xxx.ad.core.util.StringUtil;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.springframework.stereotype.Service;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.List;import java.util.Map;@Servicepublic class CheckMysqlService implements ICheckService {    private Connection connection;    protected Logger logger = LogManager.getLogger(this.getClass());    /**     * 查询mysql连接状态     *     * @param reqList     * @return     */    @Override    public List<Map<String, Object>> checkMiddlewareStatus(List<CheckParam> reqList) {        List<Map<String, Object>> retList = Lists.newArrayList();        if (CollectionUtil.isEmpty(reqList)) {            Map<String, Object> retMap = Maps.newHashMap();            retMap.put(BaseConstant.RET_KEY, 0);            retMap.put(BaseConstant.RET_DESC, "mysql链接参数为null");            retList.add(retMap);            return retList;        }        for (CheckParam checkParam : reqList) {            Map<String, Object> retMap = Maps.newHashMap();            if (checkParam.getCheckName().equals("checkMysqlService")) {                String url = checkParam.getUrl();                String user = checkParam.getUser();                String password = checkParam.getPassword();                String driver = checkParam.getDatabaseDriver();                try {                    Class.forName(driver);                    connection = DriverManager.getConnection(url, user, password);                    if (!connection.isClosed()) {                        logger.info("数据库连接测试成功");                        retMap.put(BaseConstant.RET_KEY, 1);                        retMap.put(BaseConstant.RET_DESC, "数据库连接成功,url:" + url);                        retList.add(retMap);                    }                } catch (ClassNotFoundException e) {                    logger.error("找不到Driver", e);                    retMap.put(BaseConstant.RET_KEY, 0);                    retMap.put(BaseConstant.RET_DESC, "找不到Driver,url:" + url);                    retList.add(retMap);                } catch (SQLException e) {                    logger.info("数据库连接测试异常", e);                    retMap.put(BaseConstant.RET_KEY, 0);                    retMap.put(BaseConstant.RET_DESC, url + "数据库连接异常,url:" + url);                    retList.add(retMap);                } finally {                    try {                        connection.close();                    } catch (SQLException e) {                        logger.error("数据库关闭失败", e);                        retMap.put(BaseConstant.RET_KEY, 0);                        retMap.put(BaseConstant.RET_DESC, "数据库关闭失败,url:" + url);                        retList.add(retMap);                    }                }            }        }        return retList;    }}




package com.xxx.ad.core.service.check;import com.google.common.collect.Lists;import com.google.common.collect.Maps;import com.xxx.ad.core.constant.BaseConstant;import com.xxx.ad.core.dto.CheckParam;import com.xxx.ad.core.util.CollectionUtil;import com.xxx.ad.core.util.StringUtil;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.springframework.stereotype.Service;import redis.clients.jedis.Jedis;import java.util.List;import java.util.Map;@Servicepublic class CheckRedisService implements ICheckService {    private Jedis jedis;    protected Logger logger = LogManager.getLogger(this.getClass());    @Override    public List<Map<String, Object>> checkMiddlewareStatus(List<CheckParam> reqList) {        List<Map<String, Object>> retList = Lists.newArrayList();        if (CollectionUtil.isEmpty(reqList)) {            Map<String, Object> retMap = Maps.newHashMap();            retMap.put(BaseConstant.RET_KEY, 0);            retMap.put(BaseConstant.RET_DESC, "redis链接参数为null");            retList.add(retMap);        }        for (CheckParam checkParam : reqList) {            Map<String, Object> retMap = Maps.newHashMap();            if (checkParam.getCheckName().equals("checkRedisService")) {                String url = checkParam.getUrl();                int port = checkParam.getPort();                try {                    jedis = new Jedis(url, port);                    if (StringUtil.isNotEmpty(checkParam.getPassword())) {                        jedis.auth(checkParam.getPassword());                    }                    logger.info("redis连接成功");                    retMap.put(BaseConstant.RET_KEY, 1);                    retMap.put(BaseConstant.RET_DESC, "redis连接成功,url:" + url);                    retList.add(retMap);                } catch (Exception e) {                    logger.error("redis连接失败", e);                    retMap.put(BaseConstant.RET_KEY, 0);                    retMap.put(BaseConstant.RET_DESC, "redis连接失败,url: " + url);                    retList.add(retMap);                }            }        }        return retList;    }}


package com.xxx.ad.core.service.check;import com.google.common.collect.Lists;import com.google.common.collect.Maps;import com.xxx.ad.core.constant.BaseConstant;import com.xxx.ad.core.dto.CheckParam;import com.xxx.ad.core.util.CollectionUtil;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.springframework.stereotype.Service;import kafka.javaapi.producer.Producer;import kafka.producer.KeyedMessage;import kafka.producer.ProducerConfig;import java.util.List;import java.util.Map;import java.util.Properties;@Servicepublic class CheckKafkaService implements ICheckService {    protected Logger logger = LogManager.getLogger(this.getClass());    @Override    public List<Map<String, Object>> checkMiddlewareStatus(List<CheckParam> reqList) {        List<Map<String, Object>> retList = Lists.newArrayList();        if (CollectionUtil.isEmpty(reqList)) {            Map<String, Object> retMap = Maps.newHashMap();            retMap.put(BaseConstant.RET_KEY, 0);            retMap.put(BaseConstant.RET_DESC, "Kafka链接参数为null");            retList.add(retMap);        }        for (CheckParam checkParam : reqList) {            Map<String, Object> retMap = Maps.newHashMap();            if (checkParam.getCheckName().equals("checkKafkaService")) {                Producer<String, String> producer;                String url = checkParam.getUrl();                String keySerializer = checkParam.getKeySerializer();                String valueSerializer = checkParam.getValueSerializer();                try {                    Properties props = new Properties();                    props.put("metadata.broker.list", url);                    props.put("key.serializer.class", keySerializer);                    props.put("serializer.class", valueSerializer);                    producer = new Producer<String, String>(new ProducerConfig(props));                    producer.send(new KeyedMessage<String, String>(BaseConstant.KAFKA_CHECK_TOPIC,                            BaseConstant.KAFKA_CHECK_TEST ,BaseConstant.KAFKA_CHECK_TEST));                    logger.info("Kafka连接成功");                    retMap.put(BaseConstant.RET_KEY, 1);                    retMap.put(BaseConstant.RET_DESC, "Kafka连接成功,metadata.broker.list:" + url);                    retList.add(retMap);                } catch (Exception e) {                    logger.error("Kafka连接失败", e);                    retMap.put(BaseConstant.RET_KEY, 0);                    retMap.put(BaseConstant.RET_DESC, "Kafka连接失败,metadata.broker.list: " + url);                    retList.add(retMap);                }            }        }        return retList;    }}


package com.xxx.ad.core.service;import com.google.common.base.CaseFormat;import com.google.common.collect.Lists;import com.google.common.collect.Maps;import com.xxx.ad.core.dto.CheckParam;import com.xxx.ad.core.service.check.ICheckService;import com.xxx.ad.core.util.CollectionUtil;import com.xxx.ad.core.util.SpringContextUtil;import com.xxx.ad.core.util.StringUtil;import java.util.List;import java.util.Map;public class CheckMiddlewareService {    private List<CheckParam> reqList;    private SpringContextUtil springContextUtil;    public List<CheckParam> getReqList() {        return reqList;    }    public void setReqList(List<CheckParam> reqList) {        this.reqList = reqList;    }    public SpringContextUtil getSpringContextUtil() {        return springContextUtil;    }    public void setSpringContextUtil(SpringContextUtil springContextUtil) {        this.springContextUtil = springContextUtil;    }    /**     * 中间件连接状态查询     *     * @return retMap 查询结果     */    public Map<String, Object> runCheck() throws Exception {        Map<String, Object> retMap = Maps.newHashMap();        Map<String, ICheckService> result = springContextUtil.getApplicationContext().getBeansOfType(ICheckService.class);        for (Map.Entry<String, ICheckService> entry: result.entrySet()) {            String key = StringUtil.CaseFormat(entry.getKey(), CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_CAMEL);            retMap.put(key, entry.getValue().checkMiddlewareStatus(getParam(key)));        }        return retMap;    }    /**     * 获取各中间件服务对应的参数     *     * @param key 实现类名称     * @return paramList     */    private List<CheckParam> getParam(String key) {        List<CheckParam> paramList = Lists.newArrayList();        if (!CollectionUtil.isEmpty(reqList)) {            for (CheckParam checkParam : reqList) {                if (checkParam.getCheckName().equals(key)) {                    paramList.add(checkParam);                }            }        }        return paramList;    }}



实现后,在应用的项目中引用jar包,spring配置文件中配置信息如下:

<bean id="checkMiddlewareService" class="com.xxx.ad.core.service.CheckMiddlewareService">    <property name="springContextUtil" ref="springContextUtil"/>    <property name="reqList">        <list>            <ref bean="checkMysql"/>            <ref bean="checkRedis"/>            <ref bean="checkKafka"/>        </list>    </property></bean><bean id="springContextUtil" class="com.xxx.ad.core.util.SpringContextUtil"/><bean id="checkMysql" class="com.xxx.ad.core.dto.CheckParam">    <property name="checkName" value="checkMysqlService"/>    <property name="url" value="${product.jdbcUrl}"/>    <property name="user" value="${product.username}"/>    <property name="password" value="${product.password}"/>    <property name="databaseDriver" value="${product.driverClass}"/></bean><bean id="checkRedis" class="com.xxx.ad.core.dto.CheckParam">    <property name="checkName" value="checkRedisService"/>    <property name="url" value="${redis.host}"/>    <property name="port" value="${redis.port}"/>    <property name="password" value="${redis.pass}"/></bean><bean id="checkKafka" class="com.xxx.ad.core.dto.CheckParam">    <property name="checkName" value="checkKafkaService"/>    <property name="url" value="${kafka.client.send.broker-list}"/>    <property name="keySerializer" value="kafka.serializer.StringEncoder"/>    <property name="valueSerializer" value="kafka.serializer.StringEncoder"/></bean>


通过接口调用一下测试:

@AutowiredCheckMiddlewareService checkMiddlewareService;/** * * @param response * @param request * @return */@RequestMapping(value = "/check", method = RequestMethod.GET)@ResponseBodypublic Map<String, Object> check(HttpServletResponse response, HttpServletRequest request) {    Map<String, Object> retMap = Maps.newHashMap();    try {        retMap = checkMiddlewareService.runCheck();    } catch (Exception e) {        retMap.put(OnlineConstant.ERR_CODE_KEY, "1200");        retMap.put(OnlineConstant.ERR_MESSAGE_KEY, Configure.getInstance().getPropertyValue("1200"));        logger.error("检测中间件接口异常", e);    }    return retMap;}


原创粉丝点击