猿问

Spring Boot 1 数据库多数据库用户

我目前正在构建一个访问数据库的restful API(使用Spring Boot)。该应用程序最终将托管在服务器上。

我想做的事:

  1. 配置数据库有多用户,并为不同的表分配不同的权限

  2. 根据调用的端点,使用特定用户在该函数中执行该查询

我该如何配置上述应用程序?

到目前为止我找到的答案涉及配置多个数据源,但对于上述应用程序,只有一个数据源,但有多个用户。

我已阅读以下链接,但仍在尝试理解它

https://kimrudolph.de/blog/spring-datasource-routing

我是否使用相同的 URL(本例中为 jdbcURL)配置多个数据源,并为每个角色配置多组用户名和密码?

谢谢你!


慕无忌1623718
浏览 107回答 1
1回答

忽然笑

我的意思是,你已经找到了完成这项任务的最佳方法AbstractRoutingDataSource。如果您有固定数量的用户,那么您可以使用以下方法的最简单方法:public final class RoutingDataSource extends AbstractRoutingDataSource {&nbsp; &nbsp; @Override&nbsp; &nbsp; protected Object determineCurrentLookupKey() {&nbsp; &nbsp; &nbsp; &nbsp; return UserContextHolder.getUserName() + "DataSource";&nbsp; &nbsp; }}以及配置:@Bean@Qualifier("user1DataSource")public DataSource userOneDataSource() {&nbsp; &nbsp; return DataSourceBuilder.create()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .username("user1")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .password("pass")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.build();}@Bean@Qualifier("user2DataSource")public DataSource userOneDataSource() {&nbsp; &nbsp; return DataSourceBuilder.create()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .username("user2")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.build();}@Bean@Primarypublic RoutingDataSource dataSource(Map<String, DataSource> datasources) {&nbsp; &nbsp; return new RoutingDataSource().dataSource(datasources);&nbsp;}如果您需要在运行时添加用户和数据源,您可以使用如下内容:public final class RoutingDataSource extends AbstractRoutingDataSource {&nbsp; &nbsp; private final ConcurrentHashMap<String, DataSource> dynamicDataSources = new ConcurrentHashMap<>();&nbsp; &nbsp; @Override&nbsp; &nbsp; protected Object determineCurrentLookupKey() {&nbsp; &nbsp; &nbsp; &nbsp; return UserContextHolder.getUserName() + "_datasource";&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; protected DataSource determineTargetDataSource() {&nbsp; &nbsp; &nbsp; &nbsp; String currentLookupKey = this.determineCurrentLookupKey().toString();&nbsp; &nbsp; &nbsp; &nbsp; String userName = UserContextHolder.getUserName();&nbsp; &nbsp; &nbsp; &nbsp; String password = UserContextHolder.getPassword();&nbsp; &nbsp; &nbsp; &nbsp; return this.dynamicDataSources.computeIfAbsent(currentLookupKey, (key) -> DataSourceBuilder.create()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .driverClassName("your.driver.class")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .url("jdbc:same:url/here")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .username(userName)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .password(password)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .build());&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答