我有一个 Spring Boot 项目,其中包含多个不同年份的数据库,这些数据库具有相同的表,因此唯一的区别是年份(...,DB2016,DB2017)。在应用程序的 Controller 中,我需要返回属于“不同”年份的数据。此外,在 future 几年将创建其他数据库(例如,在 2018 年将有一个名为“DB2018”的数据库)。所以我的问题是如何在不每年创建新数据源和新存储库的情况下切换数据库之间的连接。
在我发布的另一个问题 ( Spring Boot - Same repository and same entity for different databases ) 中,答案是为每个现有数据库创建不同的数据源和不同的存储库,但在这种情况下,我想根据当前年份从现有数据库中返回数据。进一步来说:
一些实体.java
@Entity(name = "SOMETABLE")
public class SomeEntity implements Serializable {
@Id
@Column(name="ID", nullable=false)
private Integer id;
@Column(name="NAME")
private String name;
}
SomeRepository.java
public interface SomeRepository extends PagingAndSortingRepository<SomeEntity, Integer> {
@Query(nativeQuery= true, value = "SELECT * FROM SOMETABLE WHERE NAME = ?1")
List<SomeEntity> findByName(String name);
}
一些 Controller .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);
}
应用程序属性
spring.datasource.url=jdbc:postgresql://localhost:5432/DB
spring.datasource.username=xxx
spring.datasource.password=xxx
所以如果今年是 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;
希望一切都清楚
最佳答案
这里可能最适合您的需求的是 Spring 的 AbstractRoutingDataSource
.您确实需要定义多个数据源,但您只需要一个存储库。多数据源在这里不是问题,因为总有一种方法可以在运行时以编程方式创建 DataSource bean 并将它们注册到应用程序上下文。
它的工作原理是您基本上注册了一个 Map<Object, DataSource>
创建 AbstractRoutingDataSource
时在 @Configuration 类中@Bean
在这种情况下,查找键将是年份。
然后你需要创建一个实现 AbstractRoutingDataSource 的类并实现 determineCurrentLookupKey()
方法。每当进行数据库调用时,都会在当前上下文中调用此方法以查找 DataSource
应该被退回。在您的情况下,听起来您只是想将年份设为 @PathVariable
在 URL 中然后作为 determineCurrentLookupKey()
的执行捕获那个 @PathVariable
在 URL 之外(例如,在您的 Controller 中,您有类似 @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");
我在为一个产品编写测试工具时使用了这种方法,其中有许多实例在多个不同的服务器上运行,我希望从我的
@Controller
中获得一个统一的编程模型。 s 但仍希望它在 url 中为服务器/部署组合访问正确的数据库。像魅力一样工作。如果您使用 Hibernate,缺点是所有连接都将通过一个 SessionFactory,这意味着您无法利用我理解的 Hibernate 的第二级缓存,但我想这取决于您的需求。
关于Spring Boot - 动态更改连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46935382/