1、Maven依赖项
<dependency><groupId>io.leopard</groupId><artifactId>javahost</artifactId><version>0.9.12</version></dependency>
2、设置虚拟DNS
hostMap中key代表host的名称,value代表ip;以下代码运行后,可以使用host名称代替IP
public class HostUtils {public static void initHost(Map<String,String> hostMap){// 加载一个虚拟DNS配置if (hostMap.size()>0) {JavaHost.updateVirtualDns(hostMap);}}
}
3、调用虚拟DNS
1)前端中创建envId,指定虚拟环境的Id
@GetMapping("run/{caseId}")
public Response runCase(@PathVariable("caseId") Integer caseId,@RequestParam(value = "envId", required = false) Integer envId) {ApiTestDto apiTestDto = apiTestCaseService.runCase(caseId, envId);return ResponseFactory.getSuccess(apiTestDto);
}
2)后端通过envId查询到数据库中的host和IP,并组装成hostMap
public Map<String, String> queryHostMap(Integer envId) {// 查询所有的host// 通过环境ID envId查询if (envId == null) {return new HashMap<>();}try {LambdaQueryWrapper<ProjectHostEntity> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(ProjectHostEntity::getStatus, 0);queryWrapper.eq(ProjectHostEntity::getEnvId, envId);queryWrapper.orderByDesc(ProjectHostEntity::getHost);List<ProjectHostEntity> list = this.list(queryWrapper);return list.stream().collect(Collectors.toMap(ProjectHostEntity::getHost, ProjectHostEntity::getIp));} catch (Exception e){return new HashMap<>();}}
3)然后执行HostUtils.initHost方法,在缓存中指定当前host和ip,然后调用doTest()执行接口用例
public void executeTest(ApiTestDto apiTestDto, Map<String, String> envMap) {// 参数提取,所有提取出来的参数放到这个Map中使用Map<String, String> extractionMap = new HashMap<>();if (envMap != null && envMap.size() > 0) {HostUtils.initHost(envMap);}doTest(apiTestDto, extractionMap);}