Mybatis-插件實(shí)現(xiàn)租戶分離

by shihang.mai

1. mybatis層次結(jié)構(gòu)

mybatis層次圖.png

2. 插件實(shí)現(xiàn)

代碼思路,就是利用mybatis插件,在上面流程中進(jìn)行攔截,做自己的業(yè)務(wù)邏輯


mybatis租戶隔離.png

3. 代碼實(shí)現(xiàn)(核心步驟)

注解:是否開啟多租戶和是否開啟敏感sql

@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.TYPE})
public @interface MultiTenant {
    /**
     * 是否開啟使用框架層的多租戶鸳惯,默認(rèn)開啟
     * @return
     */
    boolean flag() default true;

}
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.TYPE})
public @interface SqlLimit {
    /**
     * 項(xiàng)目默認(rèn)禁用drop,create,alter,truncate sql
     * @return
     */
    boolean flag() default true;

}

核心配置類PluginConfiguration螟炫,需要boostrap中加入

@Configuration
public class PluginConfiguration {

    @Resource
    private BeanFactory beanFactory;

    //為了提速,不是重點(diǎn)
    @Bean
    public MultiTenantMapperCacheManager multiTenantMapperCacheManager() {

        return new MultiTenantMapperCacheManager();
    }

     //為了提速,不是重點(diǎn)
    @Bean
    public SqlLimitMapperCacheManager sqlLimitMapperCacheManager() {
        return new SqlLimitMapperCacheManager();
    }

    @Bean
    public Interceptor tenantInterceptor(){
        Interceptor interceptor = new TenantInterceptor(multiTenantMapperCacheManager());
        Properties properties = new Properties();
        properties.setProperty(TenantConstant.DIALECT, "postgresql");
        properties.setProperty(TenantConstant.TENANTID_FIELD, TenantConstant.TENANT_ID);
        interceptor.setProperties(properties);
        return interceptor;
    }

    @Bean
    public Interceptor sqlCheckInterceptor(){
        Interceptor interceptor = new SqlCheckInterceptor(sqlLimitMapperCacheManager());
        Properties properties = new Properties();
        properties.setProperty(TenantConstant.DIALECT, "postgresql");
        interceptor.setProperties(properties);
        return interceptor;
    }


    /**
     * 多租戶線程池宣肚,為了解決異步線程租戶id的傳遞
     * @return MultiTenantLazyTraceThreadPoolTaskExecutor
     */
    @Bean
    public MultiTenantLazyTraceThreadPoolTaskExecutor multiTenantLazyTraceThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(3);
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        threadPoolTaskExecutor.setMaxPoolSize(5);
        threadPoolTaskExecutor.setQueueCapacity(1000);
        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
        threadPoolTaskExecutor.setThreadNamePrefix("base-multitsenant-pool-");
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());

        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskExecutor.initialize();
        return new MultiTenantLazyTraceThreadPoolTaskExecutor(this.beanFactory, threadPoolTaskExecutor);
    }

}

租戶攔截類TenantInterceptor

