Redis服务类模板

  • Post author:
  • Post category:其他


package cn.com.erp.configure.redis;
import cn.com.util.log.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

/**
 * ErpRedisService
 * @author zhihui
 * @date 2021/12/07
 */
@Service
public class ErpRedisService<T> {
    private static Logger logger = LoggerFactory.getLogger(ErpRedisService.class);

    @Autowired
    private RedisTemplate<String, T> redisTemplate;

    /**
     * 设置缓存
     * @param cacheKey
     * @param t
     * @param time
     * @param unit
     * @return
     */
    public boolean set(String cacheKey, T t, long time, TimeUnit unit) {
        try {
            redisTemplate.boundValueOps(cacheKey).set(t);
            redisTemplate.boundValueOps(cacheKey).expire(time, unit);
            return true;
        } catch (Exception e) {
            LogUtil.encError(logger, "ErpRedisService setStr error", e);
            return false;
        }
    }

    /**
     * 获取boundHashOps
     * @param hashKey
     * @return
     */
    public BoundHashOperations<String, Object, T> createBoundHashOps(String hashKey) {
        try {
            BoundHashOperations<String, Object, T> boundHashOps = redisTemplate.boundHashOps(hashKey);
            return boundHashOps;
        } catch (Exception e) {
            LogUtil.encError(logger, "ErpRedisService setStr error", e);
            return null;
        }
    }

    /**
     * 设置Hash缓存
     * @param hashKey
     * @param cacheKey
     * @param t
     * @param time
     * @param unit
     * @return
     */
    public boolean setHash(String hashKey, String cacheKey, T t, long time, TimeUnit unit) {
        try {
            BoundHashOperations<String, Object, T> boundHashOps = createBoundHashOps(hashKey);
            boundHashOps.put(cacheKey, t);
            boundHashOps.expire(time, unit);
            return true;
        } catch (Exception e) {
            LogUtil.encError(logger, "ErpRedisService setStr error", e);
            return false;
        }
    }

    /**
     * 设置缓存到期时间
     * @param cacheKey
     * @param time
     * @param unit
     * @return
     */
    public boolean expire(String cacheKey, long time, TimeUnit unit) {
        try {
            redisTemplate.boundValueOps(cacheKey).expire(time, unit);
            return true;
        } catch (Exception e) {
            LogUtil.encError(logger, "ErpRedisService expire error: ", e);
            return false;
        }
    }

    /**
     * 获取缓存
     * @param key
     * @return
     */
    public T get(String key) {
        try {
            return redisTemplate.boundValueOps(key).get();
        } catch (Exception e) {
            LogUtil.encError(logger, "ErpRedisService getStr error: ", e);
            return null;
        }
    }

    /**
     * 获取Hash缓存
     * @param hashKey
     * @param key
     * @return
     */
    public T getHash(String hashKey, String key) {
        try {
            BoundHashOperations<String, Object, T> boundHashOps = createBoundHashOps(hashKey);
            return boundHashOps.get(key);
        } catch (Exception e) {
            LogUtil.encError(logger, "ErpRedisService getStr error: ", e);
            return null;
        }
    }

    /**
     * 对key的值自增1
     * @param key
     * @return
     */
    public long increment(String key) {
        try {
            return redisTemplate.boundValueOps(key).increment(1);
        } catch (Exception e) {
            LogUtil.encError(logger, "ErpRedisService setStr error: ", e);
            return 0;
        }
    }

    /**
     * 获取自增key的当前值
     * @param key
     * @return
     */
    public long getIncrement(String key) {
        try {
            return redisTemplate.boundValueOps(key).increment(0);
        } catch (Exception e) {
            LogUtil.encError(logger, "ErpRedisService getIncrementCount error: ", e);
            return 0;
        }
    }

    /**
     * 删除key
     * @param key
     */
    public void delete(String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            LogUtil.encError(logger, "ErpRedisService delStr error: ", e);
        }
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            LogUtil.encError(logger, "ErpRedisService hasKey error: ", e);
            return false;
        }
    }
}

LogUtil

package cn.com.util.log;
import cn.com..util.Base64;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;

public class LogUtil {
    private static final boolean FLAG = true;

    public LogUtil() {
    }

    public static void encInfo(Logger logger, String log) {
        logger.info(log);
    }

    public static void encInfo(Logger logger, String formatStr, Object... args) {
        logger.info(formatStr, args);
    }

    public static void encWarn(Logger logger, String log) {
        logger.warn(log);
    }

    public static void encWarn(Logger logger, String formatStr, Object... args) {
        logger.warn(formatStr, args);
    }

    public static void encError(Logger logger, String log) {
        logger.error(log);
    }

