我不知道如何为以下场景找到解决方案。
我们有一个新的要求,即从属性中删除数据库密码,即使它是用 Jasypt 库或一些其他算法加密的。
我们不需要将密码存储在属性或 LDAP 中,而是需要从 Cyberark 动态获取它.
密码可能会在一两天、一周或一个月内过期。这完全取决于密码过期政策。
我们有多个项目。有些是基于网络的,有些是独立的。我们想编写一个通用的解决方案。
如何覆盖任何数据源的getConnection
方法,如Spring数据源、Apache Basic数据源(它支持扩展类)、C3P0、DBCP或HikariCP而不影响它们行为并在点击 super.getConnection()
之前设置密码?
super.getConnection(); // Here max attempt will be 3
Spring支持方法替换,但不知道对连接池框架有什么影响。
如果您需要更多详细信息,请告诉我。
最佳答案
要解决您的问题,您可以使用 spring-cloud-context 库及其 @RefreshScope
注释。此外,您需要进行一些开发。
1) 您需要一个特殊的监视程序 bean,它将监视密码是否已更改。它将是这样的:
@Service
public class Watcher {
private final ContextRefresher refresher;
public Watcher(ContextRefresher refresher) {
this.refresher = refresher;
}
@Scheduled(fixedDelay = 10000L)
public void monitor() {
if (/* smth changed*/) {
refresher.refresh();
}
}
}
因此,当您调用 refresher.refresh();
时,所有使用 @RefreshContext
注释的 beans 将在第一次访问它们后被释放并重新创建。
2) 使用@RefreshContext
注释来注释您的数据源bean。
3) 您必须提供密码才能使用 @ConfigurationProperties
注释进行访问。您将需要创建 SourceLocator。会是这样的
@Order(0)
public class SourceLocator implements PropertySourceLocator {
@Override
public PropertySource<?> locate(Environment environment) {
//Load properties to hash map
return new MapPropertySource("props", new HashMap<>());
}
}
此外,创建一个文件 spring.factories 并将以下数据放在那里:
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.test.YourSourceLocator
4) 创建将保存和刷新数据库通行证的属性类。
@RefreshScope
@ConfigurationProperties(prefix="your.prefix")
public class Properties {
private String dbPassword;
}
将此 bean 自动连接到您创建数据源的配置并使用其中的密码。
关于java - 对于密码过期的任何数据源,都需要基于 Spring 的应用程序的通用解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50829565/