Java 数据服务类

package com.panda.core.db.dao;

import com.panda.core.db.impl.CacheService;
import com.panda.core.db.impl.DBService;
import com.panda.core.db.util.SerializeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.*;

/**
 * 数据服务类
 * Created by Lovell on 16/6/20.
 */
public class Dao {
    private static Logger logger = LoggerFactory.getLogger(Dao.class);

    private DBService dbService;

    public Dao() {
        this.dbService = new DBService();
    }

    /**
     * 设置Redis服务器配置文件路径
     *
     * @param path
     */
    public void setCacheConfigFilePathName(final String path) {
        if (path == null || path.length() == 0) {
            return;
        }
        CacheService.getInstance().setCacheConfigFilePathName(path);
    }

    /**
     * 设置MySQL服务器配置文件路径
     *
     * @param path
     */
    public void setDBConfigFilePathName(final String path) {
        if (path == null || path.length() == 0) {
            return;
        }
        dbService.setDBConfigFilePathName(path);
    }

    /**
     * 启动Redis MySQL
     */
    public void start() throws IOException, SQLException {
        dbService.start();
        CacheService.getInstance().start();
        logger.info("MySQL and Redis was started.");
    }

    /**
     * 启动Redis
     */
    public void startCache() throws IOException {
        CacheService.getInstance().start();
    }

    /**
     * 停止Redis MySQL
     */
    public void stop() throws IOException, SQLException {
        dbService.stop();
        CacheService.getInstance().stop();
        logger.info("MySQL and Redis was stopped.");
    }

    /***************************************************************************
     * Redis      ***************************************************************************/
    /**
     * 加锁
     *
     * @param key
     * @return
     */
    public boolean lockss(final String key) {
        Jedis jedis = null;
        // 通过SETNX试图获取一个lock
        boolean success = false;
        try {
            jedis = CacheService.getInstance().getJedis();
            Long value = System.currentTimeMillis() + CacheService.getInstance().getCacheLocktimeout() + 1;
            Long acquired = jedis.setnx(key, String.valueOf(value));
            if (acquired == 1) {
                // 返回1,成功获取一个锁
                success = true;
            } else {
                // 返回0,setnx失败说明锁被其他对象持有,说明锁被其他对象持有
                // 检查锁持有时间是否超时
                Long oldValule = Long.valueOf(jedis.get(key));
                if (oldValule < System.currentTimeMillis()) {
                    // 如果超时,设置value
                    String getValue = jedis.getSet(key, String.valueOf(value));
                    if (Long.valueOf(getValue) == oldValule) {
                        success = true;
                    }
                }
            }
        } finally {
            if (jedis != null) jedis.close();
        }
        return success;
    }

    public void unlockss(String key) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            String value = jedis.get(key);
            if (value != null) {
                jedis.del(key);
            } else {
                logger.info("delete lock not success");
            }
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    /***************************************************************************
     * 增删改查
     * @MySql
     ***************************************************************************/
    /**
     * 增删改
     *
     * @param sql
     * @param params
     * @return
     */
    public boolean updateByPreparedStatement(final String sql, final List<Object> params) throws SQLException {
        int result = -1;
        Connection connection = dbService.getConnection();
        PreparedStatement preparedStatement = dbService.getConnection().prepareStatement(sql);
        int index = 1;
        if (params != null && !params.isEmpty()) {
            for (Object param : params) {
                preparedStatement.setObject(index++, param);
            }
        }
        result = preparedStatement.executeUpdate();
        dbService.evictConnection(connection);
        return result > 0;
    }

