Java開發常用的工具類

一、Druid數據庫連接池工具類和配置文件

Druid數據庫連接池工具類

import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCDruidUtil {
    //1、定義成員變量
    private static DataSource ds;

    static{
        //加載配置文件
        Properties pro = new Properties();
        try {
            pro.load(JDBCDruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            try {
                ds= DruidDataSourceFactory.createDataSource(pro);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //獲取連接
    public static Connection getCon() throws SQLException {
        return ds.getConnection();
    }

    //釋放資源
    public static void close(Statement stmt,Connection con){
       close(null,stmt,con);
    }

    //釋放資源
    public static void close(ResultSet rs,Statement stmt, Connection con){
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con!=null){
            try {
                con.close();  //歸還連接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs!=null){
            try {
                rs.close();  //歸還連接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //獲取連接池方法
    public static DataSource getDataSource(){
        return ds;
    }
}

druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_diary
username=root
password=123456
initialSize=5
maxActive=10
maxWait=3000

二、Jedis工具類和配置文件

(注意當存取數據完畢時要歸還連接 否則當最大連接數用完後會無法獲取數據)

jedis.close(); //歸還連接

Jedis連接池工具類

public class JedisPoolUtils {
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(config,pro.getProperty("host"),Integer.parseInt(pro.getProperty("port")));
}
/**
* 獲取連接方法
*/
public static Jedis getJedis(){
return jedisPool.getResource();
}
}

jedis.properties詳細配置文件

#最大活動對象數     
redis.pool.maxTotal=1000    
#最大能夠保持idle狀態的對象數      
redis.pool.maxIdle=100  
#最小能夠保持idle狀態的對象數   
redis.pool.minIdle=50    
#當池內沒有返回對象時,最大等待時間    
redis.pool.maxWaitMillis=10000    
#當調用borrow Object方法時,是否進行有效性檢查    
redis.pool.testOnBorrow=true    
#當調用return Object方法時,是否進行有效性檢查    
redis.pool.testOnReturn=true  
#“空閒鏈接”檢測線程,檢測的週期,毫秒數。如果爲負值,表示不運行“檢測線程”。默認爲-1.  
redis.pool.timeBetweenEvictionRunsMillis=30000  
#向調用者輸出“鏈接”對象時,是否檢測它的空閒超時;  
redis.pool.testWhileIdle=true  
# 對於“空閒鏈接”檢測線程而言,每次檢測的鏈接資源的個數。默認爲3.  
redis.pool.numTestsPerEvictionRun=50  
#redis服務器的IP    
redis.ip=xxxxxx  
#redis服務器的Port    
redis1.port=6379   

三、發郵件工具類

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 發郵件工具類
 */
public final class MailUtils {
    private static final String USER = "qq郵箱"; // 郵箱地址
    private static final String PASSWORD = "";  //  客戶端授權碼

    /**
     *
     * @param to 收件人郵箱
     * @param text 郵件正文
     * @param title 標題
     */
    /* 發送驗證信息的郵件 */
    public static boolean sendMail(String to, String text, String title){
        try {
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.qq.com");
            props.setProperty("mail.smtp.port", "587");

//如果是163郵箱 只需要設置   不需要設置端口 使用默認端口即可
// props.put("mail.smtp.host", "smtp.163.com"); 

            // 發件人的賬號
            props.put("mail.user", USER);
            //發件人的密碼
            props.put("mail.password", PASSWORD);

            // 構建授權信息,用於進行SMTP進行身份驗證
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用戶名、密碼
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用環境屬性和授權信息,創建郵件會話
            Session mailSession = Session.getInstance(props, authenticator);
            // 創建郵件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 設置發件人
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // 設置收件人
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 設置郵件標題
            message.setSubject(title);

            // 設置郵件的內容體
            message.setContent(text, "text/html;charset=UTF-8");
            // 發送郵件
            Transport.send(message);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }


//測試
    public static void main(String[] args) throws Exception { // 做測試用
        MailUtils.sendMail("要發送到的郵箱","你好,這是一封測試郵件,無需回覆。","測試郵件");
        System.out.println("發送成功");
    }
}

四、MD5加密工具類

import java.security.MessageDigest;
import java.util.Base64;

/**
 * 作者: kinggm Email:[email protected]
 * 時間:  2020-02-26 11:01
 * MD5加密
 */
public class MD5Util {

    //MD5加密
    public static String EncoderPassword(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            Base64.Encoder encoder = Base64.getEncoder();
            return new String(encoder.encode(md5.digest(str.getBytes("utf-8"))));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

五、獲取Uuid工具類

import java.util.UUID;

/**
 * 產生UUID隨機字符串工具類
 */
public final class UuidUtil {
	private UuidUtil(){}
	public static String getUuid(){
		return UUID.randomUUID().toString().replace("-","");
	}
	/**
	 * 測試
	 */
	public static void main(String[] args) {
		System.out.println(UuidUtil.getUuid());
		System.out.println(UuidUtil.getUuid());
	}
}

六、生成隨機驗證碼圖片工具類

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;

public class IdentifyCode {
    // 圖片的寬度。
    private int width = 160;
    // 圖片的高度。
    private int height = 40;
    // 驗證碼字符個數
    private int codeCount = 4;
    // 驗證碼干擾線數
    private int lineCount = 20;
    // 驗證碼
    private String code = null;
    // 驗證碼圖片Buffer
    private BufferedImage buffImg = null;
    Random random = new Random();

    // 生成默認定義的圖片
    public IdentifyCode() {
        creatImage();
    }

    // 自定義圖片寬和高
    public IdentifyCode(int width, int height) {
        this.width = width;
        this.height = height;
        creatImage();
    }

    // 自定義圖片寬、高和字符個數
    public IdentifyCode(int width, int height, int codeCount) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        creatImage();
    }

    // 自定義寬、高、字符個數和干擾線條數
    public IdentifyCode(int width, int height, int codeCount, int lineCount) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        this.lineCount = lineCount;
        creatImage();
    }

    // 生成圖片
    private void creatImage() {
        int fontWidth = width / codeCount;// 字體的寬度
        int fontHeight = height - 5;// 字體的高度
        int codeY = height - 8;

        // 圖像buffer
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = buffImg.getGraphics();
        // Graphics2D g = buffImg.createGraphics();
        // 設置背景色
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);

        // 設置字體
        // Font font1 = getFont(fontHeight);
        Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
        g.setFont(font);

        // 設置干擾線
        for (int i = 0; i < lineCount; i++) {
            int xs = random.nextInt(width);
            int ys = random.nextInt(height);
            int xe = xs + random.nextInt(width);
            int ye = ys + random.nextInt(height);
            g.setColor(getRandColor(1, 255));
            g.drawLine(xs, ys, xe, ye);
        }

        // 添加噪點
        float yawpRate = 0.01f;// 噪聲率
        int area = (int) (yawpRate * width * height);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);

            buffImg.setRGB(x, y, random.nextInt(255));
        }

        String str1 = randomStr(codeCount);// 得到隨機字符
        this.code = str1;
        for (int i = 0; i < codeCount; i++) {
            String strRand = str1.substring(i, i + 1);
            g.setColor(getRandColor(1, 255));
            // g.drawString(a,x,y);
            // a爲要畫出來的東西,x和y表示要畫的東西最左側字符的基線位於此圖形上下文座標系的 (x, y) 位置處

            g.drawString(strRand, i * fontWidth + 3, codeY);
        }

    }

    // 得到隨機字符
    private String randomStr(int n) {
        String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        String str2 = "";
        int len = str1.length() - 1;
        double r;
        for (int i = 0; i < n; i++) {
            r = (Math.random()) * len;
            str2 = str2 + str1.charAt((int) r);
        }
        return str2;
    }

    // 得到隨機顏色
    private Color getRandColor(int fc, int bc) {// 給定範圍獲得隨機顏色
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    /**
     * 產生隨機字體
     */
    private Font getFont(int size) {
        Random random = new Random();
        Font font[] = new Font[5];
        font[0] = new Font("Ravie", Font.PLAIN, size);
        font[1] = new Font("Antique Olive Compact", Font.PLAIN, size);
        font[2] = new Font("Fixedsys", Font.PLAIN, size);
        font[3] = new Font("Wide Latin", Font.PLAIN, size);
        font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, size);
        return font[random.nextInt(5)];
    }

    // 扭曲方法
    private void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }

        }

    }

    public void write(OutputStream sos) throws IOException {
        ImageIO.write(buffImg, "png", sos);
        sos.close();
    }

    public BufferedImage getBuffImg() {
        return buffImg;
    }

    public String getCode() {
        return code.toLowerCase();
    }

}


七、properties工具類(properties文件必須放在src根目錄下)

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

public class PropertistisUtil {
    static Properties pro = new Properties();

    public static String getValue(String fileName, String key) {  // 傳入文件名 和key
        try {
            pro.load(PropertistisUtil.class.getClassLoader().getResourceAsStream(fileName));
        } catch (IOException e) {
//            寫日誌
        }
        //通過key 獲取value
        return pro.getProperty(key);
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章