Java教程

工具类

本文主要是介绍工具类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

ConfigLoader

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

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigLoader {
    //1. 创建日志标记器
    private static Logger logger = LoggerFactory.getLogger(ConfigLoader.class);

    //2. 创建配置对象
    static Properties props = new Properties();

    //3. 读取配置文件《conf.properties》转化成输入流,配置对象加载输入流
    static {
        InputStream resourceAsStream = ConfigLoader.class
                .getClassLoader()
                .getResourceAsStream("conf.properties");
        try {
            props.load(resourceAsStream);
        } catch (IOException e) {
            logger.warn("当前加载配置文件出错:" + e.getMessage());
        }
    }

    //4. 定义get获取对象,类型:字符串或整数
    //-- 获取字符串
    public static String getString(String key) {
        String property = props.getProperty(key);
        return property;
    }
    //-- 获取数字类型的值
    public static int getInt(String key) {
        return Integer.parseInt(props.getProperty(key));
    }
}

DateUtil

import pers.aishuang.flink.streaming.entity.DateFormatDefine;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 时间的转换工具
 * 格式化成日期,转换成字符串
 * yyyy-MM-dd HH:mm:ss
 * yyyyMMdd
 * yyyy-MM-dd
 */
public class DateUtil {


    /**
     * TODO 1、直接获得当前日期,格式:“yyyy-MM-dd HH:mm:ss”
     * @return
     */
    public static String getCurrentDateTime(){
        return new SimpleDateFormat(DateFormatDefine.DATE_TIME_FORMAT.getFormat()).format(new Date());
    }

