繁体   English   中英

如何使用Spring Boot JPA配置动态多个数据源

[英]How to config dynamic multiple datasource with Spring boot JPA

我想在运行时选择不同的数据源,这是我的示例:在不同的数据库中有2个结构相同的MySQL表,比如testing.io:3306/db/person和production.io:3306/db/person。 我想根据一些标准选择数据库。

以下是一些代码:

实体类

@Entity
@Data
public class person{
    @Id
    @GeneratedValue
    private Long id;
    private String name;
}

它的存储库:

   @RepositoryRestResource(collectionResourceRel = "Person", path = "Person")
public interface PersonRepository extends CrudRepository<Person, Long>{

}

application.yml

 spring:
  datasource:
    testing:
      url: jdbc:mysql://testing.io:3306/db?useSSL=false
      username: root
      password: 1111
    production:
      url: jdbc:mysql://production.io:3306/db?useSSL=false
      username: root
      password: 2222
   driver-class-name: com.mysql.jdbc.Driver

我省略了服务接口,因为其中只有一种方法。

控制器:

   @RestController
public class PersonrController {
    @Autowired
    PersonService personService ;


    @RequestMapping(value = "/select-person", method= RequestMethod.POST)
    public String selectPerson(@RequestBody parameter) {
        /**
          class Parameter only has one field: env
        /
        return personService.select(Parameter parameter);
    }


}

服务工具:

@Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    @Use("testing") // It means this repo uses the 'testing' config in the application.yml
    PersonRepository testingPersonRepo;

    @Autowired
    @Use("production") // It means this repo uses the 'production' config in the application.yml
    PersonRepository productionPersonRepo;


    @Override
    public String select(Parameter parameter){
        // dynamically use different DB with the same entity
        if (parameter.getEnv().equals("production")){
            return productionPersonRepo.findAll();
        }else{
            return testingPersonRepo.findAll();
        }

    }
}

如何用Spring Boot JPA 优雅地配置它?

您应该使用弹簧轮廓。 在应用程序启动时,您告诉环境变量"spring.profiles.active"以确定它是测试还是生产, spring.profiles.active=testingspring.profiles.active=production

然后在您的application.yml

spring:
  profiles:
    active: testing

spring:
  datasource:
      url: jdbc:mysql://testing.io:3306/db?useSSL=false
      username: root
      password: 1111
 driver-class-name: com.mysql.jdbc.Driver

---
spring:
  profiles:
    active: production

spring:
  datasource:
      url: jdbc:mysql://production.io:3306/db?useSSL=false
      username: root
      password: 2222

这将根据配置文件是一个还是另一个为您的数据源分配值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM