|
| 1 | +package com.github.cadecode.uniboot.common.plugin.datasource.config; |
| 2 | + |
| 3 | +import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; |
| 4 | +import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider; |
| 5 | +import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider; |
| 6 | +import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration; |
| 7 | +import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties; |
| 8 | +import lombok.RequiredArgsConstructor; |
| 9 | +import org.apache.shardingsphere.driver.jdbc.adapter.AbstractDataSourceAdapter; |
| 10 | +import org.springframework.boot.autoconfigure.AutoConfigureBefore; |
| 11 | +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; |
| 12 | +import org.springframework.context.annotation.Bean; |
| 13 | +import org.springframework.context.annotation.Configuration; |
| 14 | +import org.springframework.context.annotation.Lazy; |
| 15 | +import org.springframework.context.annotation.Primary; |
| 16 | + |
| 17 | +import javax.annotation.Resource; |
| 18 | +import javax.sql.DataSource; |
| 19 | +import java.util.HashMap; |
| 20 | +import java.util.Map; |
| 21 | + |
| 22 | +/** |
| 23 | + * Sharding JDBC 配置 |
| 24 | + * |
| 25 | + * @author Cade Li |
| 26 | + * @since 2023/11/29 |
| 27 | + */ |
| 28 | +@RequiredArgsConstructor |
| 29 | +@ConditionalOnProperty(name = "spring.shardingsphere.enabled", havingValue = "true") |
| 30 | +@AutoConfigureBefore(DynamicDataSourceAutoConfiguration.class) |
| 31 | +@Configuration |
| 32 | +public class ShardingJdbcConfig { |
| 33 | + |
| 34 | + public static final String SHARDING_DATA_SOURCE_NAME = "sharding"; |
| 35 | + |
| 36 | + private final DynamicDataSourceProperties properties; |
| 37 | + |
| 38 | + @Lazy |
| 39 | + @Resource |
| 40 | + private AbstractDataSourceAdapter shardingSphereDataSource; |
| 41 | + |
| 42 | + @Bean |
| 43 | + public DynamicDataSourceProvider dynamicDataSourceProvider() { |
| 44 | + return new AbstractDataSourceProvider() { |
| 45 | + @Override |
| 46 | + public Map<String, DataSource> loadDataSources() { |
| 47 | + HashMap<String, DataSource> dataSourceMap = new HashMap<>(); |
| 48 | + dataSourceMap.put(SHARDING_DATA_SOURCE_NAME, shardingSphereDataSource); |
| 49 | + return dataSourceMap; |
| 50 | + } |
| 51 | + }; |
| 52 | + } |
| 53 | + |
| 54 | + @Primary |
| 55 | + @Bean |
| 56 | + public DataSource dataSource() { |
| 57 | + DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource(); |
| 58 | + dataSource.setPrimary(properties.getPrimary()); |
| 59 | + dataSource.setStrict(properties.getStrict()); |
| 60 | + dataSource.setStrategy(properties.getStrategy()); |
| 61 | + dataSource.setP6spy(properties.getP6spy()); |
| 62 | + dataSource.setSeata(properties.getSeata()); |
| 63 | + return dataSource; |
| 64 | + } |
| 65 | +} |
0 commit comments