    /**
     * TODO 2、直接获得当前日期,格式:”yyyyMMdd”
     * @return
     */
    public static String getCurrentDate(){
        return new SimpleDateFormat(DateFormatDefine.DATE_FORMAT.getFormat()).format(new Date());
    }
    /**
     * TODO 3、字符串日期格式转换,传入参数格式:“yyyyMMdd”,转成Date类型
     * @param str
     * @return
     */
    public static Date convertStringToDate(String str) {
        Date date = null;
        try {
            //注意SimpleDateFormat是线程非安全的,因此使用的时候必须要每次创建一个新的实例才可以
            SimpleDateFormat formatter = new SimpleDateFormat(DateFormatDefine.DATE_FORMAT.getFormat());
            date = formatter.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * TODO 4、字符串日期格式转换,传入参数格式:“yyyy-MM-dd”,转成Date类型
     * @param str
     * @return
     */
    public static Date convertDateStrToDate(String str){
        Date date = null;
        try {
            //注意:SimpleDateFormat是线程非安全的,因此使用的时候每次都必须要创建一个实例
            SimpleDateFormat format = new SimpleDateFormat(DateFormatDefine.DATE2_FORMAT.getFormat());
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * TODO 5、字符串日期格式转换,传入参数格式:“yyyy-MM-dd HH:mm:ss”,转成Date类型
     * @param str
     * @return
     */
    public static Date convertStringToDateTime(String str){
        Date date = null;
        try {
            //注意SimpleDateFormat是线程非安全的,因此使用的时候必须要每次创建一个新的实例才可以
            date = new SimpleDateFormat(DateFormatDefine.DATE_TIME_FORMAT.getFormat()).parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * TODO 6、字符串日期格式转换,传入参数格式:”yyyy-MM-dd HH:mm:ss“,转成”yyyyMMdd”格式
     * @param str
     * @return
     */
    public static String convertStringToDateString(String str){
        String dateStr = null;
        //第一步:先将日期字符串转换成日期对象
        Date date = convertStringToDateTime(str);
        //第二步:再将日期对象转换成指定的日期字符串
        dateStr = new SimpleDateFormat(DateFormatDefine.DATE_FORMAT.getFormat()).format(date);
        return dateStr;
    }
}

JDBCUtil

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JDBCUtil {
    // 建立数据库连接池
    private static Connection connection = null;
    private static PreparedStatement ps = null;

    static {
        try {
            String jdbcDriver = ConfigLoader.getString("jdbc.driver");
            String url = ConfigLoader.getString("jdbc.url");
            String user = ConfigLoader.getString("jdbc.user");
            String pwd = ConfigLoader.getString("jdbc.password");
            Class.forName(jdbcDriver);
            connection = DriverManager.getConnection(url, user, pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @desc 批量执行sql
     * @param sql
     * @param paramsList
     * @return 批处理行数
     */
    public static int[] executeBatch(String sql, List<ArrayList<Object>> paramsList) throws SQLException {
        int[] rows = null;
        ps = connection.prepareStatement(sql);
        connection.setAutoCommit(false);
        try {
            int countRow = 0;
            if (!paramsList.isEmpty()) {
                for (ArrayList params:paramsList) {
                    for (int i = 0;i < params.size(); i++) {
                        ps.setObject(i + 1, params.get(i));
                    }
                    ps.addBatch();
                    countRow += 1;
                    if (countRow > 0 && countRow % 1000 == 0) {
                        ps.executeBatch();
                        ps.clearBatch();
                        connection.commit();
                    }
                }
                rows = ps.executeBatch();
                ps.clearBatch();
                connection.commit();
            }
            close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rows;
    }

    /**
     * @desc:单条执行sql
     * @param sql
     * @param params
     */
    public static void executeInsert(String sql, ArrayList<Object> params) throws SQLException {
        ps = connection.prepareStatement(sql);
        connection.setAutoCommit(false);
        try {
            for (int i = 0; i < params.size(); i++) {
                ps.setObject(i + 1, params.get(i));
            }
            ps.execute();
            connection.commit();
            close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * @desc 关闭连接
     * @throws SQLException
     */
    public static void close() throws SQLException {
        if (ps != null) {
            ps.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

}

PhoenixJDBCUtil

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class PhoenixJDBCUtil {

    private static Connection conn = null;
    private static ResultSet rs = null;
    private static Statement statement = null;
    private static PreparedStatement ps = null;

    static {

        try {
            Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");

            conn = DriverManager.getConnection("jdbc:phoenix:node01,node02,node03:2181");
            statement = conn.createStatement();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void createSchema(String createSchemaName) throws SQLException {
        statement.executeUpdate(createSchemaName);
        conn.commit();
        close();
    }

    /**
     * @desc:创建表
     * @param createSql
     * @throws SQLException
     */
    public static void create(String createSql) throws SQLException {
        statement.executeUpdate(createSql);
        // 必须提交
        conn.commit();
        close();
    }

    /**
     * @desc:插入记录
     *  upsert into user(id, name, passwd) values(?, ?, ?)
     *  {"1", "张三", "111111"}
     * @param upsertSql
     */
    public static void  upsert(String upsertSql, String[] params) throws SQLException {
        ps = conn.prepareStatement(upsertSql);
        for (int i = 1; i <= params.length; i++) {
            ps.setString(i, params[i - 1]);
        }
        ps.executeUpdate();
        // 必须提交
        conn.commit();
        close();
    }

    /**
     * @desc 查询数据
     * @param querySql
     * @return
     */
    public static List<String[]> select(String querySql) throws SQLException {
        List<String[]> result = new ArrayList<>();
        rs = statement.executeQuery(querySql);
        ResultSetMetaData meta = rs.getMetaData();
        int colLength = meta.getColumnCount();
        List<String> colName = new ArrayList<>();
        for (int i = 1; i <= colLength; i++) {
            colName.add(meta.getColumnName(i));
        }

        String[] colArr;
        while (rs.next()) {
            colArr = new String[colLength];
            for (int i = 0; i < colLength; i++) {
                colArr[i] = rs.getString(colName.get(i));
            }
            result.add(colArr);
        }
        close();
        return result;
    }

    /**
     * @desc 批量插入数据
     * @param upsertSql
     * @param paramList
     */
    public static void  upsertBatch(String upsertSql, ArrayList<String[]> paramList) throws SQLException {
        ps = conn.prepareStatement(upsertSql);
        conn.setAutoCommit(false);
        paramList.forEach(params -> {
            try {
                for (int i = 0; i < params.length; i++) {
                    ps.setString(i+1, params[i]);
                }
                ps.addBatch();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });
        ps.executeBatch();
        // 必须提交
        conn.commit();
        close();
    }

    /**
     * @desc 删除
     * @param deleteSql
     * @throws SQLException
     */
    public static void delete(String deleteSql) throws SQLException {
        statement.executeUpdate(deleteSql);
        // 必须提交
        conn.commit();
        close();
    }

    /**
     * @desc:释放资源
     * @throws SQLException
     */
    public static void close() throws SQLException {
        if (rs != null) {
            rs.close();
        }
        if (statement != null){
            statement.close();
        }
        if (ps != null) {
            ps.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}

RedisUtil

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.util.Pool;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Redis工具类:
 */
public class RedisUtil {
    //线程池
    private static Pool<Jedis> jedisPool = null;
    //
    private static ReentrantLock lock = new ReentrantLock();
    //主机地址
    private static String HOST = ConfigLoader.getString("redis.host");
    //端口号
    private static int PORT = Integer.valueOf(ConfigLoader.getInt("reids.port"));
    //redis会话超时时间
    private static int TIMEOUT = Integer.valueOf(ConfigLoader.getInt("redis.session.timeout"));
    //redis数据库(0~49)
    private static int DATABASE = Integer.valueOf(ConfigLoader.getInt("redis.database"));
    //redis服务段密码
    private static String PASSWORD = ConfigLoader.getString("redis.password");

    /**
     * 初始化连接池
     */

    static {
        if("null".equals(PASSWORD)) PASSWORD= null;
        if(jedisPool == null) jedisPool = new JedisPool(new GenericObjectPoolConfig(), HOST, PORT, TIMEOUT, PASSWORD, DATABASE, "");
    }

    /**
     * 获得jedis客户端
     * @return jedis客户端
     */
    public static Jedis getJedis() {
        //此代码逻辑是:线程池还没创建的时候,锁住,静止访问,线程池创建完成时,在打开入口,允许访问
        //即:线程池相当于澡堂水池,而ReentrantLock相当于澡堂大门的锁
        if(jedisPool == null){
            lock.lock();//防止初始化时,多线程竞争问题
            jedisPool = new JedisPool(new GenericObjectPoolConfig(),HOST,PORT,TIMEOUT,PASSWORD,DATABASE,"");
            lock.unlock();
        }
        //从jedis线程池中获取资源:一个reids服务连接
        return jedisPool.getResource();
    }

    /**
     * 根据redis中存在的key获得value
     * @param key
     * @return value的字节数组
     */
    public static byte[] get(byte[] key) {
        //获取redis客户端:Jedis
        Jedis jedis = getJedis();
        byte[] result = "".getBytes(StandardCharsets.UTF_8);
        if(jedis.exists(key) ) {
            result = jedis.get(key);
        }
        //关闭redis客户端
        jedis.close();
        return result;
    }

    public static Boolean set(byte[] key, byte[] value, int keyTimeout) {
        try {
            Jedis jedis  = getJedis();
            jedis.setex(key, keyTimeout,value);
            jedis.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void set(byte[] key, byte[] value) {
        try {
            Jedis jedis = getJedis();
            jedis.set(key,value);
            jedis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放资源,关闭连接池
     */
    public static void releaseSource() {
        if(jedisPool != null) {
            jedisPool.close();
        }
    }

}
这篇关于工具类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!