2016-08-18 59 views
0

根據包含鏈接到哪個環境的變量的值選擇JNDI資源是否有可能?如何根據環境選擇JNDI

例如,在我的域中我有3個環境:DEV,QA和STAGE。我有一個名爲EcommReporting的數據庫,它存在於每個這樣的環境中。爲了迎合這個,在我的tomcat服務器的server.xml文件中,我有單獨的條目DEV_EcommReporting,QA_EcommReportingSTAGE_EcommReporting

問題是,我的代碼是否可以通過某種方式請求名爲EcommReporting的JNDI資源並提供環境名稱,然後根據這兩個詳細信息返回正確的資源?

這裏的,現在我使用Spring定義數據源的bean:

<bean id="EcommReportingDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> 
     <property name="jndiName" value="java:comp/env/jdbc/EcommReporting"/> 
    </bean> 
在我的Tomcat服務器的context.xml中(只顯示QA版),我有這個

然後:

<ResourceLink name="jdbc/EcommReporting" 
       global="jdbc/QA_EcommReporting" 
       auth="Container" 
       type="javax.sql.DataSource" /> 

最後,在我的Tomcat服務器的server.xml中,我定義了JNDI資源,如下所示:

<Resource name="jdbc/QA_EcommReporting" 
     global="jdbc/QA_EcommReporting" 
     auth="Container" 
     type="javax.sql.DataSource" 
     driverClassName="com.mysql.jdbc.Driver" 
     url="jdbc:mysql://URLHERE.COM:3311/REPORTING" 
     username="username_here" 
     password="password_here" 

     maxActive="100" 
     maxIdle="20" 
     minIdle="5" 
     maxWait="10000"/> 

ads

+0

服務器,目前還不清楚是什麼你想要,你有3個tomcat實例,並且你希望能夠從另一個JVM訪問這3個實例所使用的數據源,這是你想要的嗎? –

回答

0

你可以使用Spring配置文件做些事情。目前尚不清楚確切的設置是什麼:聽起來像所有3個WAR都部署到同一臺服務器上?如果是這樣,您需要動態設置活動配置文件。我能想到的一種方法是使用ServletContextListener並檢查已部署應用程序的路徑。

基本上,然後創建三個數據源bean並將它們與特定配置文件相關聯。這個過程被這裏概述:

https://spring.io/blog/2011/02/11/spring-framework-3-1-m1-released/

<beans profile="dev"> 
    <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/Dev_EcommReporting"/> 
</beans> 
<beans profile="qa"> 
    <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/QA_EcommReporting"/> 
</beans> 

然後,您可以創建一個的ServletContextListener並根據設定的路徑上活動的配置文件。

@Override 
    public void contextInitialized(ServletContextEvent event) { 

     ServletContext context = event.getServletContext(); 

     if(context.getContextPath().equals("/dev"){ 
      servletContext.setInitParameter("spring.profiles.active", "dev"); 
     } else if(context).getCOntextPath().equals("/qa"){ 
      servletContext.setInitParameter("spring.profiles.active", "qa"); 
     } 
    } 

此處瞭解詳情:

https://www.mkyong.com/spring/spring-profiles-example/

如果部署到不同的服務器上所有的應用程序然後就開始-Dspring.profiles.active = XYZ