    public static void encError(Logger logger, String formatStr, Object... args) {
        logger.error(formatStr, args);
    }

    public static void encError(Logger logger, String formatStr, Throwable throwable) {
        logger.error(formatStr, throwable);
    }

    private static String[] convertToJSONStringArray(StackTraceElement[] stackTraceElements) {
        if (null == stackTraceElements) {
            throw new NullPointerException("Exception stack information must not be null!");
        } else {
            String[] stringArray = new String[stackTraceElements.length];

            for(int i = 0; i < stackTraceElements.length; ++i) {
                stringArray[i] = Base64.encode(JSON.toJSONString(stackTraceElements[i]).getBytes());
            }

            return stringArray;
        }
    }

    private static String[] convertToArray(Object... args) {
        String[] stringArray = new String[args.length];

        for(int i = 0; i < args.length; ++i) {
            stringArray[i] = Base64.encode(String.valueOf(args[i]).getBytes());
        }

        return stringArray;
    }
}

Base64

package cn.com.util;

public class Base64 {
    private static final int BASELENGTH = 128;
    private static final int LOOKUPLENGTH = 64;
    private static final int TWENTYFOURBITGROUP = 24;
    private static final int EIGHTBIT = 8;
    private static final int SIXTEENBIT = 16;
    private static final int FOURBYTE = 4;
    private static final int SIGN = -128;
    private static char PAD = '=';
    private static byte[] base64Alphabet = new byte[128];
    private static char[] lookUpBase64Alphabet = new char[64];

    public Base64() {
    }

    private static boolean isWhiteSpace(char octect) {
        return octect == ' ' || octect == '\r' || octect == '\n' || octect == '\t';
    }

    private static boolean isPad(char octect) {
        return octect == PAD;
    }

    private static boolean isData(char octect) {
        return octect < 128 && base64Alphabet[octect] != -1;
    }

    public static String encode(byte[] binaryData) {
        if (binaryData == null) {
            return null;
        } else {
            int lengthDataBits = binaryData.length * 8;
            if (lengthDataBits == 0) {
                return "";
            } else {
                int fewerThan24bits = lengthDataBits % 24;
                int numberTriplets = lengthDataBits / 24;
                int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
                char[] encodedData = null;
                char[] encodedData = new char[numberQuartet * 4];
                byte k = false;
                byte l = false;
                byte b1 = false;
                byte b2 = false;
                byte b3 = false;
                int encodedIndex = 0;
                int dataIndex = 0;

                byte val2;
                byte k;
                byte l;
                byte b1;
                byte b2;
                for(int i = 0; i < numberTriplets; ++i) {
                    b1 = binaryData[dataIndex++];
                    b2 = binaryData[dataIndex++];
                    byte b3 = binaryData[dataIndex++];
                    l = (byte)(b2 & 15);
                    k = (byte)(b1 & 3);
                    val2 = (b1 & -128) == 0 ? (byte)(b1 >> 2) : (byte)(b1 >> 2 ^ 192);
                    byte val2 = (b2 & -128) == 0 ? (byte)(b2 >> 4) : (byte)(b2 >> 4 ^ 240);
                    byte val3 = (b3 & -128) == 0 ? (byte)(b3 >> 6) : (byte)(b3 >> 6 ^ 252);
                    encodedData[encodedIndex++] = lookUpBase64Alphabet[val2];
                    encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | k << 4];
                    encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2 | val3];
                    encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 63];
                }

