假设你做简单的事情:
public class Main {
public static void main(String[] args) {
long started = System.currentTimeMillis();
try {
new URL(args[0]).openConnection();
} catch (Exception ignore) {
}
System.out.println(System.currentTimeMillis() - started);
}
}
现在用 http://localhost 运行它作为 args[0]
完成需要 ~100 毫秒。
现在尝试 https://localhost
它需要 5000+ 毫秒。
现在在 linux 或 docker 中运行相同的东西:
~100 毫秒~350 毫秒这是为什么? 为什么平台之间会有如此巨大的差异? 你能做些什么?
对于长时间运行的应用程序服务器和具有自己的长而繁重的初始化序列的应用程序,这 5 秒可能无关紧要。
但是,有很多应用程序最初的 5 秒“挂起”很重要,可能会变得令人沮丧......
最佳答案
(注意:另请参阅此答案末尾的最新更新)
解释
这是默认的原因 SecureRandom供应商。
在 Windows 上,有 2 个 SecureRandom提供者可用:
- provider=SUN, type=SecureRandom, algorithm=SHA1PRNG
- provider=SunMSCAPI, type=SecureRandom, algorithm=Windows-PRNG
在 Linux 上(使用 Oracle JDK 8u162 在 Alpine docker 中测试):
- provider=SUN, type=SecureRandom, algorithm=NativePRNG
- provider=SUN, type=SecureRandom, algorithm=SHA1PRNG
- provider=SUN, type=SecureRandom, algorithm=NativePRNGBlocking
- provider=SUN, type=SecureRandom, algorithm=NativePRNGNonBlocking
这些在 jre/lib/security/java.security 中指定文件。
security.provider.1=sun.security.provider.Sun
...
security.provider.10=sun.security.mscapi.SunMSCAPI
默认情况下,第一个 SecureRandom使用提供者。在 Windows 上,默认值为 sun.security.provider.Sun ,当 JVM 使用 -Djava.security.debug="provider,engine=SecureRandom" 运行时,此实现报告如下:
Provider: SecureRandom.SHA1PRNG algorithm from: SUN
provider: Failed to use operating system seed generator: java.io.IOException: Required native CryptoAPI features not available on this machine
provider: Using default threaded seed generator
而且默认的线程种子生成器非常慢。
您需要使用 SunMSCAPI供应商。
方案一:配置
重新排序配置中的供应商:
编辑 jre/lib/security/java.security :
security.provider.1=sun.security.mscapi.SunMSCAPI
...
security.provider.10=sun.security.provider.Sun
我不知道这可以通过系统属性来完成。
或者也许是,使用 -Djava.security.properties (未经测试,see this)
解决方案 2:程序化
以编程方式重新排序提供者:
Optional.ofNullable(Security.getProvider("SunMSCAPI")).ifPresent(p->{
Security.removeProvider(p.getName());
Security.insertProviderAt(p, 1);
});
JVM 现在报告以下 ( -Djava.security.debug="provider,engine=SecureRandom"):
Provider: SecureRandom.Windows-PRNG algorithm from: SunMSCAPI
解决方案 3:程序化 v2
灵感来自 this idea , 下面的一段代码只插入一个 SecureRandom服务,从现有动态配置 SunMSCAPI提供者没有明确依赖 sun.*类。这也避免了与 SunMSCAPI 的所有服务不加区别地确定优先级相关的潜在风险。供应商。
public interface WindowsPRNG {
static void init() {
String provider = "SunMSCAPI"; // original provider
String type = "SecureRandom"; // service type
String alg = "Windows-PRNG"; // algorithm
String name = String.format("%s.%s", provider, type); // our provider name
if (Security.getProvider(name) != null) return; // already registered
Optional.ofNullable(Security.getProvider(provider)) // only on Windows
.ifPresent(p-> Optional.ofNullable(p.getService(type, alg)) // should exist but who knows?
.ifPresent(svc-> Security.insertProviderAt( // insert our provider with single SecureRandom service
new Provider(name, p.getVersion(), null) {{
setProperty(String.format("%s.%s", type, alg), svc.getClassName());
}}, 1)));
}
}
性能
<140 msec (而不是 5000+ msec )
详情
有人调用new SecureRandom()当你使用 URL.openConnection("https://...") 时调用堆栈的某个地方
它调用getPrngAlgorithm() (参见 SecureRandom:880)
这首先返回 SecureRandom它找到的提供商。
出于测试目的,请调用 URL.openConnection()可以替换为:
new SecureRandom().generateSeed(20);
免责声明
我不知道提供商重新排序会导致任何负面影响。然而,可能有一些,特别是考虑到默认提供者选择算法。
无论如何,至少在理论上,从功能的角度来看,这对应用程序应该是透明的。
更新 2019-01-08
Windows 10(版本 1803):无法再在任何最新的 JDK 上重现此问题(从旧的 oracle 1.7.0_72 到 openjdk“12-ea”2019-03-19 都进行了测试)。
看起来这是 Windows 问题,已在最新的操作系统更新中修复。在最近的 JRE 版本中也可能发生也可能没有发生相关更新。 但是,即使我最老的 JDK 7 update 72 安装也确实受到了影响,而且绝对没有以任何方式修补,我也无法重现原始问题。
使用此解决方案时仍有微小的性能提升(平均约 350 毫秒),但默认行为不再遭受无法忍受的 5 秒以上惩罚。
关于java - SecureRandom 初始化缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49322948/
在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到rubygems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决
关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc
我正在阅读一本关于Ruby的书,作者在编写类初始化定义时使用的形式与他在本书前几节中使用的形式略有不同。它看起来像这样:classTicketattr_accessor:venue,:datedefinitialize(venue,date)self.venue=venueself.date=dateendend在本书的前几节中,它的定义如下:classTicketattr_accessor:venue,:datedefinitialize(venue,date)@venue=venue@date=dateendend在第一个示例中使用setter方法与在第二个示例中使用实例变量之间是
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/