配置多个数据源,spring profile 多环境配置管理

  针对生产环境,测试环境,以及本地调试开发有时会配置多套数据库,在一个数据配置文件进行修改,往往有时发布到生成环境会忘记修改,或者本地调试时还是生产环境的库,会导致生产环境数据被污染。

ps--刚开始配完发现在Myeclipse一直是“development”模式,后来发现tomcat配置完之后要myeclise中进行jdk配置。

1.这里我们可以配置多个数据源配置文件:

application.development.properties 作为开发环境;

application.local.properties 作为本地调试环境;

application.properties 作为生产环境;

application.test.properties 作为测试环境;

 

jdbc.driver=com.mysql.jdbc.Driver

#development
jdbc.url=jdbc:mysql://ip:port/database?autoReconnect=true&initialTimeout=3&useUnicode=true&characterEncoding=utf-8
jdbc.username=user
jdbc.password=password

#connection pool settings
jdbc.pool.minIdle=1
jdbc.pool.maxIdle=3
jdbc.pool.maxActive=30
jdbc.pool.maxWait=12000

 

  

 

2.然后在applicationContext.xml配置文件中配置对应的数据源:

配置文件有点长,主要是我配置了四个数据源,耐心点看吧- -

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd"
	default-lazy-init="true">

	<description>Spring公共配置 </description>

	<context:annotation-config />
	
	<!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
	<context:component-scan base-package="com.eteclab.wodm">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
		<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
	</context:component-scan>

	<!-- Jpa Entity Manager 配置 -->
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
		<property name="dataSource" ref="dataSource"/>
		<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
		<property name="packagesToScan" value="com.eteclab"/>
		<property name="jpaProperties">
			<props>
				<!-- 命名规则 My_NAME->MyName -->
				<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
			</props>
		</property>
	</bean>
	
	<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
		<property name="databasePlatform">
			<bean factory-method="getDialect" class="org.eteclab.modules.persistence.Hibernates">
				<constructor-arg ref="dataSource"/>
			</bean>
		</property>
	</bean>

	<!-- Spring Data Jpa配置 -->
 	<jpa:repositories base-package="com.eteclab.wodm"  transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory"/>
   
	<!-- Jpa 事务配置 -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory"/>
	</bean>

	<!-- 使用annotation定义事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

	<!-- JSR303 Validator定义 -->
 	<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
	
	<!-- production环境 -->
 	<beans profile="production">
 		<context:property-placeholder ignore-unresolvable="true" 
 		location="classpath*:/application.properties"/>	
		
		<!-- 数据源配置, 使用Tomcat JDBC连接池 -->
		<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
			<!-- Connection Info -->
			<property name="driverClassName" value="${jdbc.driver}" />
			<property name="url" value="${jdbc.url}" />
			<property name="username" value="${jdbc.username}" />
			<property name="password" value="${jdbc.password}" />
		
			<!-- 连接数控制与连接归还策略 -->
			<property name="maxActive" value="${jdbc.pool.maxActive}" />
			<property name="maxIdle" value="${jdbc.pool.maxIdle}" />
			<property name="minIdle" value="${jdbc.pool.minIdle}" />
			<property name="maxWait" value="${jdbc.pool.maxWait}" />
			<property name="defaultAutoCommit" value="false" />
			<!-- 连接Idle一个小时后超时 -->
			<property name="timeBetweenEvictionRunsMillis" value="30000" />
			<property name="minEvictableIdleTimeMillis" value="30000" />
			<!-- 应对网络不稳定的策略 -->
			<!-- <property name="testOnBorrow" value="true" />
			<property name="validationInterval" value="30000" />
			<property name="validationQuery" value="select 1 from dual" /> -->
			 <property name="testOnReturn" value="true"></property>
 			 <property name="testWhileIdle" value="true"></property>
			<property name="testOnBorrow" value="true" />
			<property name="validationInterval" value="30000" />
			<property name="validationQuery" value="select 1 from dual" />
			<!-- 应对连接泄漏的策略 -->
			<property name="removeAbandoned" value="true" />
			<property name="removeAbandonedTimeout" value="60" />
		</bean>
		
		<!-- 数据源配置,使用应用服务器的数据库连接池 -->
		<!--<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/ExampleDB" />-->
	</beans>
	
	<!-- local development环境 -->
	<beans profile="development">
		<context:property-placeholder ignore-resource-not-found="true"
			location="classpath*:/application.development.properties" />	

		<!-- Tomcat JDBC连接池 -->
		<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
			<!-- Connection Info -->
			<property name="driverClassName" value="${jdbc.driver}" />
			<property name="url" value="${jdbc.url}" />
			<property name="username" value="${jdbc.username}" />
			<property name="password" value="${jdbc.password}" />
		
			<!-- 连接数控制与连接归还策略 -->
			<property name="maxActive" value="${jdbc.pool.maxActive}" />
			<property name="maxIdle" value="${jdbc.pool.maxIdle}" />
			<property name="minIdle" value="${jdbc.pool.minIdle}" />
			<property name="maxWait" value="${jdbc.pool.maxWait}" />
			<property name="defaultAutoCommit" value="false" />
			<!-- 连接Idle一个小时后超时 -->
			<property name="timeBetweenEvictionRunsMillis" value="30000" />
			<property name="minEvictableIdleTimeMillis" value="30000" />
			<!-- 应对网络不稳定的策略 -->
			<property name="testOnBorrow" value="true" />
			<property name="validationInterval" value="30000" />
			<property name="validationQuery" value="select 1 from dual" />
			<!-- 应对连接泄漏的策略 -->
			<property name="removeAbandoned" value="true" />
			<property name="removeAbandonedTimeout" value="60" />
		</bean>
	</beans>
	
	<!-- local test 环境 -->
	<beans profile="local">
		<context:property-placeholder ignore-resource-not-found="true"
			location="classpath*:/application.local.properties" />	

		<!-- Tomcat JDBC连接池 -->
		<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
			<!-- Connection Info -->
			<property name="driverClassName" value="${jdbc.driver}" />
			<property name="url" value="${jdbc.url}" />
			<property name="username" value="${jdbc.username}" />
			<property name="password" value="${jdbc.password}" />
		
			<!-- 连接数控制与连接归还策略 -->
			<property name="maxActive" value="${jdbc.pool.maxActive}" />
			<property name="maxIdle" value="${jdbc.pool.maxIdle}" />
			<property name="minIdle" value="${jdbc.pool.minIdle}" />
			<property name="maxWait" value="${jdbc.pool.maxWait}" />
			<property name="defaultAutoCommit" value="false" />
			<!-- 连接Idle一个小时后超时 -->
			<property name="timeBetweenEvictionRunsMillis" value="30000" />
			<property name="minEvictableIdleTimeMillis" value="30000" />
			<!-- 应对网络不稳定的策略 -->
			<property name="testOnBorrow" value="true" />
			<property name="validationInterval" value="30000" />
			<property name="validationQuery" value="select 1 from dual" />
			<!-- 应对连接泄漏的策略 -->
			<property name="removeAbandoned" value="true" />
			<property name="removeAbandonedTimeout" value="60" />
		</bean>
	</beans>
	
	<!-- unit test环境 -->
	<beans profile="test">
	 	<context:property-placeholder ignore-resource-not-found="true"
			location="classpath*:/application.test.properties" />	
		
		<!-- Tomcat JDBC连接池 -->
		<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
			<!-- Connection Info -->
			<property name="driverClassName" value="${jdbc.driver}" />
			<property name="url" value="${jdbc.url}" />
			<property name="username" value="${jdbc.username}" />
			<property name="password" value="${jdbc.password}" />
		
			<!-- 连接数控制与连接归还策略 -->
			<property name="maxActive" value="${jdbc.pool.maxActive}" />
			<property name="maxIdle" value="${jdbc.pool.maxIdle}" />
			<property name="minIdle" value="${jdbc.pool.minIdle}" />
			<property name="maxWait" value="${jdbc.pool.maxWait}" />
			<property name="defaultAutoCommit" value="false" />
			<!-- 连接Idle一个小时后超时 -->
			<property name="timeBetweenEvictionRunsMillis" value="30000" />
			<property name="minEvictableIdleTimeMillis" value="30000" />
			<!-- 应对网络不稳定的策略 -->
			<property name="testOnBorrow" value="true" />
			<property name="validationInterval" value="30000" />
			<property name="validationQuery" value="select 1 from dual" />
			<!-- 应对连接泄漏的策略 -->
			<property name="removeAbandoned" value="true" />
			<property name="removeAbandonedTimeout" value="60" />
		</bean>
	</beans>
