您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“SpringBoot多數(shù)據(jù)源配置的過(guò)程是什么”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“SpringBoot多數(shù)據(jù)源配置的過(guò)程是什么”吧!
多數(shù)據(jù)源的核心就是向 IOC 容器注入 AbstractRoutingDataSource 和如何切換數(shù)據(jù)源。注入的方式可以是注冊(cè) BeanDefinition 或者是構(gòu)建好的 Bean,切換數(shù)據(jù)源的方式可以是方法參數(shù)或者是注解切換(其他的沒(méi)想象出來(lái)),具體由需求決定。
我的需求是統(tǒng)計(jì)多個(gè)庫(kù)的數(shù)據(jù),將結(jié)果寫入另一個(gè)數(shù)據(jù)庫(kù),統(tǒng)計(jì)的數(shù)據(jù)庫(kù)數(shù)量是不定的,無(wú)法通過(guò) @Bean 直接注入,又是統(tǒng)計(jì)任務(wù),DAO 層注解切換無(wú)法滿足,因此選擇注冊(cè)(AbstractRoutingDataSource 的)BeanDefinition 和方法參數(shù)切換來(lái)實(shí)現(xiàn)。下面以統(tǒng)計(jì)統(tǒng)計(jì)中日韓用戶到結(jié)果庫(kù)為例。
master 為結(jié)果庫(kù),其他為被統(tǒng)計(jì)的數(shù)據(jù)庫(kù)(china、japan 可以用枚舉唯一標(biāo)識(shí),當(dāng)然也可以用 String):
dynamic: dataSources: master: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/result?useUnicode=true&characterEncoding=utf8xxxxxxxx username: root password: 123456 china: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/china?useUnicode=true&characterEncoding=utf8xxxxxxxx username: root password: 123456 japan: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/japan?useUnicode=true&characterEncoding=utf8xxxxxxxx username: root password: 123456 korea: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/korea?useUnicode=true&characterEncoding=utf8xxxxxxxx username: root password: 123456
對(duì)應(yīng)的配置類:
package com.statistics.dynamicds.core.config; import com.statistics.dynamicds.core.Country; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import java.util.Map; import static com.statistics.dynamicds.core.config.MultiDataSourceProperties.PREFIX; @Data @Configuration @ConfigurationProperties(prefix = PREFIX) public class MultiDataSourceProperties { public static final String PREFIX = "dynamic"; private Map<Country, DataSourceProperties> dataSources; @Data public static class DataSourceProperties { private String driverClassName; private String url; private String username; private String password; } } package com.statistics.dynamicds.core; public enum Country { MASTER("master", 0), CHINA("china", 86), JAPAN("japan", 81), KOREA("korea", 82), // 其他國(guó)家省略 private final String name; private final int id; Country(String name, int id) { this.name = name; this.id = id; } public int getId() { return id; } public String getName() { return name; } }
ORM 用的 JPA,SpringBoot 版本為 2.3.7.RELEASE,通過(guò) Lombok 簡(jiǎn)化 GetSet。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> <scope>provided</scope> </dependency>
Spring 的動(dòng)態(tài)數(shù)據(jù)源需要注入 AbstractRoutingDataSource,因?yàn)榕渲梦募斜唤y(tǒng)計(jì)數(shù)據(jù)源不是固定的,所以不能通過(guò) @Bean 注解注入,需要手動(dòng)構(gòu)建。
要在啟動(dòng)類加上 @Import(MultiDataSourceImportBeanDefinitionRegistrar.class)。
要在啟動(dòng)類加上 @Import(MultiDataSourceImportBeanDefinitionRegistrar.class)。
要在啟動(dòng)類加上 @Import(MultiDataSourceImportBeanDefinitionRegistrar.class),重要的事情寫三行。
package com.statistics.dynamicds.autoconfig; import com.statistics.dynamicds.core.DynamicDataSourceRouter; import com.statistics.dynamicds.core.Country; import com.statistics.dynamicds.core.config.MultiDataSourceProperties; import com.zaxxer.hikari.HikariDataSource; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.env.Environment; import org.springframework.core.type.AnnotationMetadata; import javax.annotation.Nonnull; import java.util.Map; import java.util.stream.Collectors; import static com.statistics.dynamicds.core.config.MultiDataSourceProperties.PREFIX; public class MultiDataSourceImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware { public static final String DATASOURCE_BEANNAME = "dynamicDataSourceRouter"; private Environment environment; @Override public void registerBeanDefinitions(@Nonnull AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { MultiDataSourceProperties multiDataSourceProperties = Binder.get(environment) .bind(PREFIX, MultiDataSourceProperties.class) .orElseThrow(() -> new RuntimeException("no found dynamicds config")); final HikariDataSource[] defaultTargetDataSource = {null}; Map<Country, HikariDataSource> targetDataSources = multiDataSourceProperties.getDataSources().entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, entry -> { MultiDataSourceProperties.DataSourceProperties dataSourceProperties = entry.getValue(); HikariDataSource dataSource = DataSourceBuilder.create() .type(HikariDataSource.class) .driverClassName(dataSourceProperties.getDriverClassName()) .url(dataSourceProperties.getUrl()) .username(dataSourceProperties.getUsername()) .password(dataSourceProperties.getPassword()) .build(); dataSource.setPoolName("HikariPool-" + entry.getKey()); if (Country.MASTER == entry.getKey()) { defaultTargetDataSource[0] = dataSource; } return dataSource; })); AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(DynamicDataSourceRouter.class) .addConstructorArgValue(defaultTargetDataSource[0]) .addConstructorArgValue(targetDataSources) .getBeanDefinition(); registry.registerBeanDefinition(DATASOURCE_BEANNAME, beanDefinition); } @Override public void setEnvironment(@Nonnull Environment environment) { this.environment = environment; } }
上面代碼中 MultiDataSourceProperties 不是由 @Resource 或者 @Autowired 獲取的是因?yàn)?ImportBeanDefinitionRegistrar 執(zhí)行的很早,此時(shí) @ConfigurationProperties 的配置參數(shù)類還沒(méi)有注入,因此要手動(dòng)獲?。?@ConfigurationProperties 注解是為了使 IOC 容器中其他 Bean 能獲取配置的 Country,以此來(lái)切換數(shù)據(jù)源)。
下面是 AbstractRoutingDataSource 的實(shí)現(xiàn)類 DynamicDataSourceRouter:
package com.statistics.dynamicds.core; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import java.util.Map; public class DynamicDataSourceRouter extends AbstractRoutingDataSource { public DynamicDataSourceRouter(Object defaultTargetDataSource, Map<Object, Object> targetDataSources) { this.setDefaultTargetDataSource(defaultTargetDataSource); this.setTargetDataSources(targetDataSources); } @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getLookupKey(); } }
數(shù)據(jù)源的切換由 DataSourceContextHolder 和切面 DynamicDataSourceAspect 控制:
package com.statistics.dynamicds.core; public class DataSourceContextHolder { private static final ThreadLocal<Country> HOLDER = ThreadLocal.withInitial(() -> Country.MASTER); public static void setLookupKey(Country lookUpKey) { HOLDER.set(lookUpKey); } public static Country getLookupKey() { return HOLDER.get(); } public static void clear() { HOLDER.remove(); } } package com.statistics.dynamicds.core; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class DynamicDataSourceAspect { @Pointcut("execution(* com.statistics.dao..*.*(..))") void aspect() { } @Around("aspect()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { for (Object arg : joinPoint.getArgs()) { if (arg instanceof Country) { DataSourceContextHolder.setLookupKey((Country) arg); break; } } try { return joinPoint.proceed(); }finally { DataSourceContextHolder.clear(); } } }
到此,相信大家對(duì)“SpringBoot多數(shù)據(jù)源配置的過(guò)程是什么”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。