`
geeksun
  • 浏览: 952908 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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;
    }
}

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics