QRCodeServiceImpl.java 2.79 KB
package com.xkl.service;

import com.xkl.config.Constants;
import com.xkl.tools.DESTools;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * create by zhaoyue
 * 2017-03-11
 */

@Service
@CommonsLog
public class QRCodeServiceImpl implements IQRCodeService, Constants {
    private static final String REDIS_ACC_QR_PREFIX = "acc_qr-";
    private static final String REDIS_QR_ACC_PREFIX = "qr_acc-";
    private static final String HTTP_PARA_QR_KEY = "tnvkqybFHp69pinDZJ7UWuX7";

    private RedisTemplate<String, String> redis;

    @Autowired
    public void setRedis(RedisTemplate redis) {
        this.redis = redis;
    }


    @Override
    public String getDecryptHttpParaQr(String encryptQr, long t) {
        String qrcode = "";
        try {
            String str = DESTools.decrypt(encryptQr, HTTP_PARA_QR_KEY);
            if (str.endsWith(Long.toString(t))) {
                return str.replace(Long.toString(t), "");
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String getAccountWithQRCode(String qrcode) {
        String qrAcckey = genQrAccKey(qrcode);
        String account = null;
        if (redis.hasKey(qrAcckey)) {
            account = redis.boundValueOps(qrAcckey).get();
        }
        return account;
    }

    @Override
    public String getQRCodeWithAccount(String account) {
        String accQrkey = genAccQrKey(account);
        String qrCodeStr = "";
        if (redis.hasKey(accQrkey)) {
            qrCodeStr = redis.boundValueOps(accQrkey).get();
        } else {
            Date dt = new Date();
            SimpleDateFormat matter1 = new SimpleDateFormat("yyyyMMdd");
            String dateStr = matter1.format(dt);
            try {
                qrCodeStr = DESTools.encrypt(account + dateStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String qrAcckey = genQrAccKey(qrCodeStr);
            redis.boundValueOps(qrAcckey).set(account, Constants.QRCODE_EXPIRES_HOUR, TimeUnit.HOURS);
            redis.boundValueOps(accQrkey).set(qrCodeStr, Constants.QRCODE_EXPIRES_HOUR, TimeUnit.HOURS);
        }
        return qrCodeStr;
    }

    private static String genAccQrKey(String account) {
        return REDIS_ACC_QR_PREFIX + account;
    }

    private static String genQrAccKey(String account) {
        return REDIS_QR_ACC_PREFIX + account;
    }

    public static String getHttpParaQrKey() {
        return HTTP_PARA_QR_KEY;
    }
}