首页>代码>springboot2 aop注解配置多个数据库并实现多数据源动态切换和数据库读写分离>/read-write-splitting/src/main/java/cn/jsxwsl/www/config/datasource/DataSourceTheadLocal.java
package cn.jsxwsl.www.config.datasource;

import cn.jsxwsl.www.nums.DBTypeEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: 佚名
 * @Date: 2020/3/25 18:30
 */
@Slf4j
public class DataSourceTheadLocal {
    private static final ThreadLocal<DBTypeEnum> dbTypeEnumThreadLocal = new ThreadLocal<>();

    private static final AtomicInteger counter = new AtomicInteger(-1);

    /**
     * 设置当前线程中的数据源 key, 由 aop 切面调用
     *
     * @param dbType DBTypeEnum
     */
    public static void set(DBTypeEnum dbType) {
        dbTypeEnumThreadLocal.set(dbType);
    }

    /**
     * 获取当前线程的数据库key
     *
     * @return DBTypeEnum
     */
    public static DBTypeEnum get() {
        return dbTypeEnumThreadLocal.get();
    }

    public static void master() {
        set(DBTypeEnum.MASTER);
        log.info(" ========> this is master");
    }

    public static void slave() {
        //  轮询
        int index = counter.getAndIncrement() % 2;
        if (counter.get() > 9999) {
            counter.set(-1);
        }
        if (index == 0) {
            set(DBTypeEnum.SLAVE1);
            log.info(" ========> this is slave1");
        } else {
            set(DBTypeEnum.SLAVE2);
            log.info(" ========> this is slave2");
        }
    }


}
最近下载更多
lironggang  LV38 2023年7月11日
HANCW  LV8 2023年3月12日
1529860026  LV24 2022年10月18日
1234mama  LV19 2022年4月11日
fellowfun  LV12 2021年8月12日
mudingc木钉  LV30 2021年6月16日
annazhang  LV29 2021年6月11日
pxqtsht  LV15 2021年5月16日
xhmpmail  LV17 2021年2月22日
听说过  LV17 2021年1月4日
最近浏览更多
1358849392  LV21 1月22日
漫步的海星  LV4 2023年9月21日
lironggang  LV38 2023年7月11日
HANCW  LV8 2023年3月12日
xiahaoyu  LV8 2023年2月25日
xp95323  LV14 2022年9月21日
绘飛的渔 2022年8月2日
暂无贡献等级
fangen0005  LV25 2022年4月17日
zhang6332 2022年4月6日
暂无贡献等级
1214066599  LV8 2022年4月4日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友