</beans>

 3.对tomcat服务器进行修改:

{tomcat_home}

/bin/catalina.bat 或 catalina.sh 以确定tomcat所在服务器的环境

{production, development, local, test}


对于windows操作系统,在catalina.bat的第二行,增加如下的语句


set CATALINA_OPTS=%CATALINA_OPTS% -Dspring.profiles.active="production"

对于linux操作系统,在catalina.sh的第二行,增加如下的语句

CATALINA_OPTS="$CATALINA_OPTS -Dspring.profiles.active=\"production\""

注意这里的"production",只能是{production, development, local, test}
中的一个

例如我在我本地开发,使用“local”配置:

 还有一步要注意的地方就是在web.xml文件中:

配置默认为开发环境,这样如果新接触项目的开发人员如果本地没有配置tomcat,也不会触及到生产环境。

*************************************************************************************************

*************************************************************************************************

 

这里我们可以在项目中写一个监听类,来监听项目运行时所属的环境:

public class InitConfigListener  implements ServletContextListener {
	
    public void contextInitialized(ServletContextEvent sce) {
        //侦测jvm环境,并缓存到全局变量中
        String env = System.getProperty("spring.profiles.active");
        if(env == null) {
            Config.ENV = "development";
        } else {
            Config.ENV = env;
        }
        
        System.out.println("==================================================================================================");
        System.out.println("The Application "+sce.getServletContext().getServletContextName()+" is running on the environment:" + Config.ENV);
        System.out.println("==================================================================================================");
    }

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
	}

}

  

