refactor(cloud-query): 优化获取服务列表

This commit is contained in:
2023-12-21 00:31:22 +08:00
parent cae9fd5dc3
commit 11a8a3d96c

View File

@@ -1,12 +1,10 @@
package com.lanyuanxiaoyao.service.cloud;
import cn.hutool.core.util.StrUtil;
import java.util.List;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.list.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -31,13 +29,23 @@ public class CloudController {
}
@GetMapping("services")
public ImmutableList<String> infoQueryServices(@RequestParam("service_name") String serviceName) {
public ImmutableList<String> infoQueryServices(
@RequestParam("service_name") String serviceName,
@RequestParam(value = "with_schema", defaultValue = "true") Boolean withSchema,
@RequestParam(value = "with_port", defaultValue = "true") Boolean withPort
) {
return Lists.immutable.ofAll(client.getServices())
.select(name -> StrUtil.equals(name, serviceName))
.flatCollect(name -> {
return Lists.immutable.ofAll(client.getInstances(name))
.collect(instance -> instance.getUri().toString());
})
.flatCollect(name ->
Lists.immutable.ofAll(client.getInstances(name))
.collect(instance -> {
if (withSchema)
if (withPort) return instance.getUri().toString();
else return StrUtil.format("{}://{}", instance.getScheme(), instance.getHost());
else if (withPort)
return StrUtil.format("{}:{}", instance.getHost(), instance.getPort());
else return instance.getHost();
}))
.toSortedList()
.toImmutable();
}