gpt4 book ai didi

java - AWS Elastic Beanstalk 中的 JDBC 连接字符串

转载 作者:行者123 更新时间:2023-11-29 03:02:52 24 4
gpt4 key购买 nike

我想在 aws 中迁移我的应用程序,

我已经设置了我的环境。使用 Elastic Beanstalk 。

在我的应用程序的当前版本中,它在本地运行正常,我使用这个简单的代码设置连接:

我在 web.xml 中定义了资源:

<resource-ref> 
<description> Resource reference to a factory for java.sql.Connection instances that may be used for talking to a particular database that is configured in the <Context> configuration for the web application. </description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

然后在 config.xml 中我定义了资源

<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="utente1" password="utente1" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/nazioni?autoReconnect=true" />

现在我可以通过这种方式获得连接了

/* JNDI query to locate the DataSource object */ 
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env") ;

// JNDI standard naming root
DataSource ds = (DataSource)envContext.lookup("jdbc/TestDB");

/* Ask DataSource for a connection */
Connection conn = ds.getConnection();

现在我的问题是:我可以在 config.xml 中对连接字符串进行硬编码,还是使用 System.getProperty("JDBC_CONNECTION_STRING") 更好?如果是这样,我如何在加载 tomcat 时设置连接字符串?

谢谢,洛里斯

最佳答案

Tomcat Configuration Reference提及对 Ant 样式变量替换的支持:

Apache Ant-style variable substitution is supported; a system property with the name propname may be used in a configuration file using the syntax ${propname}. All system properties are available including those set using the -D syntax, those automatically made available by the JVM and those configured in the $CATALINA_BASE/conf/catalina.properties file.

这意味着如果你在.ebextensions/<environment-name>.config内定义一个属性比如:

option_settings:
- option_name: JDBC_CONNECTION_STRING
value: jdbc:mysql://localhost:3306/nazioni?autoReconnect=true

然后您应该能够在配置文件中引用该属性:

<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="utente1" password="utente1" driverClassName="com.mysql.jdbc.Driver" url="{JDBC_CONNECTION_STRING}" />

与硬编码相比,该方法至少有两个好处:

  1. 可以在正在运行的实例上的 AWS Beanstalk 控制台中手动更改该值
  2. 可以在正在运行的实例上以编程方式更改该值

关于java - AWS Elastic Beanstalk 中的 JDBC 连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20471484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com