public class Config {

	public static String ENV = "development";//默认开发常量
	
}

  直接启动tomcat看到如下效果:

当然我们更希望是在Myeclise开发工具中启动- -

最后启动tomcat就出来了= =

 

转载于:https://www.cnblogs.com/SimonHu1993/p/7451612.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud Data Flow 是一个用于构建、部署和管理微服务的框架,它不直接提供多数据源配置,而是通过集成 Spring Boot Actuator 和第三方工具来实现。然而,在 Spring Cloud 中,我们确实可以使用 Spring JPA 或者 Spring Boot 的@ConfigurationProperties 来配置多个数据源,通常在分布式系统中为了支持读写分离或者事务隔离。 以下是配置数据源的基本步骤: 1. **添加依赖**:引入 spring-boot-starter-data-jpa 和 spring-cloud-starter-config(如果用的是 Config Server)的依赖。 2. **配置数据源**:在application.yml 或 application.properties 文件中为每个数据源定义一个独立的 profile,比如 `db1`, `db2` 等,每个profile有自己的数据库地址、用户名、密码等信息。 ```yaml spring: profiles: active: db1 jpa: properties: hibernate: dialect: ... # 数据库特定的Dialect url: ${jpa.url.db1} username: ${jpa.username.db1} password: ${jpa.password.db1} ``` 3. **使用@Profile注解**:在需要使用不同数据源的地方,可以使用 Spring 的 @Profile 注解来切换。 ```java @Configuration @Profile("db1") public class DatabaseConfig1 { @Bean public DataSource dataSource() { // 配置数据源 } } @Configuration @Profile("db2") public class DatabaseConfig2 { @Bean public DataSource dataSource() { // 配置另一个数据源 } } ``` 4. **配置事务管理器**:如果需要事务隔离,可能还需要为每个数据源配置单独的事务管理器。 5. **使用Repository或JPA**:在Repository或者Service层,你可以根据环境变量或Profile选择使用哪个数据源
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值