我知道已经晚了,但我觉得同样的解决方案可能会帮助其他人实施。
几周前我遇到了同样的问题,我已经实现了如下相同的:
在我当前的实现中,我使用下面的代码来加载 jks 文件:
Resource res = resLoader.getResource(filePath);
jksKeystore = KeyStore.getInstance("JKS");
jksKeystore.load(res.getInputStream(), clientHeaderInfo());// clientHeaderInfo() method is used to load custom header information
要处理从 Spring 云配置服务器读取的自定义路径,我们需要将完整的 http 链接设置为“server.ssl.key-store”属性。例如:http://localhost:8888/application/profile/sample.jks?useDefaultLabel=useDefaultLabel
回到自定义方面,我们需要将自定义协议解析器添加到 spring 上下文中,如下所示:
@Configuration
public class CustomProtocolResolverRegistrar implements ApplicationContextAware {
@Value("${customurl.prefix:chttp:}")
private String urlPrefix;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (applicationContext instanceof ConfigurableApplicationContext) {
final ConfigurableApplicationContext configurableApplicationContext
= (ConfigurableApplicationContext) applicationContext;
configurableApplicationContext.addProtocolResolver((location, resourceLoader)-> {
if(StringUtils.hasText(location) && location.startsWith(urlPrefix)) {
try {
return new CloudResource(location.replace(urlPrefix, ""));
}
catch (MalformedURLException e) {
logger.error("Exception while getting CloudResource : {}",e);
}
}
return null;
});
}
} }
稍后添加 CustomResource 实现如下:
public class CustomResource extends UrlResource {
private String path;
private URL url;
public CustomResource(URL url) {
super(url);
this.url = url;
}
public CustomResource(String path) throws MalformedURLException {
super(path);
this.url = new URL(path);
this.path = path;
}
@Override
public InputStream getInputStream() throws IOException {
URLConnection con = this.url.openConnection();
con.setRequestProperty(org.springframework.http.HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM_VALUE);
ResourceUtils.useCachesIfNecessary(con);
try {
return con.getInputStream();
}
catch (IOException e) {
if (con instanceof HttpURLConnection) {
((HttpURLConnection) con).disconnect();
}
throw e;
}
}
最后一步是我们需要自动配置要被弹簧加载器拾取的类:
在资源文件夹下创建 META-INF/spring.factories 文件并自动配置您的类,如下所示:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.xxx.xxx.xxx.CustomProtocolResolverRegistrar
注意:如果您使用 git 作为后端,则应正确配置基本路径以将 jks 文件提供给客户端请求。
它应该可以解决上述问题。
如果有其他更好的方法,请纠正我。