1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
@Bean @Intercepts(value = { @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}), @Signature(type = Executor.class, method = "queryCursor", args = {MappedStatement.class, Object.class, RowBounds.class}), }) public class DataSourceInterceptor implements Interceptor, ApplicationListener<ContextRefreshedEvent> {
private final Map<String, String> CACHE = new HashMap<>(128);
@Override public Object intercept(Invocation invocation) throws Throwable { String dataSource = CACHE.get(((MappedStatement) invocation.getArgs()[0]).getId()); if (dataSource == null) { dataSource = DataSources.DB1; } DataSourceContext.set(dataSource); try { return invocation.proceed(); } finally { DataSourceContext.remove(); } }
@Override public Object plugin(Object target) { return Plugin.wrap(target, this); }
@Override public void setProperties(Properties properties) { }
@Override public void onApplicationEvent(ContextRefreshedEvent event) { Map<String, SqlSessionFactory> factories = event.getApplicationContext().getBeansOfType(SqlSessionFactory.class); if (factories.isEmpty()) { return; } for (SqlSessionFactory factory : factories.values()) { Collection<Class<?>> mappers = factory.getConfiguration().getMapperRegistry().getMappers(); for (Class<?> mapper : mappers) { RoutingDataSource annotation = mapper.getAnnotation(RoutingDataSource.class); String dataSource = annotation == null ? DataSources.DB1 : annotation.value(); Method[] methods = mapper.getMethods(); for (Method method : methods) { CACHE.put(mapper.getName() + "." + method.getName(), dataSource); } } } } }
|