在 Tomcat 中使用动态数据源
我正在为我的应用程序创建一系列 Web 服务,并且需要根据在 Web 服务调用中作为参数传递的 serviceCode 来访问不同的数据库。
我使用 tomcat 设置了一个基本资源来访问这样的数据库
<Resource name="jdbc/db_name" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="user" password="pass" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://server_ip:3306/db_name"/>
但是这样我必须为我在服务器上创建的每个数据库设置一个资源,我想要什么,但我没有找到信息(或者不明白) ),是能够将 db_name 设置为在运行时从 Web 服务传递的变量,因此基本上只有一个资源并动态地使用它,而不是为每个数据库都拥有一个资源(这需要我启动服务器来更改每次我创建新数据库时的 context.xml )
我使用这样的 scalaquery 访问资源
val db = Database.forDataSource(datasource("jdbc/db_name"))
,这就是我希望能够动态传递 db_name 或在运行时定义资源的点,是否有其他方法tomcat/scala 还是我每次都被迫添加资源?
I'm creating a series of webservices for my application and i have the need to access a different database based on the serviceCode that is passed as a parameter in the webservice call.
I setup a basic resource with tomcat to access a database like this
<Resource name="jdbc/db_name" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="user" password="pass" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://server_ip:3306/db_name"/>
But in this way i have to setup a resource for every database i create on the server, what i wanted, and that i didn't found info ( or didn't understand ), was to be able to set db_name as a variable that is passed at runtime from the webservice, so basically having only one resource and using it dinamically instead of having a resource for every database ( that would require me to start the server for changing the context.xml every time i create a new database)
I access the resource using scalaquery like this
val db = Database.forDataSource(datasource("jdbc/db_name"))
and this is the point where i wanted to be able to dinamically pass the db_name, or define the resource at runtime, is there an alternative way with tomcat/scala or am i forced to add a resource everytime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
定义您自己的资源。请参阅 Tomcat 文档。您提供 javax.naming.spi.ObjectFactory 的实现。让它返回 Context 的适当实现,以便通过某个名称查找它会返回到该名称的数据库连接。就我而言,context.xml 中所需的条目如下所示:
Define your own Resource. See the Tomcat documentation. You provide an implementation of javax.naming.spi.ObjectFactory. Have it return an appropriate implementation of Context such that looking it up via some name returns a DB connection to that name. In my case the required entry in context.xml looked like this: