我在项目中使用browscap-java。但是初始加载时间太长。
final UserAgentParser parser = new UserAgentService().loadParser();
加载代码耗时约22058ms。
这是我的代码:
public String[] getAgentInfo() {
final UserAgentParser parser;
try {
parser = new UserAgentService().loadParser();
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
final String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36";
final Capabilities capabilities = parser.parse(userAgent);
final String[] agentInfo = new String[6];
agentInfo[0] = capabilities.getBrowser();
agentInfo[1] = capabilities.getBrowserType();
agentInfo[2] = capabilities.getBrowserMajorVersion();
agentInfo[3] = capabilities.getDeviceType();
agentInfo[4] = capabilities.getPlatform();
agentInfo[5] = capabilities.getPlatformVersion();
return agentInfo;
}
每次使用此功能都会初始化parser
。但是parser
是不变的,所以我想知道如何重用parser
,使parser
仅在第一次初始化。
PS:该代码适用于Java Web。
答案 0 :(得分:1)
您可以在此方法之外初始化/构建解析器,并将其作为参数传递。这将为您提供一次初始化解析器的灵活性,并通过传递已初始化的解析器多次调用此方法。
public UserAgentParser createUserAgentParser() {
final UserAgentParser parser;
try {
parser = new UserAgentService().loadParser();
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
return parser;
}
public String[] getAgentInfo(final UserAgentParser parser) {
final String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36";
final Capabilities capabilities = parser.parse(userAgent);
final String[] agentInfo = new String[6];
agentInfo[0] = capabilities.getBrowser();
agentInfo[1] = capabilities.getBrowserType();
agentInfo[2] = capabilities.getBrowserMajorVersion();
agentInfo[3] = capabilities.getDeviceType();
agentInfo[4] = capabilities.getPlatform();
agentInfo[5] = capabilities.getPlatformVersion();
return agentInfo;
}