Mybatis Plus 动态分表拦截器配置

定义注解
package com.*.*.annotation;

import java.lang.annotation.*;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DynamicTableService {
    String function() default "注解作用描述";
}

定义切面逻辑
package com.*.*.aspect;


import com.*.*.aspect.helper.DynamicTableHelper;
import lombok.SneakyThrows;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class DynamicTableServiceAspect {


    @Before("@within(com.*.*.annotation.DynamicTableService) && execution(* *(..))")
    public @SneakyThrows void before(JoinPoint joinPoint) {
        Object value = joinPoint.getArgs()[0];
        if (value instanceof Date taskCreateTime) {
            DynamicTableHelper.setHashKey(taskCreateTime);
        } else if (value instanceof String taskCode) {
            DynamicTableHelper.setHashKey(taskCode);
        }
    }


    @AfterReturning("@within(com.*.*.annotation.DynamicTableService) && execution(* *(..))")
    public void afterReturning() {
        DynamicTableHelper.remove();
    }


}
定义实体类
@Data
@TableName(value = "apple_", autoResultMap = true)
public class Apple {
    @TableId(type = IdType.ASSIGN_ID)
    private String code;
}
定义实体业务逻辑层并切面这个类的方法
package com.*.*.repository;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Repository
@RequiredArgsConstructor
@DynamicTableService
public class AppleRepository extends CrudRepository<AppleMapper, Apple> {

    private final AppleMapper appleMapper;

    public List<Apple> find(String appleCode) {
        return baseMapper.selectById(appleCode);
    }
定义分表帮助工具
package com.*.*.aspect.helper;

import com.*.*.utils.DateUtil;

import java.util.Date;

public class DynamicTableHelper {

    private static final ThreadLocal<String> THREAD_LOCAL_TABLE_HASH_KEY = new ThreadLocal<>();

    public static void setHashKey(String code) {
        THREAD_LOCAL_TABLE_HASH_KEY.set(code);
    }

    public static String getHashKey() {
        return THREAD_LOCAL_TABLE_HASH_KEY.get();
    }

    public static void setHashKey(Date createTime) {
        THREAD_LOCAL_TABLE_HASH_KEY.set(DateUtil.format(createTime, DateUtil.yyyyMMddHH));
    }

    public static void remove() {
        THREAD_LOCAL_TABLE_HASH_KEY.remove();
    }

}

自定义Mybatis Plus拦截器配置
package com.*.*.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.*.*.aspect.helper.DynamicTableHelper;
import com.*.*.utils.DateUtil;
import com.*.*.utils.PartitionByMurmurHashUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.List;

@Setter
@Getter
@Configuration
@Slf4j
public class MybatisPlusDynamicTableConfig {

    static final List<String> DYNAMIC_TABLES_HASH = List.of("apple_");

    static final List<String> DYNAMIC_TABLES_TIME = List.of("banana_");

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
            String hashKey = DynamicTableHelper.getHashKey();
            if (DYNAMIC_TABLES_HASH.contains(tableName)) {
                int hashed = PartitionByMurmurHashUtil.hash(hashKey, 20);
                return tableName + hashed;
            }
            if (DYNAMIC_TABLES_TIME.contains(tableName)) {
                if (Integer.parseInt(hashKey) > startTime) {
                    return tableName + "_" + hashKey.substring(0, 6);
                }
            }
            return tableName;
        });
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容