|
@@ -0,0 +1,67 @@
|
|
|
|
+package cn.com.qmth.examcloud.web.cloud;
|
|
|
|
+
|
|
|
|
+import java.util.List;
|
|
|
|
+import java.util.concurrent.TimeUnit;
|
|
|
|
+
|
|
|
|
+import org.apache.commons.collections.CollectionUtils;
|
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
|
+import org.springframework.cloud.client.ServiceInstance;
|
|
|
|
+import org.springframework.cloud.client.discovery.DiscoveryClient;
|
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
|
+
|
|
|
|
+import com.google.common.cache.Cache;
|
|
|
|
+import com.google.common.cache.CacheBuilder;
|
|
|
|
+import com.google.common.collect.Lists;
|
|
|
|
+
|
|
|
|
+import cn.com.qmth.examcloud.commons.exception.ExamCloudRuntimeException;
|
|
|
|
+
|
|
|
|
+/**
|
|
|
|
+ * 注册中心客户端
|
|
|
|
+ *
|
|
|
|
+ * @author WANGWEI
|
|
|
|
+ * @date 2019年5月28日
|
|
|
|
+ * @Copyright (c) 2018-? http://qmth.com.cn All Rights Reserved.
|
|
|
|
+ */
|
|
|
|
+@Component
|
|
|
|
+public class ExamCloudDiscoveryClient {
|
|
|
|
+
|
|
|
|
+ @Autowired(required = false)
|
|
|
|
+ private DiscoveryClient discoveryClient;
|
|
|
|
+
|
|
|
|
+ private Cache<String, List<String>> cache = CacheBuilder.newBuilder().maximumSize(100)
|
|
|
|
+ .expireAfterWrite(1, TimeUnit.MINUTES).concurrencyLevel(10).recordStats().build();
|
|
|
|
+
|
|
|
|
+ /**
|
|
|
|
+ * 获取实例的URL
|
|
|
|
+ *
|
|
|
|
+ * @author WANGWEI
|
|
|
|
+ * @param appName
|
|
|
|
+ * @return
|
|
|
|
+ */
|
|
|
|
+ public String getInstanceUrl(String appName) {
|
|
|
|
+
|
|
|
|
+ List<String> urlList = cache.getIfPresent(appName);
|
|
|
|
+ if (CollectionUtils.isNotEmpty(urlList)) {
|
|
|
|
+ String url = urlList.get(0);
|
|
|
|
+ return url;
|
|
|
|
+ }
|
|
|
|
+ urlList = Lists.newArrayList();
|
|
|
|
+
|
|
|
|
+ List<ServiceInstance> instances = discoveryClient.getInstances(appName);
|
|
|
|
+ if (instances.isEmpty()) {
|
|
|
|
+ throw new ExamCloudRuntimeException("no instance!");
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ for (ServiceInstance serviceInstance : instances) {
|
|
|
|
+ String host = serviceInstance.getHost();
|
|
|
|
+ int port = serviceInstance.getPort();
|
|
|
|
+ String url = "http://" + host + ":" + port;
|
|
|
|
+ urlList.add(url);
|
|
|
|
+ }
|
|
|
|
+ cache.put(appName, urlList);
|
|
|
|
+
|
|
|
|
+ String url = urlList.get(0);
|
|
|
|
+ return url;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+}
|