Java程序健康检查,查看相关Bean对象是否存在、各种服务是否正常运行

本代码的目的用于Java程序健康检查,放到项目中可以查看相关Bean对象是否存在、各种服务是否正常运行

上接上代码,这个需要自己测试,或是压测,本人从公司项目中扒下来的

import java.util.List;

/**
 * Bean健康检查接口

*/

public interface IBeanHealthChecker {

    /**
     * 检查checker内部定义bean
     * @return
     */
    public GroupHealthStatus check();

    /**
     * 依次检查多个bean
     * @param groupBeansPairs
     * @return
     */
    public List check(GroupBeansPair ... groupBeansPairs);
}


import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Bean健康状态抽象基类
 */
public abstract class BaseBeanHealthChecker implements IBeanHealthChecker {

    private static final Logger logger = LoggerFactory.getLogger(BaseBeanHealthChecker.class);

    @Override
    public GroupHealthStatus check() {
        return check(getGroupBeansPairs());
    }

    @Override
    public List check(GroupBeansPair ... groupBeansPairs) {
        if (groupBeansPairs == null || groupBeansPairs.length == 0) {
            if (logger.isErrorEnabled()) {
                logger.error("分组bean参数为空,无法进行bean健康检查");
            }
            return null;
        }
        List groupHealthStatuses = new ArrayList();
        for (GroupBeansPair groupBean : groupBeansPairs) {
            GroupHealthStatus groupBeansPair = check(groupBean);
            if (groupBeansPair != null) {
                groupHealthStatuses.add(groupBeansPair);
            }
        }
        return groupHealthStatuses;
    }

    private GroupHealthStatus check(GroupBeansPair groupBeansPair) {
        if (groupBeansPair == null) {
            if (logger.isErrorEnabled()) {
                logger.error("分组bean参数为空,无法进行bean健康检查");
            }
            return null;
        }
        if (groupBeansPair.getBeanNames() == null || groupBeansPair.getBeanNames().length == 0) {
            if (logger.isErrorEnabled()) {
                logger.error("bean列表参数为空,无法进行bean健康检查");
            }
            return null;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("开始对分组:" + groupBeansPair.getGroup() + "进行健康检查");
        }

        GroupHealthStatus groupHealthStatus = new GroupHealthStatus();
        groupHealthStatus.setGroup(groupBeansPair.getGroup());
        groupHealthStatus.setRight(true);
        List statuses = new ArrayList();
        groupHealthStatus.setBeanHealthStatusList(statuses);

        for (String beanName : groupBeansPair.getBeanNames()) {
            BeanHealthStatus status = new BeanHealthStatus();
            status.setGroup(groupBeansPair.getGroup());
            status.setBean(beanName);
            Object obj = checkBeanInContainer(beanName);
            if (obj == null) {
                status.setRight(false);
                status.setStatus(BeanHealthStatus.HEALTH_STATUS_BEAN_NOT_FOUND);
                status.setDesc(BeanHealthStatus.HEALTH_STATUS_BEAN_NOT_FOUND_DESC);
            } else {
                status.setRight(true);
                status.setStatus(BeanHealthStatus.HEALTH_STATUS_NORMAL);
                status.setDesc(BeanHealthStatus.HEALTH_STATUS_NORMAL_DESC);
            }
            if (logger.isDebugEnabled()) {
                StringBuilder bf = new StringBuilder("通过容器对bean进行健康检查");
                bf.append(status.isRight()?"成功":"失败");
                bf.append(",服务名称:").append(beanName).append(",状态:" + status.getStatus() + ",状态描述:" + status.getDesc());
                logger.debug(bf.toString());
            }
            if (status.isRight()) {
                checkBeanByMethod(obj , status);
            }
            if (!status.isRight()) {
                groupHealthStatus.setRight(false);
            }
            statuses.add(status);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("分组" + groupBeansPair.getGroup() + "检查状态结果:" + (groupHealthStatus.isRight()?"成功":"失败"));
        }
        return groupHealthStatus;
    }

