Spring Boot - 动态更改连接

Mar*_*ark 4 spring database-connection datasource dynamic spring-boot

我有一个 Spring Boot 项目,其中包含多个不同年份的数据库,并且这些数据库具有相同的表,因此唯一的区别是年份(...,DB2016,DB2017)。在应用程序的控制器中,我需要返回属于“不同”年份的数据。此外,在未来几年将创建其他数据库(例如,在 2018 年将有一个名为“DB2018”的数据库)。所以我的问题是如何在不每年创建新数据源和新存储库的情况下切换数据库之间的连接。在我发布的另一个问题中(Spring Boot - 不同数据库的相同存储库和相同实体) 答案是为每个现有数据库创建不同的数据源和不同的存储库,但在这种情况下,我想根据当前年份从现有数据库中返回数据。进一步来说:

一些实体.java

@Entity(name = "SOMETABLE")
public class SomeEntity implements Serializable {
@Id
@Column(name="ID", nullable=false)
private Integer id;

@Column(name="NAME")
private String name;
}
Run Code Online (Sandbox Code Playgroud)

SomeRepository.java

public interface SomeRepository extends PagingAndSortingRepository<SomeEntity, Integer> {
@Query(nativeQuery= true, value = "SELECT * FROM SOMETABLE WHERE NAME = ?1")
List<SomeEntity> findByName(String name);
}
Run Code Online (Sandbox Code Playgroud)

一些控制器.java

@RequestMapping(value="/foo/{name}", method=RequestMethod.GET)
public ResponseEntity<List<SomeEntity>> findByName(@PathVariable("name") String name) {
List<SomeEntity> list = autowiredRepo.findByName(name);
return new ResponseEntity<List<SomeEntity>>(list,HttpStatus.OK);

}
Run Code Online (Sandbox Code Playgroud)

应用程序属性

spring.datasource.url=jdbc:postgresql://localhost:5432/DB
spring.datasource.username=xxx
spring.datasource.password=xxx
Run Code Online (Sandbox Code Playgroud)

所以如果今年是 2017 年,我想要这样的东西:

int currentyear = Calendar.getInstance().get(Calendar.YEAR);
int oldestDbYear = 2014;
List<SomeEntity> listToReturn = new LinkedList<SomeEntity>();
//the method getProperties is a custom method to get properties from a file
String url = getProperties("application.properties", "spring.datasource.url");
props.setProperty("user", getProperties("application.properties","spring.datasource.username"));
props.setProperty("password", getProperties("application.properties","spring.datasource.password"));
for (int i = currentYear, i>oldestDbYear, i--) {
//this is the connection that must be used by autowiredRepo Repository, but i don't know how to do this.
//So the repository uses different connection for every year.
Connection conn = getConnection(url+year,props);
List<SomeEntity> list_of_specific_year = autowiredRepo.findByName(name);
conn.close;
listToReturn.addAll(list_of_specific_year);
}
return listToReturn;
Run Code Online (Sandbox Code Playgroud)

希望一切都清楚

Jam*_*ler 6

可能最适合您的需求的是 Spring 的AbstractRoutingDataSource. 您确实需要定义多个数据源,但您只需要一个存储库。多数据源在这里不是问题,因为总有一种方法可以在运行时以编程方式创建 DataSource bean 并将它们注册到应用程序上下文。

它的工作原理是您Map<Object, DataSource>在创建您的@Configuration 类时基本上注册了一个AbstractRoutingDataSource @Bean,在这种情况下,查找键将是年份。

然后您需要创建一个实现 AbstractRoutingDataSource 的类并实现该determineCurrentLookupKey()方法。每当进行数据库调用时,都会在当前上下文中调用此方法以查找DataSource应返回的内容。在您的情况下,听起来您只是希望将年份作为@PathVariableURL 中的 a ,然后作为从 URL 中determineCurrentLookupKey()获取它的实现@PathVariable(例如,在您的控制器中,您有类似 的映射@GetMapping("/{year}/foo/bar/baz"))。

    HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder
            .getRequestAttributes()).getRequest();

    HashMap templateVariables =
 (HashMap)request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

    return templateVariables.get("year");
Run Code Online (Sandbox Code Playgroud)

我在为一个产品编写测试工具时使用了这种方法,其中有许多实例在多个不同的服务器上运行,我希望我的@Controllers有一个统一的编程模型,但仍然希望它为服务器/部署组合中的服务器/部署组合命中正确的数据库网址。像魅力一样工作。

如果您使用 Hibernate,缺点是所有连接都将通过一个 SessionFactory,这意味着您无法利用我理解的 Hibernate 的第二级缓存,但我想这取决于您的需求。