@Intercepts({
        @Signature(type = Executor.class, method = "update",
                args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
})
@Order(-20)
public class TenantInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(TenantInterceptor.class);
    /**
     * 當(dāng)前數(shù)據(jù)庫(kù)的方言
     */
    private String dialect;
    /**
     * 多租戶字段名稱
     */
    private String tenantIdField;

    private SqlConditionHelper conditionHelper;
    private SqlLimitHelper sqlLimitHelper;
    private AnnotationHelper annotationHelper;
    private final MultiTenantMapperCacheManager multiTenantMapperCacheManager;

    public TenantInterceptor(MultiTenantMapperCacheManager multiTenantMapperCacheManager) {
        this.multiTenantMapperCacheManager = multiTenantMapperCacheManager;

    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        String tenantId = MultiTenantHolders.getTenantId();
        //租戶id為空時(shí)不做處理
        if (StringUtils.isBlank(tenantId)) {
            //todo 測(cè)試tenant_id暫時(shí)固定
            tenantId = "0210000001";
            //return invocation.proceed();
        }

        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        BoundSql boundSql = ms.getBoundSql(parameter);
        //判斷調(diào)用棧的mapper類跟方法是否有注解
        ClazzMethodInfo clazzMethodInfo = annotationHelper.getClassAndMethod(ms.getId());

        boolean flag = checkAnnotation(clazzMethodInfo);
        logger.info("old sql:{}", boundSql.getSql());

        if (flag) {
            String newSql = addTenantCondition(boundSql.getSql(), tenantId);
            logger.info("new sql:{}", newSql);
            //重新構(gòu)造MappedStatement
            buildMappedStatement(ms, args, newSql);
        }
        return invocation.proceed();
    }

    /**
     * 重新構(gòu)造mappedStatement
     * @param mappedStatement
     * @param args
     * @param sql
     */
    private void buildMappedStatement(MappedStatement mappedStatement, final Object[] args, String sql) {
        // 獲取攔截方法的參數(shù)
        BoundSql currentBoundSql = mappedStatement.getBoundSql(args[1]);
        BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), sql,
                currentBoundSql.getParameterMappings(), currentBoundSql.getParameterObject());
        // 把新的查詢放到statement里
        MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
        for (ParameterMapping mapping : currentBoundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (currentBoundSql.hasAdditionalParameter(prop)) {
                newBoundSql.setAdditionalParameter(prop, currentBoundSql.getAdditionalParameter(prop));
            }
        }
        args[0] = newMs;
    }

    private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(ms.getKeyProperties()[0]);
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }


    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    /**
     * 設(shè)置屬性
     * @Param properties 注入屬性參數(shù)
     */
    @Override
    public void setProperties(Properties properties) {
        dialect = properties.getProperty(TenantConstant.DIALECT);
        if (StringUtils.isBlank(dialect)) {
            throw new IllegalArgumentException("MultiTenantPlugin need dialect property value");
        }
        tenantIdField = properties.getProperty(TenantConstant.TENANTID_FIELD);
        if (StringUtils.isBlank(tenantIdField)) {
            throw new IllegalArgumentException("MultiTenantPlugin need tenantIdField property value");
        }
        //多租戶條件字段決策器
        conditionHelper = new SqlConditionHelper(() -> false);
        sqlLimitHelper = new SqlLimitHelper();
        annotationHelper = new AnnotationHelper();
    }


    /**
     * 校驗(yàn)注解 注解可作用在類與方法上,方法注解優(yōu)先于類注解
     * @param data 類方法信息
     * @return true/false
     */
    private boolean checkAnnotation(ClazzMethodInfo data) {
        if (Objects.isNull(data) || Objects.isNull(data.getMethodName()) || Objects.isNull(data.getClassName())) {
            return false;
        }

        String namespace = data.getNamespace();
        String cacheKey = getCacheKey(namespace);
        if (StringUtils.isNotEmpty(cacheKey)) {
            return Boolean.valueOf(cacheKey);
        }
        MultiTenant annotation = annotationHelper.checkAnnotation(data, MultiTenant.class);
        if (Objects.isNull(annotation)) {
            setCacheKey(namespace, false);
            return false;
        }
        setCacheKey(namespace, annotation.flag());
        return annotation.flag();
    }

//    private boolean checkAnnotation(ClazzMethodInfo data) {

        /*if (Objects.isNull(data) || Objects.isNull(data.getMethodName()) || Objects.isNull(data.getClassName())) {
            return false;
        }
        String namespace = data.getNamespace();
        //緩存校驗(yàn)悠栓,定位到緩存值直接返回
        String cacheKey = getCacheKey(namespace);
        if (StringUtils.isNotEmpty(cacheKey)) {
            return Boolean.valueOf(cacheKey);
        }
        try {
            //攔截方法級(jí)別的注解
            Method[] methods = Class.forName(data.getClassName()).getMethods();
            for (int i = 0; i < methods.length; i++) {
                if (data.getMethodName().equals(methods[i].getName())) {
                    MultiTenant annotation = methods[i].getAnnotation(MultiTenant.class);
                    if (Objects.nonNull(annotation)) {
                        setCacheKey(namespace, annotation.flag());
                        return annotation.flag();
                    }
                }
            }
            //攔截類級(jí)別的注解霉涨,在方法級(jí)別沒(méi)有定位到注解按价,才去定位類注解
            MultiTenant annotation = Class.forName(data.getClassName()).getAnnotation(MultiTenant.class);
            if (Objects.isNull(annotation)) {
                setCacheKey(namespace, false);
                return false;
            }
            return annotation.flag();
        } catch (ClassNotFoundException e) {
            ExceptionLogger.log(e);
        }
        setCacheKey(namespace, false);*/
//        return false;
//    }

    private void setCacheKey(String namespace, boolean flag) {
        logger.info("設(shè)置annotation緩存:{}, flag:{}", namespace, flag);
        multiTenantMapperCacheManager.update(namespace, flag);
    }
    private String getCacheKey(String namespace) {
        logger.info("get annotation緩存:{}", namespace);
        return multiTenantMapperCacheManager.get(namespace);
    }

    /**
     * 給sql語(yǔ)句where添加租戶id過(guò)濾條件
     * @param sql      要添加過(guò)濾條件的sql語(yǔ)句
     * @param tenantId 當(dāng)前的租戶id
     * @return 添加條件后的sql語(yǔ)句
     */
    private String addTenantCondition(String sql, String tenantId) {
        //todo throw
        if (StringUtils.isBlank(sql) || StringUtils.isBlank(tenantIdField)) return sql;
        //處理limit offset size
        SqlLimiter sqlLimiter = sqlLimitHelper.splitLimitOffsetSize(sql);
        if (StringUtils.isNotEmpty(sqlLimiter.getSql())){
            sql = sqlLimiter.getSql();
        }

        List<SQLStatement> statementList = SQLUtils.parseStatements(sql, dialect);
        if (CollectionUtils.isEmpty(statementList)) return sql;

        SQLStatement sqlStatement = statementList.get(0);
        conditionHelper.addStatementCondition(sqlStatement, tenantIdField, tenantId);
        String sqllimit = StringUtils.isNotEmpty(sqlLimiter.getLimit())?" "+sqlLimiter.getLimit():"";
        return SQLUtils.toSQLString(statementList, DbType.postgresql) + sqllimit;
    }
}

敏感sql攔截類SqlCheckInterceptor

