首页 > 解决方案 > 如何为许多客户端进行 Spring-boot 配置

问题描述

我想知道如何解决问题:我在 docker 上有一个 spring-boot 应用程序,它连接到 db 和其他一些服务。可能有些客户会在其他 url 上拥有 db。

我使用spring.datasource.url属性连接到数据库。我应该将它添加到 args 并使用:

    Properties properties = new Properties();
    properties.put("spring.datasource.url", args[1]);
    application.setDefaultProperties(properties);

类似的东西会覆盖它吗?但是每次运行都需要添加数据库 url。还是用别的东西?

标签: springspring-boot

解决方案


数据源可以从 docker-compose 文件中作为变量读取:

假设这是您的 docker-compose 文件:

version: '2'

services:
  db:
    image: customimage_mysql
    restart: always
    ports:
    - "3306:3306"

  application:
   build: .
   ports:
     - "9111:9111"
   depends_on:
     - db
   links:
     - db
   environment:
     - database.url=jdbc:mysql://mysql-docker-container:3306/spring_app_db?

现在您有 2 个选项:

  • 在 docker compose 中为 databse.url 设置不同的值,并为每个应用程序相应地构建图像
  • 在 docker-compose 文件中设置不同的变量(databse1.url,databse2.url,databse3.url,...),并从 application.properties 中引用它们:

application.properties

spring.datasource.url=${database.url}
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
server.port=9111

推荐阅读