All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yuyenews.easy.util.ConnectionUtil Maven / Gradle / Ivy

The newest version!
package com.yuyenews.easy.util;

import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

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

import com.yuyenews.core.util.ThreadUtil;
import com.yuyenews.easy.base.BaseDao;
import com.yuyenews.easy.server.constant.EasySpace;

public class ConnectionUtil {
	
	private static Logger logger = LoggerFactory.getLogger(ConnectionUtil.class);

	private static EasySpace commontSpace = EasySpace.getEasySpace();
	
	/**
	 * 获取当前线程的连接,如果没有则从baseDao拿一个
	 * @param name mingc
	 * @return lianjie
	 */
	public static Connection getConnection(String name) {
		
		try {
			Map connections =  getConnections();
			
			Connection connection = connections.get(name);
			if(connection == null) {
				connection = BaseDao.getConnection(name);
				connection.setAutoCommit(true);
			} else {
				connection.setAutoCommit(false);
			}
			
			return connection;
		} catch (Exception e) {
			logger.error("获取连接失败",e);
			return null;
		}
	}
	
	/**
	 * 获取连接缓存
	 * @return duix
	 */
	@SuppressWarnings("unchecked")
	public static Map getConnections() {

		Map connections = new HashMap<>();
		try {
			Object obj = commontSpace.getAttr(ThreadUtil.getThreadId());
			if (obj != null) {
				connections = (Map) obj;
			} else {
				commontSpace.setAttr(ThreadUtil.getThreadId(), connections);
			}
		} catch (Exception e) {
			logger.error("从缓存中获取连接对象失败", e);
		}
		return connections;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy