我有一个JAVA 8 AWS lambda函数,它在容器第一次启动时有一些非常昂贵的设置。它必须调用以提取各种凭据/仙人掌。我想缓存这个设置(它的输出是一个SSLContext对象,用于调用另一个api)。
我以前从来没有这样做过,我的问题似乎找不到答案:
在Lambda还活着时,是否存在重复使用SSLContext对象的问题?这可能是15分钟或5小时,或2天,等等。只要有车辆通过它,它就会活着。
所有凭据都不会更改,而且SSLContext对象在所有调用之间都是相同的。
SSLContext对象有TTL吗?创建SSLConext的代码非常简单。在完成了获取certs/cred的昂贵拉操作并缓存此SSLContext对象之后,将调用此方法:
public SSLContext getContext(){
KeyStore clientStore = KeyStore.getInstance(KEY_INSTANCE);
keyStoreInputstream = //GET STREAM
clientStore.load(keyStoreInputstream, caCertCred.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientStore, KEY.toCharArray());
KeyManager[] kms = kmf.getKeyManagers();
trustStoreInputStream = //GET STREAM
KeyStore trustStore = KeyStore.getInstance(TRUST_INSTANCE);
trustStore.load(trustStoreInputStream, caCertCred.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
TrustManager[] tms = tmf.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kms, tms, new SecureRandom());
return sslContext;
}
发布于 2020-09-22 13:53:37
简单的回答是:使用一个类级变量。
在AWS Lambda中,类级变量是“全局”变量。因此,如果在handleRequest(...)
方法之外声明一个变量,Lambda容器将使用相同的值对该变量进行初始化。当lambda函数再次执行时,您只需按原样重用变量。
下面是它如何工作的一个例子:
public class LambdaExample implements RequestStreamHandler {
private LambdaLogger logger;
private SSLContext sslContext;
@Override
public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
logger = context.getLogger();
// do some work
if(sslContext == null) {
// this means SSLContext needs to be initialized - probably a new container
initSslContext();
} else {
// this means SSLContext is already initialized - just use it as it is
}
// use SSLContext
}
private void initSslContext() {
// note: you need to create the KeyStore, KeyManagerFactory
// and re-initialize the SSLContext here because it's null
}
}
注意:
通常,全局变量有一些缺点,但我认为在您的例子中,它不会产生任何问题。您可以观看以下视频,以真正了解AWS中全局变量的工作方式。
https://stackoverflow.com/questions/63940867
复制相似问题