    /**
     * 查询单条记录
     *
     * @param sql
     * @param params
     * @return
     */
    public Map<String, Object> selectOne(final String sql, final List<Object> params) throws SQLException {
        Map<String, Object> map = new HashMap<String, Object>();
        int index = 1;
        Connection connection = dbService.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (Object param : params) {
                preparedStatement.setObject(index++, param);
            }
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int col_len = metaData.getColumnCount();
        while (resultSet.next()) {
            for (int i = 0; i < col_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                map.put(cols_name, cols_value);
            }
        }
        try {
            resultSet.close();
            dbService.evictConnection(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 查询多条记录
     *
     * @param sql
     * @param params
     * @return
     */
    public List<Map<String, Object>> selectMulti(final String sql, final List<Object> params) throws SQLException {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        int index = 1;
        Connection connection = dbService.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (Object param : params) preparedStatement.setObject(index++, param);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int cols_len = metaData.getColumnCount();
        while (resultSet.next()) {
            Map<String, Object> map = new HashMap<String, Object>();
            for (int i = 0; i < cols_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                map.put(cols_name, cols_value);
            }
            list.add(map);
        }
        try {
            resultSet.close();
            dbService.evictConnection(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 通过反射机制实现查询单条记录
     *
     * @param sql
     * @param params
     * @param cls
     * @param <T>
     * @return
     */
    public <T> T selectOne(final String sql, final List<Object> params, final Class<T> cls) throws SQLException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        T resultObject = null;
        int index = 1;
        Connection connection = dbService.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (Object param : params) preparedStatement.setObject(index++, param);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int cols_len = metaData.getColumnCount();
        while (resultSet.next()) {
            // 通过反射机制创造一个实例
            resultObject = cls.newInstance();
            for (int i = 0; i < cols_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                Field field = cls.getDeclaredField(cols_name);
                // 打开javabean访问权限
                field.setAccessible(true);
                field.set(resultObject, cols_value);
            }
        }
        try {
            resultSet.close();
            dbService.evictConnection(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultObject;
    }

    /**
     * 通过反射机制查询多条记录
     *
     * @param sql
     * @param params
     * @param cls
     * @param <T>
     * @return
     */
    public <T> List<T> selectMulti(final String sql, final List<Object> params, final Class<T> cls) throws SQLException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        List<T> list = new ArrayList<T>();
        int index = 1;
        Connection connection = dbService.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (Object param : params) preparedStatement.setObject(index++, param);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int cols_len = metaData.getColumnCount();
        while (resultSet.next()) {
            // 通过反射机制创建一个实例
            T resultObject = cls.newInstance();
            for (int i = 0; i < cols_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                Field field = cls.getDeclaredField(cols_name);
            }
            list.add(resultObject);
        }
        try {
            resultSet.close();
            dbService.evictConnection(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /***************************************************************************
     * 增删改查
     * @Redis
     ***************************************************************************/
    /**
     * 设置(key,value)(String, Map<String, Object>) 超时seconds
     *
     * @param key
     * @param hash
     * @return
     */
    public String hmsoset(final String key, final Map<String, Object> hash, final int seconds) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            jedis.expire(key, seconds);
            return jedis.hmset(key.getBytes(), SerializeUtil.serializehmso2mbb(hash));
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    /**
     * 设置(key,value)(String, Map<String, String>) 超时seconds
     *
     * @param key
     * @param hash
     * @return
     */
    public String hmssset(final String key, final Map<String, String> hash, final int seconds) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            jedis.expire(key, seconds);
            return jedis.hmset(key, hash);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    /**
     * 设置(key,value)(String, Map<String, Object>)
     *
     * @param key
     * @param hash
     * @return
     */
    public String hmsoset(final String key, final Map<String, Object> hash) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hmset(key.getBytes(), SerializeUtil.serializehmso2mbb(hash));
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    /**
     * 返回hash Map<Sting, Object>
     *
     * @param key
     * @return
     */
    public Map<String, Object> hsogetall(String key) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            Map<byte[], byte[]> hash = jedis.hgetAll(key.getBytes());
            return SerializeUtil.unserializehmbb2mso(hash);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    /**
     * key value
     */
    public String get(final String key) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.get(key);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public String set(final String key, final String value) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.set(key, value);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long del(final String... keys) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.del(keys);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long append(final String key, final String str) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.del(key, str);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Boolean exists(final String key) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.exists(key);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    /**
     * set
     */
    public Long setnx(final String key, final String value) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.setnx(key, value);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public String setex(final String key, final int seconds, final String value) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.setex(key, seconds, value);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long setrange(final String key, final Long offset, final String value) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.setrange(key, offset, value);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public List<String> mget(final String... keys) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.mget(keys);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public String mset(final String... keys) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.mset(keys);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long msetnx(final String... keysvalues) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.msetnx(keysvalues);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public String getSet(final String key, final String value) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.getSet(key, value);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    /**
     * hash string
     */
    public String hmset(final String key, final Map<String, String> hash) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            ;
            return jedis.hmset(key, hash);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Map<String, String> hgetall(final String key) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hgetAll(key);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public String hget(final String key, final String field) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hget(key, field);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long hset(final String key, final String field, final String value) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hset(key, field, value);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long expire(final String key, final int seconds) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.expire(key, seconds);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Boolean hexists(final String key, final String field) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hexists(key, field);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long hdel(final String key, final String field) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hdel(key, field);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long hsetnx(final String key, final String field, final String value) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hsetnx(key, field, value);
        } finally {
            if (jedis != null) jedis.close();
        }
    }


    public List<String> hmget(final String key, final String... fields) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hmget(key, fields);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long hincrBy(final String key, final String field, final Long value) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hincrBy(key, field, value);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long hlen(final String key) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hlen(key);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Set<String> hkeys(final String key) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hkeys(key);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public List<String> hvals(final String key) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hmget(key);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    /**
     * hash binary
     */
    public byte[] hget(final byte[] key, final byte[] field) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hget(key, field);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long hsetnx(final byte[] key, final byte[] field, final byte[] value) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hsetnx(key, field, value);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public String hmset(final byte[] key, final Map<byte[], byte[]> hash) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hmset(key, hash);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public List<byte[]> hmget(final byte[] key, final byte[]... fields) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hmget(key, fields);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long hincrBy(final byte[] key, final byte[] field, final Long value) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hincrBy(key, field, value);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Double hincrByFloat(final byte[] key, final byte[] field, final double value) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hincrByFloat(key, field, value);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Boolean hexists(final byte[] key, final byte[] field) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hexists(key, field);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long hdel(final byte[] key, final byte[]... fields) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hdel(key, fields);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Long hlen(final byte[] key) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hlen(key);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Set<byte[]> hkeys(final byte[] key) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hkeys(key);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public List<byte[]> hvals(final byte[] key) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hvals(key);
        } finally {
            if (jedis != null) jedis.close();
        }
    }

    public Map<byte[], byte[]> hgetAll(final byte[] key) {
        Jedis jedis = null;
        try {
            jedis = CacheService.getInstance().getJedis();
            return jedis.hgetAll(key);
        } finally {
            if (jedis != null) jedis.close();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/langzi7758521/article/details/80691439