1、前言
簡(jiǎn)單的說(shuō)串述,mybatis插件就是對(duì)ParameterHandler执解、ResultSetHandler、StatementHandler纲酗、Executor這四個(gè)接口上的方法進(jìn)行攔截衰腌,利用JDK動(dòng)態(tài)代理機(jī)制,為這些接口的實(shí)現(xiàn)類(lèi)創(chuàng)建代理對(duì)象觅赊,在執(zhí)行方法時(shí)右蕊,先去執(zhí)行代理對(duì)象的方法,從而執(zhí)行自己編寫(xiě)的攔截邏輯吮螺,所以真正要用好mybatis插件尤泽,主要還是要熟悉這四個(gè)接口的方法以及這些方法上的參數(shù)的含義;
另外规脸,如果配置了多個(gè)攔截器的話坯约,會(huì)出現(xiàn)層層代理的情況,即代理對(duì)象代理了另外一個(gè)代理對(duì)象莫鸭,形成一個(gè)代理鏈條闹丐,執(zhí)行的時(shí)候,也是層層執(zhí)行被因;
關(guān)于mybatis插件涉及到的設(shè)計(jì)模式和軟件思想如下:
設(shè)計(jì)模式:代理模式卿拴、責(zé)任鏈模式;
軟件思想:AOP編程思想梨与,降低模塊間的耦合度堕花,使業(yè)務(wù)模塊更加獨(dú)立;
一些注意事項(xiàng):
不要定義過(guò)多的插件粥鞋,代理嵌套過(guò)多缘挽,執(zhí)行方法的時(shí)候,比較耗性能;
攔截器實(shí)現(xiàn)類(lèi)的intercept方法里最后不要忘了執(zhí)行invocation.proceed()方法壕曼,否則多個(gè)攔截器情況下苏研,執(zhí)行鏈條會(huì)斷掉;
2腮郊、Springboot 編寫(xiě) mybatis 插件
編寫(xiě) mybatis 插件很簡(jiǎn)單摹蘑,首先定義要攔截的是上面說(shuō)到的哪個(gè)類(lèi),攔截哪個(gè)方法轧飞,參數(shù)是啥衅鹿,然后配置一下即可
package com.snowflake1.test.config;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.util.Properties;
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class MyPlugin implements Interceptor {
private Logger logger = LoggerFactory.getLogger(MyPlugin.class);
private long time;
//方法攔截
@Override
public Object intercept(Invocation invocation) throws Throwable {
//通過(guò)StatementHandler獲取執(zhí)行的sql
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql();
long start = System.currentTimeMillis();
Object proceed = invocation.proceed();
long end = System.currentTimeMillis();
if ((end - start) > time) {
logger.info("本次數(shù)據(jù)庫(kù)操作是慢查詢(xún),sql是:" + sql);
}
return proceed;
}
//獲取到攔截的對(duì)象过咬,底層也是通過(guò)代理實(shí)現(xiàn)的大渤,實(shí)際上是拿到一個(gè)目標(biāo)代理對(duì)象
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
//獲取設(shè)置的閾值等參數(shù)
@Override
public void setProperties(Properties properties) {
this.time = Long.parseLong(properties.getProperty("time"));
}
}
在 springboot 那配置一下(我用的是 mybatisplus)
package com.snowflake1.test.config;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class MapperConfig {
//將插件加入到mybatis插件攔截鏈中
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return new ConfigurationCustomizer() {
@Override
public void customize(MybatisConfiguration configuration) {
//插件攔截鏈采用了責(zé)任鏈模式,執(zhí)行順序和加入連接鏈的順序有關(guān)
MyPlugin myPlugin = new MyPlugin();
//設(shè)置參數(shù)援奢,比如閾值等兼犯,可以在配置文件中配置忍捡,這里直接寫(xiě)死便于測(cè)試
Properties properties = new Properties();
//這里設(shè)置慢查詢(xún)閾值為1毫秒集漾,便于測(cè)試
properties.setProperty("time", "1");
myPlugin.setProperties(properties);
configuration.addInterceptor(myPlugin);
}
};
}
}
或者
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.xdd.mybatis.CatMybatisPlugin;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Configuration
public class MybatisInterceptorConfig {
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Autowired
private SnowflakeIdGenerator snowflakeIdGenerator;
@PostConstruct
public void addInterceptor() {
this.sqlSessionFactory.getConfiguration().addInterceptor(new PaginationInterceptor());
this.sqlSessionFactory.getConfiguration().addInterceptor(new CatMybatisPlugin());
MybatisConfiguration mybatisConfiguration = (MybatisConfiguration) this.sqlSessionFactory.getConfiguration();
mybatisConfiguration.getGlobalConfig().setIdentifierGenerator(snowflakeIdGenerator);
}
}
SnowflakeIdGenerator:
import cn.com.kemai.open.util.SnowflakeIdUtils;
import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
@Component
public class SnowflakeIdGenerator implements IKeyGenerator, IdentifierGenerator {
@Override
public Number nextId(Object entity) {
return SnowflakeIdUtils.generateId();
}
/**
* @param incrementerName
* 增量器名稱(chēng),@KeySequence中的value之會(huì)傳入該參數(shù)中
* @return
*/
@Override
public String executeSql(String incrementerName) {
return "select " + getId() + " from dual";
}
public static String getId() {
//獲取當(dāng)前時(shí)間戳
String str = String.valueOf(System.currentTimeMillis());
List list = new ArrayList();
//將時(shí)間戳放入到List中
for (Character s : str.toCharArray()) {
list.add(s.toString());
}
//隨機(jī)打亂
Collections.shuffle(list);
//拼接字符串砸脊,并添加2(自定義)位隨機(jī)數(shù)
return String.join("", list) + randomNumber(2);
}
/**
* 生成指定長(zhǎng)度的一個(gè)數(shù)字字符串
*
* @param num
* @return
*/
public static String randomNumber(int num) {
if (num < 1) {
num = 1;
}
Random random = new Random();
StringBuilder str = new StringBuilder();
for (int i = 0; i < num; i++) {
str.append(random.nextInt(10));
}
return str.toString();
}
}
SnowflakeIdUtils:
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.Date;
/**
* Twitter_Snowflake<br>
* SnowFlake的結(jié)構(gòu)如下(每部分用-分開(kāi)):<br>
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
* 1位標(biāo)識(shí)具篇,由于long基本類(lèi)型在Java中是帶符號(hào)的,最高位是符號(hào)位凌埂,正數(shù)是0驱显,負(fù)數(shù)是1,所以id一般是正數(shù)瞳抓,最高位是0<br>
* 41位時(shí)間截(毫秒級(jí))埃疫,注意,41位時(shí)間截不是存儲(chǔ)當(dāng)前時(shí)間的時(shí)間戳孩哑,而是存儲(chǔ)時(shí)間戳的差值(當(dāng)前時(shí)間戳 - 開(kāi)始時(shí)間戳)
* 得到的值)栓霜,這里的的開(kāi)始時(shí)間戳,一般是我們的id生成器開(kāi)始使用的時(shí)間横蜒,由我們程序來(lái)指定的(如下下面程序IdWorker類(lèi)的startTime屬性)胳蛮。41位的時(shí)間戳,可以使用69年丛晌,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
* 10位的數(shù)據(jù)機(jī)器位仅炊,可以部署在1024個(gè)節(jié)點(diǎn),包括5位datacenterId和5位workerId<br>
* 12位序列澎蛛,毫秒內(nèi)的計(jì)數(shù)抚垄,12位的計(jì)數(shù)順序號(hào)支持每個(gè)節(jié)點(diǎn)每毫秒(同一機(jī)器,同一時(shí)間截)產(chǎn)生4096個(gè)ID序號(hào)<br>
* 加起來(lái)剛好64位,為一個(gè)Long型督勺。<br>
* SnowFlake的優(yōu)點(diǎn)是渠羞,整體上按照時(shí)間自增排序,并且整個(gè)分布式系統(tǒng)內(nèi)不會(huì)產(chǎn)生ID碰撞(由數(shù)據(jù)中心ID和機(jī)器ID作區(qū)分)智哀,并且效率較高次询,經(jīng)測(cè)試,SnowFlake每秒能夠產(chǎn)生26萬(wàn)ID左右瓷叫。
*/
public class SnowflakeIdUtils {
/** 開(kāi)始時(shí)間截 (2021-01-01) */
private final long twepoch = 1609430400000L;
/** 機(jī)器id所占的位數(shù) */
private final long workerIdBits = 5L;
/** 數(shù)據(jù)標(biāo)識(shí)id所占的位數(shù) */
private final long dataCenterIdBits = 5L;
/** 支持的最大機(jī)器id屯吊,結(jié)果是31 (這個(gè)移位算法可以很快的計(jì)算出幾位二進(jìn)制數(shù)所能表示的最大十進(jìn)制數(shù)) */
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
/** 支持的最大數(shù)據(jù)標(biāo)識(shí)id,結(jié)果是31 */
private final long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits);
/** 序列在id中占的位數(shù) */
private final long sequenceBits = 12L;
/** 機(jī)器ID向左移12位 */
private final long workerIdShift = sequenceBits;
/** 數(shù)據(jù)標(biāo)識(shí)id向左移17位(12+5) */
private final long dataCenterIdShift = sequenceBits + workerIdBits;
/** 時(shí)間截向左移22位(5+5+12) */
private final long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;
/** 生成序列的掩碼摹菠,這里為4095 (0b111111111111=0xfff=4095) */
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
/** 工作機(jī)器ID(0~31) */
private long workerId;
/** 數(shù)據(jù)中心ID(0~31) */
private long dataCenterId;
/** 毫秒內(nèi)序列(0~4095) */
private long sequence = 0L;
/** 上次生成ID的時(shí)間截 */
private long lastTimestamp = -1L;
private static SnowflakeIdUtils idWorker;
static {
idWorker = new SnowflakeIdUtils(getWorkId(), getDataCenterId());
}
/**
* 構(gòu)造函數(shù)
* @param workerId 工作ID (0~31)
* @param dataCenterId 數(shù)據(jù)中心ID (0~31)
*/
public SnowflakeIdUtils(long workerId, long dataCenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("workerId can't be greater than %d or less than 0", maxWorkerId));
}
if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
throw new IllegalArgumentException(String.format("dataCenterId can't be greater than %d or less than 0", maxDataCenterId));
}
this.workerId = workerId;
this.dataCenterId = dataCenterId;
}
/**
* 獲得下一個(gè)ID (該方法是線程安全的)
* @return SnowflakeId
*/
public synchronized long nextId() {
long timestamp = timeGen();
//如果當(dāng)前時(shí)間小于上一次ID生成的時(shí)間戳盒卸,說(shuō)明系統(tǒng)時(shí)鐘回退過(guò)這個(gè)時(shí)候應(yīng)當(dāng)拋出異常
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
//如果是同一時(shí)間生成的,則進(jìn)行毫秒內(nèi)序列
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
//毫秒內(nèi)序列溢出
if (sequence == 0) {
//阻塞到下一個(gè)毫秒,獲得新的時(shí)間戳
timestamp = tilNextMillis(lastTimestamp);
}
}
//時(shí)間戳改變次氨,毫秒內(nèi)序列重置
else {
sequence = 0L;
}
//上次生成ID的時(shí)間截
lastTimestamp = timestamp;
//移位并通過(guò)或運(yùn)算拼到一起組成64位的ID
return ((timestamp - twepoch) << timestampLeftShift)
| (dataCenterId << dataCenterIdShift)
| (workerId << workerIdShift)
| sequence;
}
/**
* 阻塞到下一個(gè)毫秒蔽介,直到獲得新的時(shí)間戳
* @param lastTimestamp 上次生成ID的時(shí)間截
* @return 當(dāng)前時(shí)間戳
*/
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
* 返回以毫秒為單位的當(dāng)前時(shí)間
* @return 當(dāng)前時(shí)間(毫秒)
*/
protected long timeGen() {
return System.currentTimeMillis();
}
private static Long getWorkId(){
try {
String hostAddress = Inet4Address.getLocalHost().getHostAddress();
int[] ints = StringUtils.toCodePoints(hostAddress);
int sums = 0;
for(int b : ints) {
sums += b;
}
return (long)(sums % 32);
} catch (UnknownHostException e) {
// 如果獲取失敗,則使用隨機(jī)數(shù)備用
return RandomUtils.nextLong(0,31);
}
}
private static Long getDataCenterId(){
int[] ints = StringUtils.toCodePoints(SystemUtils.getHostName());
int sums = 0;
for (int i: ints) {
sums += i;
}
return (long)(sums % 32);
}
/**
* 靜態(tài)工具類(lèi)
*
* @return
*/
public static synchronized Long generateId(){
long id = idWorker.nextId();
return id;
}
/** 測(cè)試 */
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
long startTime = System.nanoTime();
for (int i = 0; i < 5; i++) {
long id = SnowflakeIdUtils.generateId();
System.out.println(id);
}
System.out.println((System.nanoTime()-startTime)/1000000+"ms");
Date date = DateUtils.stringToDate("2021-01-01 00:00:00");
System.out.println(date.getTime());
}
}