    /**
     * 检查Bean在容器中是否存在
     * @return
     */
    private Object checkBeanInContainer(String beanName) {
        if (logger.isDebugEnabled()) {
            logger.debug("通过容器对Bean进行健康检查,beanName:" + beanName);
        }
        return FactoryBeanUtils.getBean(beanName);
    }

    /**
     * 通过方法校验Bean是否正常
     */
    private void checkBeanByMethod(Object bean , BeanHealthStatus status ) {
        //TODO 通过调用 bean的方法校验bean是否正常
        return;
    }

    /**
     * 获取分组与bean的配对列表
     * @return
     */
    public GroupBeansPair getGroupBeansPairs() {
        return null;
    }

}
/**
 * Bean健康状态
 */
public class BeanHealthStatus {

    /**
     * 正常状态
     */
    public static final String HEALTH_STATUS_NORMAL = "0";

    /**
     * 正常状态描述
     */
    public static final String HEALTH_STATUS_NORMAL_DESC = "正常状态";

    /**
     * bean未获取到,容器中没有该bean,表明该bean初始化失败
     */
    public static final String HEALTH_STATUS_BEAN_NOT_FOUND = "1";

    /**
     * bean未找到描述
     */
    public static final String HEALTH_STATUS_BEAN_NOT_FOUND_DESC = "bean未获取到,容器中没有该bean,表明该bean初始化失败";

    /**
     * 调用相应bean的check逻辑失败
     */
    public static final String HEALTH_STATUS_BEAN_CHECK_ERROR = "2";

    /**
     * 调用bean check逻辑失败描述
     */
    public static final String HEALTH_STATUS_BEAN_CHECK_ERROR_DESC = "调用相应bean的check逻辑失败";

    /**
     * 分组
     */
    private String group;

    /**
     * 当前是否正常
     */
    private boolean right;

    /**
     * 当前bean名称
     */
    private String bean;

    /**
     * 当前状态
     */
    private String status;

    /**
     * 当前的状态描述
     */
    private String desc;

    public String getBean() {
        return bean;
    }

    public void setBean(String bean) {
        this.bean = bean;
    }

    public boolean isRight() {
        return right;
    }

    public void setRight(boolean right) {
        this.right = right;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }
}

/**
 * 组与bean的匹配
 */
public class GroupBeansPair {

    public GroupBeansPair(String group, String[] beanNames) {
        this.group = group;
        this.beanNames = beanNames;
    }

    private String group;

    private String[] beanNames;

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

    public String[] getBeanNames() {
        return beanNames;
    }

    public void setBeanNames(String[] beanNames) {
        this.beanNames = beanNames;
    }
}

import java.util.List;

/**
 * 属性类
 */
public class GroupHealthStatus {
    private String group;

    private boolean right;

    private List beanHealthStatusList;

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

    public List getBeanHealthStatusList() {
        return beanHealthStatusList;
    }

    public void setBeanHealthStatusList(List beanHealthStatusList) {
        this.beanHealthStatusList = beanHealthStatusList;
    }

    public boolean isRight() {
        return right;
    }

    public void setRight(boolean right) {
        this.right = right;
    }
}

/**
 * 某个的健康检查
 * 例如 DAO健康检查
 */
public class BeanHealthCheckerForDAO extends BaseBeanHealthChecker {
    /**
     * 获取分组与bean的配对列表
     * @return

     *new String[]里填的是spring bean
     */
    public GroupBeansPair getGroupBeansPairs() {
        return new GroupBeansPair("数据访问层" , new String[]{
                "baseDAO",
                "baseJdbcDAO",
                "commonDAO",
                "namedSqlDAO",
                "qoDAO"
        });
    }
}

/**
 * 例如 :健康检查数据访问job 
 * 
 */
public class HealthCheckerForDAOJob {
	private static  final Logger logger = LoggerFactory.getLogger(HealthCheckerForDAOJob.class);

