JDBCUtil工具类
/** * 数据库连接池druid的工具类 * druid的配置文件里的键名是否可以乱取 -- 最好别,以driverClassName,url,username,password就好了 * druid:方便开发,资源更好利用 * 获取数据库druid的数据源对象DataSource的方法是通过静态工厂DruidDataSourceFactory * DataSource ds=DruidDataSourceFactory.createDataSource(pro); * 个人认为druid里拿到connecttion对象很重要 */ public class JDBCUtils { private static DataSource ds; static { try { //1.加载配置文件 Properties pro=new Properties(); InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(is); //2.初始化druid数据库连接池对象 ds = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) { e.printStackTrace(); } } //1.获取数据源 public static DataSource getDataSource(){ return ds; } //2.获取数据库连接 public static Connection getConnection() throws SQLException { return ds.getConnection(); } public void close(Connection conn, PreparedStatement pstmt){ if (pstmt!=null){ try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public void close(Connection conn, PreparedStatement pstmt, ResultSet rs){ close(conn,pstmt); if (rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } //只是测试下而已 @Test public void test(){ Properties pro=new Properties(); InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); String path = JDBCUtils.class.getClassLoader().getResource("druid.properties").getPath(); System.out.println(path); System.out.println(is); } }
jdbc.properties
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/heima?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai username=root password= # 初始化连接数量 initialSize=5 # 最大连接数 maxActive=10 # 最大等待时间 maxWait=3000
jedisUtil
public class JedisPoolUtils { //工具类主要都是获取Jedis private static JedisPool jedisPool; static { //读取配置文件 InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties"); //创建Properties对象 Properties pro=new Properties(); try { //关联文件 pro.load(is); } catch (IOException e) { e.printStackTrace(); } //获取数据,设置到JedisPoolConfig中 JedisPoolConfig config=new JedisPoolConfig(); //总数 config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal"))); //最大连接数 config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle"))); //初始化JedisPool jedisPool = new JedisPool(pro.getProperty("host"),Integer.parseInt(pro.getProperty("port"))); } public static Jedis getJedis(){ return jedisPool.getResource(); } }
jedis.properties
host=127.0.0.1
port=6379
maxTotal=50
maxIdle=10