从配置文件读取基础url信息,端口起始信息,访问路径列表
application.properties
server.search.port.begin=8080
server.search.port.end=8090
server.search.url=http://127.0.0.1
server.search.visit-list=,doc.html,index,examples,docs
当发现指定 baseUrl + “:” + port + “/” + path 可以访问时,自动打开该地址。
核心代码
@Slf4j
public class ApplicationPortTest
{
RestTemplate restTemplate = new RestTemplate();
ResourceBundle resource;
@Test
public void test()
{
try (Scanner sc = new Scanner(System.in))
{
do
{
runCall();
log.info("------------输入x退出,回车换行继续------------");
} while (!"x".equalsIgnoreCase(sc.nextLine()));
log.info("------------成功退出------------");
}
}
/**
* 线程池方式测试
*
* @see [类、类#方法、类#成员]
*/
private void runCall()
{
// 取配置
resource = ResourceBundle.getBundle("application");
String baseUrl = resource.getString("server.search.url");
Integer portBegin = NumberUtils.parseNumber(resource.getString("server.search.port.begin"), Integer.class);
Integer portEnd = NumberUtils.parseNumber(resource.getString("server.search.port.end"), Integer.class);
String[] visits = resource.getString("server.search.visit-list").split(",");
// 线程池
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = portBegin; i < portEnd; i++)
{
final int port = i;
cachedThreadPool.execute(() -> openBrowser(baseUrl, port, visits));
}
}
private void openBrowser(String baseUrl, int port, String[] visits)
{
Arrays.stream(visits).forEach(path -> {
try
{
String url = baseUrl + ":" + port + "/" + path;
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
if (responseEntity.getStatusCode() == HttpStatus.OK)
{
log.info("now open url: {}", url);
Runtime.getRuntime().exec("cmd /c start /min " + url);
}
}
catch (Exception e)
{
}
});
}
}
运行效果图
此代码无强依赖,springmvc,springboot工程均可用。
-over-