使用apollo获取mysql的登录密码,但密码是加密过的,需要先进行解密,才能使用,所以要覆盖springboot默认的数据源
pom.xml文件:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> <version>1.3.8.RELEASE</version> </dependency>
<dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
application.yaml配置文件如下:
#mysql部分:
spring:
datasource:
current:
type: com.alibaba.druid.pool.DruidDataSource
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
接着需要添加数据源的配置类:
DataSourceConfig.java
import com.test.room.common.utis.ApolloUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.test.room.dao", sqlSessionFactoryRef = "currentSqlSessionFactory")
public class DatasourceConfig {
// 将这个对象放入Spring容器中
@Bean(name = "currentDataSource")
// 表示这个数据源是默认数据源
@Primary
// 读取application.properties中的配置参数映射成为一个对象
// prefix表示参数的前缀,不读取默认yaml文件的password等信息去映射对象
// @ConfigurationProperties(prefix = "spring.datasource.current")
@Qualifier("currentDataSource")
public DataSource getDateSource1(){
// 从apollo读取相关配置及解密方法在ApolloUtil类中自定义
String url = "jdbc:mysql://" + ApolloUtils.getCommonValue("mysql.ip") + ":" + ApolloUtils.getCommonValue("mysql.port") + "/room?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=true&verifyServerCertificate=false";
return DataSourceBuilder.create()
.password(ApolloUtils.getCommonValue("mysql.password.room"))
.username(ApolloUtils.getCommonValue("mysql.username.room"))
.driverClassName("com.mysql.jdbc.Driver")
.url(url)
.type(com.alibaba.druid.pool.DruidDataSource.class)
.build();
}
@Bean(name = "currentSqlSessionFactory")
// 表示这个数据源是默认数据源
@Primary
// @Qualifier表示查找Spring容器中名字为currentDataSource的对象
public SqlSessionFactory currentSqlSessionFactory(@Qualifier("currentDataSource") DataSource datasource)
throws Exception
{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
// 设置mybatis的xml所在位置, 注意是 xml 所在位置。
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
return bean.getObject();
}
@Bean("currentSqlSessionTemplate")
// 表示这个数据源是默认数据源
@Primary
public SqlSessionTemplate test1SqlSessionTemplate(
@Qualifier("currentSqlSessionFactory") SqlSessionFactory sessionFactory)
{
return new SqlSessionTemplate(sessionFactory);
}
// 配置初始化sql文件位置,用于创建初始化数据表
@Value("classpath:migration/init.sql")
private Resource sqlScriptSchema;
@Bean
public DataSourceInitializer dataSourceInitializer(@Qualifier("currentDataSource") final DataSource dataSource) {
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(dataSource);
dataSourceInitializer.setDatabasePopulator(databasePopulator());
return dataSourceInitializer;
}
private DatabasePopulator databasePopulator() {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(sqlScriptSchema);
resourceDatabasePopulator.setSeparator(";");//分隔符[默认;]
return resourceDatabasePopulator;
}
}
如果是hibernate框架
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryPrimary",
transactionManagerRef = "transactionManagerPrimary",
basePackages = {"com.test.room.dao"})
public class HibernateConfig {
@Autowired
@Qualifier("currentDataSource")
private DataSource primaryDataSource;
@Primary
@Bean(name = "entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
return builder.dataSource(primaryDataSource).properties(getVendorProperties())
.packages("com.test.room.po") //设置实体类所在位置
.persistenceUnit("primaryPersistenceUnit").build();
}
private Map<String, Object> getVendorProperties() {
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect","org.hibernate.dialect.MySQL5InnoDBDialect");
properties.put("hibernate.ddl-auto","update");
properties.put("hibernate.physical_naming_strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
properties.put("hibernate.implicit_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
return properties;
}
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}