From 5e4e64532f9a60db931e571cadd4af92b38f8f1d Mon Sep 17 00:00:00 2001 From: elijah Date: Sat, 27 Apr 2019 16:05:37 +0800 Subject: [PATCH] =?UTF-8?q?@BeanFactoryAware=20=E5=8E=BB=E6=B3=A8=E5=86=8C?= =?UTF-8?q?=E5=AF=B9=E8=B1=A1=20@?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/cn/iwuliao/ds/core/Db.java | 10 +- .../ds/core/{DbConf1.java => DbConf.java} | 6 +- .../cn/iwuliao/ds/core/DbContextHolder.java | 2 +- .../iwuliao/ds/core/DsScannerConfigurer.java | 137 +++++++++--------- src/main/resources/application.yml | 60 +++++--- 5 files changed, 120 insertions(+), 95 deletions(-) rename src/main/java/cn/iwuliao/ds/core/{DbConf1.java => DbConf.java} (54%) diff --git a/src/main/java/cn/iwuliao/ds/core/Db.java b/src/main/java/cn/iwuliao/ds/core/Db.java index d67eb7f..716c79c 100644 --- a/src/main/java/cn/iwuliao/ds/core/Db.java +++ b/src/main/java/cn/iwuliao/ds/core/Db.java @@ -1,10 +1,10 @@ package cn.iwuliao.ds.core; -import com.alibaba.druid.pool.DruidDataSource; import lombok.Getter; import lombok.Setter; import lombok.ToString; +import java.util.Map; import java.util.Properties; @Setter @@ -12,13 +12,9 @@ @ToString public class Db { -// private DruidDataSource master; -// private DruidDataSource slave; -// private DruidDataSource slave1; -// private Properties master; - private Properties slave; - private Properties slave1; + + private Map slaves; private String mapperLocations; private String typeHandlersPackage; diff --git a/src/main/java/cn/iwuliao/ds/core/DbConf1.java b/src/main/java/cn/iwuliao/ds/core/DbConf.java similarity index 54% rename from src/main/java/cn/iwuliao/ds/core/DbConf1.java rename to src/main/java/cn/iwuliao/ds/core/DbConf.java index 3bbe727..862f517 100644 --- a/src/main/java/cn/iwuliao/ds/core/DbConf1.java +++ b/src/main/java/cn/iwuliao/ds/core/DbConf.java @@ -1,6 +1,8 @@ package cn.iwuliao.ds.core; import lombok.*; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; import java.util.Map; import java.util.Properties; @@ -10,7 +12,9 @@ @ToString @NoArgsConstructor @AllArgsConstructor -public class DbConf1 { +@Configuration +@ConfigurationProperties(prefix = "druid2") +public class DbConf { private String poolType; diff --git a/src/main/java/cn/iwuliao/ds/core/DbContextHolder.java b/src/main/java/cn/iwuliao/ds/core/DbContextHolder.java index a036baa..50bd805 100644 --- a/src/main/java/cn/iwuliao/ds/core/DbContextHolder.java +++ b/src/main/java/cn/iwuliao/ds/core/DbContextHolder.java @@ -6,7 +6,7 @@ public class DbContextHolder { public enum DbType { - MASTER, SLAVE + MASTER, SLAVE, SLAVE1 } private static final ThreadLocal contextHolder = new ThreadLocal<>(); diff --git a/src/main/java/cn/iwuliao/ds/core/DsScannerConfigurer.java b/src/main/java/cn/iwuliao/ds/core/DsScannerConfigurer.java index e0b5a32..84f0e20 100644 --- a/src/main/java/cn/iwuliao/ds/core/DsScannerConfigurer.java +++ b/src/main/java/cn/iwuliao/ds/core/DsScannerConfigurer.java @@ -10,16 +10,27 @@ import org.springframework.beans.BeanMetadataAttribute; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.*; import org.springframework.beans.factory.parsing.DefaultsDefinition; import org.springframework.beans.factory.support.*; +import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.json.YamlJsonParser; import org.springframework.cglib.beans.BeanMap; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ConfigurationClassPostProcessor; +import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.MutablePropertySources; @@ -34,14 +45,17 @@ import org.yaml.snakeyaml.representer.Representer; import javax.sql.DataSource; +import java.sql.SQLException; +import java.time.LocalDateTime; import java.util.*; /** * */ @Component -public class DsScannerConfigurer { +public class DsScannerConfigurer implements BeanFactoryAware, Ordered, ApplicationContextAware { + private BeanFactory beanFactory; private static final String PREFIX = "druid2."; private static final String DRUID_DS_PROPS_PREFIX = "druid."; @@ -49,50 +63,38 @@ public class DsScannerConfigurer { private static final String MAPPERSCANNERCONFIGURER = "MapperScannerConfigurer"; public static final String SQLSESSIONFACTORY = "SqlSessionFactory"; - @Bean - public BeanDefinitionRegistryPostProcessor factory(final StandardServletEnvironment environment) { - - return new BeanDefinitionRegistryPostProcessor() { - @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { - MutablePropertySources propertySources = environment.getPropertySources(); - Properties properties = new Properties(); - propertySources.forEach(x -> { - Object source = x.getSource(); - if (source instanceof LinkedHashMap) { - LinkedHashMap props = (LinkedHashMap) source; - props.forEach((k, v) -> { - String key = k.toString(); - boolean druid2 = key.startsWith(PREFIX); - if (druid2) { - properties.put(key, v); - } - }); - } - }); - boolean empty = properties.isEmpty(); - if (!empty) { - DbConf1 dbConf1 = getDsConfBean(properties); - try { - registryDs(dbConf1, registry); - } catch (Exception e) { - e.printStackTrace(); - } - } - } + @Autowired + private DbConf dbConf; - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + @Override + public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + this.beanFactory = beanFactory; + } + + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; + try { + registryDs(registry); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } - } - }; } - private void registryDs(DbConf1 properties, BeanDefinitionRegistry registry) throws Exception { - String poolType = properties.getPoolType(); + @Override + public int getOrder() { + return -100; + } + + + private void registryDs(BeanDefinitionRegistry registry) throws ClassNotFoundException { + String poolType = dbConf.getPoolType(); if (Objects.nonNull(poolType)) { - Map dbs = properties.getDbs(); + + Map dbs = dbConf.getDbs(); Set> entries = dbs.entrySet(); for (Map.Entry entry : entries) { String dbName = entry.getKey(); @@ -101,18 +103,24 @@ private void registryDs(DbConf1 properties, BeanDefinitionRegistry registry) thr String mapperScannerPackage = value.getMapperScannerPackage(); String typeHandlersPackage = value.getTypeHandlersPackage(); Properties masterProperties = getDsProps(value.getMaster()); - Properties slaveProperties = getDsProps(value.getSlave()); - + Map slaves = value.getSlaves(); + List salves1 = new ArrayList<>(); + if (Objects.nonNull(slaves)) { + slaves.entrySet().forEach(x -> salves1.add(getDsProps(slaves.get(x)))); + } DruidDataSource master = new DruidDataSource(); master.setConnectProperties(masterProperties); - master.init(); - - DruidDataSource slave = new DruidDataSource(); - slave.setConnectProperties(slaveProperties); - slave.init(); + List slaveDatasources = new ArrayList<>(); + if (!salves1.isEmpty()) { + salves1.forEach(x -> { + DruidDataSource ds = new DruidDataSource(); + ds.setConnectProperties(x); + slaveDatasources.add(ds); + }); + } //获取动态数据源 - registryDynamicDs(master, slave, dbName, registry); + registryDynamicDs(master, slaveDatasources, dbName, registry); //事物 registryDynamicDsTrancationManager(dbName, registry); @@ -125,6 +133,7 @@ private void registryDs(DbConf1 properties, BeanDefinitionRegistry registry) thr } } + private Properties getDsProps(Properties master) { Properties props = new Properties(); Enumeration enumeration = master.propertyNames(); @@ -171,11 +180,14 @@ private void registryDynamicDsTrancationManager(String dbName, BeanDefinitionReg registry.registerBeanDefinition(dbName + TRANSACTIONMANAGER, beanDefinition); } - private void registryDynamicDs(DruidDataSource master, DruidDataSource slave, String dbName, BeanDefinitionRegistry registry) { + private void registryDynamicDs(DruidDataSource master, List slaves, String dbName, BeanDefinitionRegistry registry) { Map targetDataResources = new HashMap<>(); targetDataResources.put(DbContextHolder.DbType.MASTER, master); - targetDataResources.put(DbContextHolder.DbType.SLAVE, slave); + if (Objects.nonNull(slaves) && !slaves.isEmpty()) { + targetDataResources.put(DbContextHolder.DbType.SLAVE, slaves.get(0)); + } + GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(MasterSlaveRoutingDataSource.class); @@ -186,7 +198,13 @@ private void registryDynamicDs(DruidDataSource master, DruidDataSource slave, St } - private DbConf1 getDsConfBean(Properties properties) { + /** + * 目前无效代码了 + * + * @param properties + * @return + */ + private DbConf getDsConfBean(Properties properties) { PropertiesToYamlConverter converter = new PropertiesToYamlConverter(); StringBuilder sb = new StringBuilder(); @@ -207,25 +225,8 @@ private DbConf1 getDsConfBean(Properties properties) { Map ymalMap = yaml.loadAs(docment, Map.class); String s = JsonUtil.toJsonStr(ymalMap); - DbConf1 dbConf11 = JsonUtil.json2Bean(s, DbConf1.class); + DbConf dbConf11 = JsonUtil.json2Bean(s, DbConf.class); return dbConf11; } - - public static void main(String[] args) { - Map ymalMap = new HashMap(); - ymalMap.put("poolType", "wwwww"); - DbConf1 dbConf1 = new DbConf1(); - BeanMap beanMap = BeanMap.create(dbConf1); - beanMap.putAll(ymalMap); - - String s = JsonUtil.toJsonStr(ymalMap); - DbConf1 dbConf11 = JsonUtil.json2Bean(s, DbConf1.class); - - - System.out.println(dbConf11); - - } - - } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 9f795f8..4beba7a 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,4 +1,17 @@ + +datasource1: + pool-type: com.alibaba.druid.pool.DruidDataSource + ds: + url: jdbc:mysql://127.0.0.1:3306/dba?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true&useLocalSessionState=true&autoReconnect=true&failOverReadOnly=false&noAccessToProcedureBodies=true&useTimezone=true&serverTimezone=Hongkong + driverClassName: com.mysql.cj.jdbc.Driver + username: root + password: 123456 + initialSize: '1' + minIdle: '1' + maxActive: '20' + testOnBorrow: 'true' + druid2: poolType: com.alibaba.druid.pool.DruidDataSource dbs: @@ -15,15 +28,25 @@ druid2: minIdle: '1' maxActive: '20' testOnBorrow: 'true' - slave: - url: jdbc:mysql://127.0.0.1:3306/dba?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true&useLocalSessionState=true&autoReconnect=true&failOverReadOnly=false&noAccessToProcedureBodies=true&useTimezone=true&serverTimezone=Hongkong - driverClassName: com.mysql.cj.jdbc.Driver - username: root - password: 123456 - initialSize: '1' - minIdle: '1' - maxActive: '20' - testOnBorrow: 'true' + slaves: + slave0: + url: jdbc:mysql://127.0.0.1:3306/dba?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true&useLocalSessionState=true&autoReconnect=true&failOverReadOnly=false&noAccessToProcedureBodies=true&useTimezone=true&serverTimezone=Hongkong + driverClassName: com.mysql.cj.jdbc.Driver + username: root + password: 123456 + initialSize: '1' + minIdle: '1' + maxActive: '20' + testOnBorrow: 'true' + slave1: + url: jdbc:mysql://127.0.0.1:3306/dba?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true&useLocalSessionState=true&autoReconnect=true&failOverReadOnly=false&noAccessToProcedureBodies=true&useTimezone=true&serverTimezone=Hongkong + driverClassName: com.mysql.cj.jdbc.Driver + username: root + password: 123456 + initialSize: '1' + minIdle: '1' + maxActive: '20' + testOnBorrow: 'true' dbb: mapperLocations: classpath:mybatis/dbb/*.xml typeHandlersPackage: @@ -37,15 +60,16 @@ druid2: minIdle: '1' maxActive: '20' testOnBorrow: 'true' - slave: - url: jdbc:mysql://127.0.0.1:3306/dbb?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true&useLocalSessionState=true&autoReconnect=true&failOverReadOnly=false&noAccessToProcedureBodies=true&useTimezone=true&serverTimezone=Hongkong - driverClassName: com.mysql.cj.jdbc.Driver - username: root - password: 123456 - initialSize: '1' - minIdle: '1' - maxActive: '20' - testOnBorrow: 'true' + slaves: + slave0: + url: jdbc:mysql://127.0.0.1:3306/dbb?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true&useLocalSessionState=true&autoReconnect=true&failOverReadOnly=false&noAccessToProcedureBodies=true&useTimezone=true&serverTimezone=Hongkong + driverClassName: com.mysql.cj.jdbc.Driver + username: root + password: 123456 + initialSize: '1' + minIdle: '1' + maxActive: '20' + testOnBorrow: 'true' logging: level: