001/*
002 *  Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com).
003 *  <p>
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package com.mybatisflex.core.datasource;
017
018import java.util.function.Supplier;
019
020/**
021 * @author michael
022 */
023public class DataSourceKey {
024
025    /**
026     * 通过注解设置的 key
027     */
028    private static ThreadLocal<String> annotationKeyThreadLocal = new ThreadLocal<>();
029
030    /**
031     * 通过手动编码指定的 key
032     */
033    private static ThreadLocal<String> manualKeyThreadLocal = new ThreadLocal<>();
034
035    public static String manualKey;
036
037    private DataSourceKey() {
038    }
039
040    public static void use(String dataSourceKey) {
041        manualKeyThreadLocal.set(dataSourceKey.trim());
042    }
043
044    public static void useWithAnnotation(String dataSourceKey) {
045        annotationKeyThreadLocal.set(dataSourceKey.trim());
046    }
047
048    public static <T> T use(String dataSourceKey, Supplier<T> supplier) {
049        try {
050            use(dataSourceKey);
051            return supplier.get();
052        } finally {
053            clear();
054        }
055    }
056
057    public static void use(String dataSourceKey, Runnable runnable) {
058        try {
059            use(dataSourceKey);
060            runnable.run();
061        } finally {
062            clear();
063        }
064    }
065
066    public static void clear() {
067        annotationKeyThreadLocal.remove();
068        manualKeyThreadLocal.remove();
069    }
070
071    public static String getByAnnotation() {
072        return annotationKeyThreadLocal.get();
073    }
074
075    public static String getByManual() {
076        return manualKeyThreadLocal.get();
077    }
078
079    public static String get() {
080        String key = manualKeyThreadLocal.get();
081        return key != null ? key : annotationKeyThreadLocal.get();
082    }
083
084    public static void setAnnotationKeyThreadLocal(ThreadLocal<String> annotationKeyThreadLocal) {
085        DataSourceKey.annotationKeyThreadLocal = annotationKeyThreadLocal;
086    }
087
088    public static void setManualKeyThreadLocal(ThreadLocal<String> manualKeyThreadLocal) {
089        DataSourceKey.manualKeyThreadLocal = manualKeyThreadLocal;
090    }
091}