	public void execute() throws Exception {
		try {
		    logger.debug("健康检查 数据访问job 开始"); 
		    IBeanHealthChecker healthCache = new BeanHealthCheckerForDAO();
		    GroupHealthStatus status=healthCache.check();
		    boolean statu=status.isRight();
		
		    logger.info("健康检查  数据访问job  的状态="+statu);

		    if(statu){
		    	logger.info("健康检查  数据访问job 很健康!");
		    }else{
		    	logger.info("健康检查  数据访问job 不健康!");
		    }
	    	logger.debug("健康检查  数据访问job 结束");
	    } catch (Exception e) {
		    logger.error("健康检查  数据访问job 出错",e);
		    throw new Exception("健康检查  数据访问 job出错",e);
	    }
	}
} 

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

/**
 * 获取Spring容器中的Bean工具类
  * 类的名称上增加@Component注解,这样spring初始化的时候才能把这个类纳入到IOC容器,然后就可以在任意地方使用这个工具类了
 * @author Administrator
 *
 */
@Component
public class FactoryBeanUtils extends SpringBeanAutowiringSupport {
	
	/**
	 * 适用用于Web项目的Spring容器获取
	 */
	private static ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
	 
    
    /**
     * 根据bean名称获取
     * 内部是通过上下文件加载器获取Bean
     * 
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return ctx.getBean(name);
    }
    
    /** 
     * 根据bean的名称获取相应类型的对象,使用泛型,获得结果后,不需要强制转换为相应的类型 
     * 内部是通过上下文件加载器获取Bean
     * 
     * 
     * @param clazz bean的类型,使用泛型 
     * @return T类型的对象 
     */  
    public static  T getBeanGenerics(Class clazz) {    
        T bean = ctx.getBean(clazz);  
        return bean;  
    }
    
    /** 
     * 根据bean的类型获取相应类型的对象,没有使用泛型,获得结果后,需要强制转换为相应的类型 
     * 内部是通过上下文件加载器获取Bean
     * 
     * 
     * @param clazz bean的类型,没有使用泛型 
     * @return Object类型的对象 
     */  
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object getBean(Class clazz) {    
        Object bean = ctx.getBean(clazz);  
        return bean;  
    }  
 
} 

获取Spring Bean工具类或使用下面代码也可以

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; 

/**  
 *  
 * 获取spring容器,以访问容器中定义的其他bean 
 * 类的名称上增加@Component注解,这样spring初始化的时候才能把这个类纳入到IOC容器,然后就可以在任意地方使用这个工具类了
 * @author  
 */

@Component
public class SpringContextUtil implements ApplicationContextAware {  
  
    // Spring应用上下文环境  
    private static ApplicationContext ctx;  
  
    /** 
     * 实现ApplicationContextAware接口的回调方法,设置上下文环境 
     *  
     * @param applicationContext 
     */  
    public void setApplicationContext(ApplicationContext applicationContext) {  
        SpringContextUtil.ctx = applicationContext;  
    }  
  
    /** 
     * @return ApplicationContext 
     */  
    public static ApplicationContext getApplicationContext() {  
        return ctx;  
    }  
  

    /**
     * 根据bean名称获取
     * 内部是通过上下文件加载器获取Bean
     * 
     * @param name
     * @return
     */
    public static Object getBean(String name) { 
        return ctx.getBean(name);
    }
    
    /** 
     * 根据bean的名称获取相应类型的对象,使用泛型,获得结果后,不需要强制转换为相应的类型 
     * 内部是通过上下文件加载器获取Bean
     * 
     * 
     * @param clazz bean的类型,使用泛型 
     * @return T类型的对象 
     */  
    public static  T getBeanGenerics(Class clazz) {    
        T bean = ctx.getBean(clazz);  
        return bean;  
    }
    
    /** 
     * 根据bean的类型获取相应类型的对象,没有使用泛型,获得结果后,需要强制转换为相应的类型 
     * 内部是通过上下文件加载器获取Bean
     * 
     * 
     * @param clazz bean的类型,没有使用泛型 
     * @return Object类型的对象 
     */  
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object getBean(Class clazz) {    
        Object bean = ctx.getBean(clazz);  
        return bean;  
    }  
  
}  


你可能感兴趣的:(java)