目前项目中在用一个后端生成二维码的功能,因为二维码传递信息过多,导致 二维码帧点数过多,最后形成的图片太密集,用手机识别时 需比较长的时间。那么碰到这种情况改如何处理呢?
处理前:
处理后:
二维码太密的原因是 传递的信息太多,那么,我们是否可以通过减少传递的信息,来降低二维码密集度。
目前有两个方向:
1. 产品方向: 因为传递的参数为了安全性,是加密后的,因此太长。为了安全性,因此这个方向可以直接放弃了。
2. 技术方向: 因为之前刚好调用过新浪的短链接生产接口,用短链接与长链接相互映射,二维码扫描出来是 短链接,然后由后台重定向至长链接,即可解决我们这个问题。但是 由于安全性问题,新浪,腾讯、阿里已于去年全面下架短链接生成接口。那么只能我们自己来实现了,其实弄清楚原理后,自己实现他也非常简单。
maven
<properties>
<zxing.version>3.3.0</zxing.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>${
zxing.version}</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>${
zxing.version}</version>
</dependency>
</dependencies>
工具类
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.util.Base64Utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.net.URL;
import java.util.Hashtable;
import java.util.UUID;
public class QRCodeUtils {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int WIDTH = 60;
// LOGO高度
private static final int HEIGHT = 60;
private static int BLACK = 0x000000;
private static int WHITE = 0xFFFFFF;
private static String BASE64_JPG_IMAGE_HEADER = "data:image/jpg;base64,";
private static BufferedImage createImage(String content, String imgPath,
boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK
: WHITE);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCodeUtils.insertImage(image, imgPath, needCompress);
return image;
}
/**
* 插入LOGO
*
* @param source 二维码图片
* @param imgPath LOGO图片地址
* @param needCompress 是否压缩
* @throws Exception
*/
private static void insertImage(BufferedImage source, String imgPath,
boolean needCompress) throws Exception {
Image src = null;
if (imgPath.startsWith("http")) {
URL url = new URL(imgPath);
src = ImageIO.read(url);
} else {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println("" + imgPath + " 该文件不存在!");
return;
}
src = ImageIO.read(new File(imgPath));
}
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) {
// 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content 内容
* @param imgPath LOGO地址
* @param destPath 存放目录
* @param needCompress 是否压缩LOGO
* @throws Exception
*/
public static String encode(String content, String imgPath, String destPath,
boolean needCompress, boolean toBase64) throws Exception {
BufferedImage image = QRCodeUtils.createImage(content, imgPath,
needCompress);
if (toBase64) {
StringBuffer stringBuffer = new StringBuffer(BASE64_JPG_IMAGE_HEADER);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(image, FORMAT_NAME, baos);
stringBuffer.append(Base64Utils.encodeToString(baos.toByteArray()).trim());
} finally {
baos.close();
}
return stringBuffer.toString();
} else {
mkdirs(destPath);
String file = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));
return file;
}
}
/**
* 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
*
* @param destPath 存放目录
* @date 2013-12-11 上午10:16:36
*/
public static void mkdirs(String destPath) {
File file = new File(destPath);
//当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content 内容
* @param imgPath LOGO地址
* @param destPath 存储地址
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath)
throws Exception {
QRCodeUtils.encode(content, imgPath, destPath, false, false);
}
/**
* 生成二维码
*
* @param content 内容
* @param destPath 存储地址
* @param needCompress 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String destPath,
boolean needCompress) throws Exception {
QRCodeUtils.encode(content, null, destPath, needCompress, false);
}
/**
* 生成二维码
*
* @param content 内容
* @param destPath 存储地址
* @throws Exception
*/
public static void encode(String content, String destPath) throws Exception {
QRCodeUtils.encode(content, null, destPath, false, false);
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content 内容
* @param imgPath LOGO地址
* @param output 输出流
* @param needCompress 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String imgPath,
OutputStream output, boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtils.createImage(content, imgPath,
needCompress);
ImageIO.write(image, FORMAT_NAME, output);
}
/**
* 生成二维码
*
* @param content 内容
* @param output 输出流
* @throws Exception
*/
public static void encode(String content, OutputStream output)
throws Exception {
QRCodeUtils.encode(content, null, output, false);
}
/**
* 解析二维码
*
* @param file 二维码图片
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
/**
* 解析二维码
*
* @param path 二维码图片地址
* @return
* @throws Exception
*/
public static String decode(String path) throws Exception {
return QRCodeUtils.decode(new File(path));
}
1. 新建 映射表
CREATE TABLE `bpm_url` (
`url_uuid` varchar(32) NOT NULL,
`short_url` varchar(32) NOT NULL DEFAULT '' COMMENT '短连接',
`long_url` varchar(4000) NOT NULL DEFAULT '' COMMENT '长链接',
`key` varchar(64) NOT NULL DEFAULT '',
`expires_time` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '过期时间',
`valid_state` tinyint(2) unsigned NOT NULL DEFAULT '1' COMMENT '状态;0表示无效,1表示有效',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`url_uuid`),
KEY `idx_short_url` (`short_url`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='链接表';
2. 短链接生成算法(目前主流有以下两种 62 进制 和 MD5 加密算法)
MD5加密:
public class ShortUrlGenerator {
/**
* @param args
*/
public static void main(String[] args) {
// 长连接: http://tech.sina.com.cn/i/2011-03-23/11285321288.shtml
// 新浪解析后的短链接为: http://t.cn/h1jGSC
String sLongUrl = "http://tech.sina.com.cn/i/2011-03-23/11285321288.shtml" ;
// 3BD768E58042156E54626860E241E999
String[] aResult = shortUrl (sLongUrl);
// 打印出结果
for ( int i = 0; i < aResult. length ; i++) {
System. out .println( "[" + i + "]:::" + aResult[i]);
}
}
public static String[] shortUrl(String url) {
// 可以自定义生成 MD5 加密字符传前的混合 KEY
String key = "wuguowei" ;
// 要使用生成 URL 的字符
String[] chars = new String[] {
"a" , "b" , "c" , "d" , "e" , "f" , "g" , "h" ,
"i" , "j" , "k" , "l" , "m" , "n" , "o" , "p" , "q" , "r" , "s" , "t" ,
"u" , "v" , "w" , "x" , "y" , "z" , "0" , "1" , "2" , "3" , "4" , "5" ,
"6" , "7" , "8" , "9" , "A" , "B" , "C" , "D" , "E" , "F" , "G" , "H" ,
"I" , "J" , "K" , "L" , "M" , "N" , "O" , "P" , "Q" , "R" , "S" , "T" ,
"U" , "V" , "W" , "X" , "Y" , "Z"
};
// 对传入网址进行 MD5 加密
String sMD5EncryptResult = ( new MD5()).getMD5ofStr(key + url);
String hex = sMD5EncryptResult;
String[] resUrl = new String[4];
for ( int i = 0; i < 4; i++) {
// 把加密字符按照 8 位一组 16 进制与 0x3FFFFFFF 进行位与运算
String sTempSubString = hex.substring(i * 8, i * 8 + 8);
// 这里需要使用 long 型来转换,因为 Inteper .parseInt() 只能处理 31 位 , 首位为符号位 , 如果不用 long ,则会越界
long lHexLong = 0x3FFFFFFF & Long.parseLong (sTempSubString, 16);
String outChars = "" ;
for ( int j = 0; j < 6; j++) {
// 把得到的值与 0x0000003D 进行位与运算,取得字符数组 chars 索引
long index = 0x0000003D & lHexLong;
// 把取得的字符相加
outChars += chars[( int ) index];
// 每次循环按位右移 5 位
lHexLong = lHexLong >> 5;
}
// 把字符串存入对应索引的输出数组
resUrl[i] = outChars;
}
return resUrl;
}
}
62 进制
可以通过雪花算法生成唯一编号,然后在进行62进制转换。
/*雪花算法*/
import java.util.Random;
/**
* todo: 雪花算法获得唯一编号
*
* @author : zhoulin.zhu
* @date : 2019/7/23 14:24
*/
public class SnowKeyGenUtils {
private static volatile SnowKeyGenUtils snowKeyGenUtils;
public static SnowKeyGenUtils getInstance() {
if (null == snowKeyGenUtils) {
synchronized (SnowKeyGenUtils.class) {
if (null == snowKeyGenUtils) {
snowKeyGenUtils = new SnowKeyGenUtils();
}
}
}
return snowKeyGenUtils;
}
//开始时间(2020-08-25)
private final long startTime = 1598319388200L;
//机器ID所占大小
private final long workerIdBits = 5L;
// 数据标识id所占的位数
private final long dataCenterIdBits = 5L;
// 支持的最大机器id(十进制),结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)
// -1L 左移 5位 (worker id 所占位数) 即 5位二进制所能获得的最大十进制数 - 31
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 支持的最大数据标识id - 31
private final long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits);
// 序列在id中占的位数
private final long sequenceBits = 12L;
// 机器ID 左移位数 - 12 (即末 sequence 所占用的位数)
private final long workerIdMoveBits = sequenceBits;
// 数据标识id 左移位数 - 17(12+5)
private final long dataCenterIdMoveBits = sequenceBits + workerIdBits;
// 时间截向 左移位数 - 22(5+5+12)
private final long timestampMoveBits = sequenceBits + workerIdBits + dataCenterIdBits;
// 生成序列的掩码(12位所对应的最大整数值),这里为4095 (0b111111111111=0xfff=4095)
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
/**
* 工作机器ID(0~31)
*/
private long workerId;
/**
* 数据中心ID(0~31)
*/
private long dataCenterId;
/**
* 毫秒内序列(0~4095)
*/
private long sequence = 0L;
/**
* 上次生成ID的时间截
*/
private long lastTimestamp = -1L;
/**
* 功能描述: 随机生成 workerId 和 dataCenterId ,解决多台机器并发问题
*
* @author : zhoulin.zhu
* @date :
*/
private SnowKeyGenUtils() {
long workerId = getRandom();
long dataCenterId = getRandom();
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("Worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
throw new IllegalArgumentException(String.format("DataCenter Id can't be greater than %d or less than 0", maxDataCenterId));
}
this.workerId = workerId;
this.dataCenterId = dataCenterId;
}
/**
* 生成1-31之间的随机数
*
* @return
*/
private long getRandom() {
int max = (int) (maxDataCenterId);
int min = 1;
Random random = new Random();
return random.nextInt(max - min) + min;
}
/**
* 构造函数
*
* @param workerId 工作ID (0~31)
* @param dataCenterId 数据中心ID (0~31)
*/
public SnowKeyGenUtils(long workerId, long dataCenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("Worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
throw new IllegalArgumentException(String.format("DataCenter Id can't be greater than %d or less than 0", maxDataCenterId));
}
this.workerId = workerId;
this.dataCenterId = dataCenterId;
}
// 线程安全的获得下一个 ID 的方法
public synchronized String getNextId() {
long timestamp = currentTime();
//如果当前时间小于上一次ID生成的时间戳: 说明系统时钟回退过 - 这个时候应当抛出异常
if (timestamp < lastTimestamp) {
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
//如果是同一时间生成的,则进行毫秒内序列
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
//毫秒内序列溢出 即 序列 > 4095
if (sequence == 0) {
//阻塞到下一个毫秒,获得新的时间戳
timestamp = blockTillNextMillis(lastTimestamp);
}
}
//时间戳改变,毫秒内序列重置
else {
sequence = 0L;
}
//上次生成ID的时间截
lastTimestamp = timestamp;
//移位并通过或运算拼到一起组成64位的ID
long nextId = ((timestamp - startTime) << timestampMoveBits) //
| (dataCenterId << dataCenterIdMoveBits) //
| (workerId << workerIdMoveBits) //
| sequence;
return Long.toString(nextId);
}
// 阻塞到下一个毫秒 即 直到获得新的时间戳
private long blockTillNextMillis(long lastTimestamp) {
long timestamp = currentTime();
while (timestamp <= lastTimestamp) {
timestamp = currentTime();
}
return timestamp;
}
// 获得以毫秒为单位的当前时间
private long currentTime() {
return System.currentTimeMillis();
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
Thread2 thread2 = new Thread2();
thread2.start();
}
}
}
// 测试线程
class Thread2 extends Thread {
@Override
public void run() {
System.out.println("SnowKeyGenUtils.instance.hashCode() = " + SnowKeyGenUtils.getInstance().hashCode() +" :" + SnowKeyGenUtils.getInstance().getNextId());
}
}
/* 这里的顺序建议打乱,这样可以降低 与其他算法的 碰撞几率 */
static final char[] DIGITS =
{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
private static String to62RadixString(long seq) {
StringBuilder sBuilder = new StringBuilder();
while (true) {
int remainder = (int) (seq % 62);
sBuilder.append(DIGITS[remainder]);
seq = seq / 62;
if (seq == 0) {
break;
}
}
return sBuilder.reverse().toString();
}
private static long radixString(String str) {
long sum = 0l;
int len = str.length();
for (int i = 0; i < len; i++) {
sum += indexDigits(str.charAt(len-i-1))*Math.pow((double)62,(double)i);
}
return sum;
}
private static int indexDigits(char ch){
for (int i = 0; i < DIGITS.length; i++) {
if (ch == DIGITS[i]){
return i;
}
}
return -1;
}
4. 跳转用301还是302
这也是一个有意思的话题。首先当然考察一个候选人对301和302的理解。浏览器缓存机制的理解。然后是考察他的业务经验。301是永久重定向,302是临时重定向。短地址一经生成就不会变化,所以用301是符合http语义的。同时对服务器压力也会有一定减少。
但是如果使用了301,我们就无法统计到短地址被点击的次数了。而这个点击次数是一个非常有意思的大数据分析数据源。能够分析出的东西非常非常多。所以选择302虽然会增加服务器压力,但是我想是一个更好的选择