Spring 初始化2次的问题

在Spring的使用中,有时初始化一些公共类,比如数据源、常量配置等,这些方法会执行两次,导致程序执行出现异常。

 

一个解决方法是利用Spring的事件机制,事件机制需要实现ApplicationListener监听器,只要编写一个实现类实现该接口的onApplicationEvent方法,在方法体中初始化应用需要的初始化数据,并做防二次初始化的处理。

 

此处是一个jedis工厂类的代码:

public class JedisFactory implements ApplicationListener<ApplicationEvent> {  
    private static Logger logger = LogHelper.LOG_CollectDataService;  
  
    private static JedisPoolConfig jedisPoolConfig;  
  
    private static JedisPool jedisPool;  
  
    private static boolean isStart = false;  
  
    @Value("${redis.maxActive}")  
    private String maxActive;  
  
    @Value("${redis.maxIdle}")  
    private String maxIdle;  
  
    @Value("${redis.maxWait}")  
    private String maxWait;  
  
    @Value("${redis.ip}")  
    private String host;  
  
    @Value("${redis.port}")  
    private String port;  
  
    @Override  
    public void onApplicationEvent(ApplicationEvent event) {  
        if (!isStart) {  
            isStart = true;  
  
            try {  
                jedisPoolConfig = new JedisPoolConfig();  
  
                // 最大连接数  
                jedisPoolConfig.setMaxActive(Integer.parseInt(maxActive));  
                // 最大空闲连接数  
                jedisPoolConfig.setMaxIdle(Integer.parseInt(maxIdle));  
                // 获取连接最大等待时间  
                jedisPoolConfig.setMaxWait(Integer.parseInt(maxWait));  
                // 设置获取连接前是否进行连接测试  
                jedisPoolConfig.setTestOnBorrow(true);  
  
                jedisPool = new JedisPool(jedisPoolConfig, host, Integer.parseInt(port));  
  
                logger.info("JedisPool 已初始化, ", JSON.toJSONString(jedisPool));  
            } catch (Exception e) {  
                logger.error("JedisPool 初始化异常", e);  
            }  
        }  
    }  
  
    public static Jedis getJedis() {  
        Jedis jedis = null;  
        try {  
            logger.info("jedisPool = ", jedisPool.toString());  
            jedis = jedisPool.getResource();  
            return jedis;  
        } catch (Exception e) {  
            logger.error("获取Jedis实例异常", e);  
            jedisPool.returnBrokenResource(jedis);  
            return null;  
        }  
    }  
  
    /** 
     * 将jedis对象释放回连接池中 
     * 
     * @param jedis 使用完毕的Jedis对象 
     * @return true 释放成功;否则返回false 
     */  
    public static boolean release(Jedis jedis) {  
        if (jedis != null) {  
            jedisPool.returnResource(jedis);  
            return true;  
        }  
  
        return false;  
    }  
}

获取【下载地址】 【新技术】现在最流行的java后台框架组合java springmvc mybaits mysql oracle html5 后台框架源码

转载于:https://my.oschina.net/u/2523543/blog/531430

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值