|
@@ -0,0 +1,65 @@
|
|
|
+package com.sf.controller.my;
|
|
|
+
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+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.PathVariable;
|
|
|
+import org.springframework.web.bind.annotation.RestController;
|
|
|
+import org.springframework.web.client.RestTemplate;
|
|
|
+
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Random;
|
|
|
+
|
|
|
+
|
|
|
+@RestController
|
|
|
+public class MyRandomController {
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ private RestTemplate restTemplate;
|
|
|
+
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ private DiscoveryClient discoveryClient;
|
|
|
+
|
|
|
+
|
|
|
+ @GetMapping("/echoRandom/{string}")
|
|
|
+ public String echo(@PathVariable("string") String str) {
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ String serviceId = "service-provider-demo";
|
|
|
+ List<ServiceInstance> serviceInstances = new ArrayList<>();
|
|
|
+
|
|
|
+ List<String> services = discoveryClient.getServices();
|
|
|
+ System.out.println(services);
|
|
|
+ for (String service : services) {
|
|
|
+
|
|
|
+ List<ServiceInstance> instances = discoveryClient.getInstances(service);
|
|
|
+ for (ServiceInstance instance : instances) {
|
|
|
+ System.out.println(instance.getInstanceId() + ":" + instance.getHost() +
|
|
|
+ ":" + instance.getPort() + ":" + instance.getUri());
|
|
|
+ }
|
|
|
+ if (service.equals(serviceId)) {
|
|
|
+ serviceInstances = instances;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ Random random = new Random();
|
|
|
+ int randomIndex = random.nextInt(serviceInstances.size());
|
|
|
+ System.out.println("randomIndex:" + randomIndex);
|
|
|
+ ServiceInstance serviceInstance = serviceInstances.get(randomIndex);
|
|
|
+ String newUrl = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/echo/{string}";
|
|
|
+ System.out.println("newUrl:" + newUrl);
|
|
|
+ String result = restTemplate.getForObject(newUrl, String.class, str);
|
|
|
+
|
|
|
+ return "result:" + result;
|
|
|
+ }
|
|
|
+}
|