                byte val1;
                if (fewerThan24bits == 8) {
                    b1 = binaryData[dataIndex];
                    k = (byte)(b1 & 3);
                    val1 = (b1 & -128) == 0 ? (byte)(b1 >> 2) : (byte)(b1 >> 2 ^ 192);
                    encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
                    encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
                    encodedData[encodedIndex++] = PAD;
                    encodedData[encodedIndex++] = PAD;
                } else if (fewerThan24bits == 16) {
                    b1 = binaryData[dataIndex];
                    b2 = binaryData[dataIndex + 1];
                    l = (byte)(b2 & 15);
                    k = (byte)(b1 & 3);
                    val1 = (b1 & -128) == 0 ? (byte)(b1 >> 2) : (byte)(b1 >> 2 ^ 192);
                    val2 = (b2 & -128) == 0 ? (byte)(b2 >> 4) : (byte)(b2 >> 4 ^ 240);
                    encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
                    encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | k << 4];
                    encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
                    encodedData[encodedIndex++] = PAD;
                }

                return new String(encodedData);
            }
        }
    }

    public static byte[] decode(String encoded) {
        if (encoded == null) {
            return null;
        } else {
            char[] base64Data = encoded.toCharArray();
            int len = removeWhiteSpace(base64Data);
            if (len % 4 != 0) {
                return null;
            } else {
                int numberQuadruple = len / 4;
                if (numberQuadruple == 0) {
                    return new byte[0];
                } else {
                    byte[] decodedData = null;
                    byte b1 = false;
                    byte b2 = false;
                    byte b3 = false;
                    byte b4 = false;
                    char d1 = false;
                    char d2 = false;
                    char d3 = false;
                    char d4 = false;
                    int i = 0;
                    int encodedIndex = 0;
                    int dataIndex = 0;

                    byte[] decodedData;
                    byte b1;
                    byte b2;
                    byte b3;
                    byte b4;
                    char d1;
                    char d2;
                    char d3;
                    char d4;
                    for(decodedData = new byte[numberQuadruple * 3]; i < numberQuadruple - 1; ++i) {
                        if (!isData(d1 = base64Data[dataIndex++]) || !isData(d2 = base64Data[dataIndex++]) || !isData(d3 = base64Data[dataIndex++]) || !isData(d4 = base64Data[dataIndex++])) {
                            return null;
                        }

                        b1 = base64Alphabet[d1];
                        b2 = base64Alphabet[d2];
                        b3 = base64Alphabet[d3];
                        b4 = base64Alphabet[d4];
                        decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4);
                        decodedData[encodedIndex++] = (byte)((b2 & 15) << 4 | b3 >> 2 & 15);
                        decodedData[encodedIndex++] = (byte)(b3 << 6 | b4);
                    }

                    if (isData(d1 = base64Data[dataIndex++]) && isData(d2 = base64Data[dataIndex++])) {
                        b1 = base64Alphabet[d1];
                        b2 = base64Alphabet[d2];
                        d3 = base64Data[dataIndex++];
                        d4 = base64Data[dataIndex++];
                        if (isData(d3) && isData(d4)) {
                            b3 = base64Alphabet[d3];
                            b4 = base64Alphabet[d4];
                            decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4);
                            decodedData[encodedIndex++] = (byte)((b2 & 15) << 4 | b3 >> 2 & 15);
                            decodedData[encodedIndex++] = (byte)(b3 << 6 | b4);
                            return decodedData;
                        } else {
                            byte[] tmp;
                            if (isPad(d3) && isPad(d4)) {
                                if ((b2 & 15) != 0) {
                                    return null;
                                } else {
                                    tmp = new byte[i * 3 + 1];
                                    System.arraycopy(decodedData, 0, tmp, 0, i * 3);
                                    tmp[encodedIndex] = (byte)(b1 << 2 | b2 >> 4);
                                    return tmp;
                                }
                            } else if (!isPad(d3) && isPad(d4)) {
                                b3 = base64Alphabet[d3];
                                if ((b3 & 3) != 0) {
                                    return null;
                                } else {
                                    tmp = new byte[i * 3 + 2];
                                    System.arraycopy(decodedData, 0, tmp, 0, i * 3);
                                    tmp[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4);
                                    tmp[encodedIndex] = (byte)((b2 & 15) << 4 | b3 >> 2 & 15);
                                    return tmp;
                                }
                            } else {
                                return null;
                            }
                        }
                    } else {
                        return null;
                    }
                }
            }
        }
    }

    private static int removeWhiteSpace(char[] data) {
        if (data == null) {
            return 0;
        } else {
            int newSize = 0;
            int len = data.length;

            for(int i = 0; i < len; ++i) {
                if (!isWhiteSpace(data[i])) {
                    data[newSize++] = data[i];
                }
            }

            return newSize;
        }
    }

    static {
        int i;
        for(i = 0; i < 128; ++i) {
            base64Alphabet[i] = -1;
        }

        for(i = 90; i >= 65; --i) {
            base64Alphabet[i] = (byte)(i - 65);
        }

        for(i = 122; i >= 97; --i) {
            base64Alphabet[i] = (byte)(i - 97 + 26);
        }

        for(i = 57; i >= 48; --i) {
            base64Alphabet[i] = (byte)(i - 48 + 52);
        }

        base64Alphabet[43] = 62;
        base64Alphabet[47] = 63;

        for(i = 0; i <= 25; ++i) {
            lookUpBase64Alphabet[i] = (char)(65 + i);
        }

        i = 26;

        int j;
        for(j = 0; i <= 51; ++j) {
            lookUpBase64Alphabet[i] = (char)(97 + j);
            ++i;
        }

        i = 52;

        for(j = 0; i <= 61; ++j) {
            lookUpBase64Alphabet[i] = (char)(48 + j);
            ++i;
        }

        lookUpBase64Alphabet[62] = '+';
        lookUpBase64Alphabet[63] = '/';
    }
}