@Intercepts({
        /*@Signature(type = StatementHandler.class, method = "update",
                args = {Statement.class}),
        @Signature(type = StatementHandler.class, method = "query",
                args = {Statement.class, ResultHandler.class}),*/
        @Signature(type = StatementHandler.class, method = "prepare",
                args = {Connection.class, Integer.class}),
})
@Order(-10)
public class SqlCheckInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(SqlCheckInterceptor.class);

    /**
     * 當(dāng)前數(shù)據(jù)庫(kù)的方言
     */
    private String dialect;

    private SqlConditionHelper conditionHelper;
    private SqlLimitHelper sqlLimitHelper;
    private AnnotationHelper annotationHelper;

    private final SqlLimitMapperCacheManager sqlLimitMapperCacheManager;

    public SqlCheckInterceptor(SqlLimitMapperCacheManager sqlLimitMapperCacheManager) {
        this.sqlLimitMapperCacheManager = sqlLimitMapperCacheManager;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 獲取代理對(duì)象
        StatementHandler target = (StatementHandler) invocation.getTarget();
        // 獲取sql語(yǔ)句的id(id取法直接通過(guò)getter方法獲取,因此這里通過(guò)反射進(jìn)行獲取)
        MetaObject metaObject = MetaObject.forObject(target, SystemMetaObject.DEFAULT_OBJECT_FACTORY,
                SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory());
        String id = (String) metaObject.getValue("delegate.mappedStatement.id");
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        logger.info("old sql:{}", boundSql.getSql());

        //判斷調(diào)用棧的mapper類跟方法是否有注解
        ClazzMethodInfo clazzMethodInfo = annotationHelper.getClassAndMethod(id);
        boolean flag = checkAnnotation(clazzMethodInfo);
        //攔截敏感sql
        if (flag) {
            checkCondition(boundSql.getSql());
        }
        return invocation.proceed();
    }

    /**
     * 校驗(yàn)注解 注解可作用在類與方法上笙瑟,方法注解優(yōu)先于類注解
     * @param data 類方法信息
     * @return true/false
     */
    private boolean checkAnnotation(ClazzMethodInfo data) {
        if (Objects.isNull(data) || Objects.isNull(data.getMethodName()) || Objects.isNull(data.getClassName())) {
            return false;
        }

        String namespace = data.getNamespace();
        String cacheKey = getCacheKey(namespace);
        if (StringUtils.isNotEmpty(cacheKey)) {
            return Boolean.valueOf(cacheKey);
        }
        SqlLimit annotation = annotationHelper.checkAnnotation(data, SqlLimit.class);
        if (Objects.isNull(annotation)) {
            setCacheKey(namespace, false);
            return false;
        }
        setCacheKey(namespace, annotation.flag());
        return annotation.flag();
    }

    private void setCacheKey(String namespace, boolean flag) {
        logger.info("設(shè)置annotation緩存:{}, flag:{}", namespace, flag);
        sqlLimitMapperCacheManager.update(namespace, flag);
    }
    private String getCacheKey(String namespace) {
        logger.info("get annotation緩存:{}", namespace);
        return sqlLimitMapperCacheManager.get(namespace);
    }



    //todo throw
    private void checkCondition(String sql) {
        //update/delete no condition
        //drop/create/alter limit
        //update 條件沒(méi)有定位到索引
        if (StringUtils.isBlank(sql)) return;

        //處理limit offset size
        SqlLimiter sqlLimiter = sqlLimitHelper.splitLimitOffsetSize(sql);
        if (Objects.nonNull(sqlLimiter) && StringUtils.isNotEmpty(sqlLimiter.getSql())){
            sql = sqlLimiter.getSql();
        }
        List<SQLStatement> statementList = SQLUtils.parseStatements(sql, dialect);

        if (CollectionUtils.isEmpty(statementList)) return;

        SQLStatement sqlStatement = statementList.get(0);
        conditionHelper.checkNonCondition(sqlStatement);
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    /**
     * 設(shè)置屬性
     * @Param properties 注入屬性參數(shù)
     */
    @Override
    public void setProperties(Properties properties) {
        dialect = properties.getProperty("dialect");
        if (StringUtils.isBlank(dialect)) {
            throw new IllegalArgumentException("MultiTenantPlugin need dialect property value");
        }

        //決策器
        conditionHelper = new SqlConditionHelper(() -> false);
        sqlLimitHelper = new SqlLimitHelper();
        annotationHelper = new AnnotationHelper();
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末楼镐,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子往枷,更是在濱河造成了極大的恐慌框产,老刑警劉巖,帶你破解...
    沈念sama閱讀 210,978評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件错洁,死亡現(xiàn)場(chǎng)離奇詭異秉宿,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)屯碴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,954評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門描睦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人导而,你說(shuō)我怎么就攤上這事忱叭。” “怎么了今艺?”我有些...
    開封第一講書人閱讀 156,623評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵韵丑,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我虚缎,道長(zhǎng)埂息,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,324評(píng)論 1 282
  • 正文 為了忘掉前任遥巴,我火速辦了婚禮千康,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘铲掐。我一直安慰自己拾弃,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,390評(píng)論 5 384
  • 文/花漫 我一把揭開白布摆霉。 她就那樣靜靜地躺著豪椿,像睡著了一般。 火紅的嫁衣襯著肌膚如雪携栋。 梳的紋絲不亂的頭發(fā)上搭盾,一...
    開封第一講書人閱讀 49,741評(píng)論 1 289
  • 那天,我揣著相機(jī)與錄音婉支,去河邊找鬼鸯隅。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的蝌以。 我是一名探鬼主播炕舵,決...
    沈念sama閱讀 38,892評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼跟畅!你這毒婦竟也來(lái)了咽筋?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,655評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤徊件,失蹤者是張志新(化名)和其女友劉穎奸攻,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體虱痕,經(jīng)...
    沈念sama閱讀 44,104評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡舞箍,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了皆疹。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片疏橄。...
    茶點(diǎn)故事閱讀 38,569評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖略就,靈堂內(nèi)的尸體忽然破棺而出捎迫,到底是詐尸還是另有隱情,我是刑警寧澤表牢,帶...
    沈念sama閱讀 34,254評(píng)論 4 328
  • 正文 年R本政府宣布窄绒,位于F島的核電站,受9級(jí)特大地震影響崔兴,放射性物質(zhì)發(fā)生泄漏彰导。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,834評(píng)論 3 312
  • 文/蒙蒙 一敲茄、第九天 我趴在偏房一處隱蔽的房頂上張望位谋。 院中可真熱鬧,春花似錦堰燎、人聲如沸掏父。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,725評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)赊淑。三九已至,卻和暖如春仅讽,著一層夾襖步出監(jiān)牢的瞬間陶缺,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,950評(píng)論 1 264
  • 我被黑心中介騙來(lái)泰國(guó)打工洁灵, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留饱岸,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,260評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像伶贰,于是被迫代替她去往敵國(guó)和親蛛砰。 傳聞我的和親對(duì)象是個(gè)殘疾皇子罐栈,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,446評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容