gitee地址 https://gitee.com/aquari/spring_cloud_all
package com.springCloudAll.web;
import com.springCloudAll.client.TestClient;
import com.springCloudAll.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
import java.util.List;
/**
* Created by YouGuessWho on 2017/4/27.
*/
@RequestMapping(value="/discoveryTest")
@RestController
public class DiscoveryTestController {
@Autowired
private DiscoveryClient client;
@Autowired
private LoadBalancerClient loadBalancer;
/**
* 服务发现测试
* @return
*/
@RequestMapping("/getServiceData")
public String getSentence() {
return "discovery service and get data:"+getWord("TEST_SERVICE");//大小写不区分
}
/**
* 负载均衡
* @param service
* @return
*/
@RequestMapping("/getWordRibbon")
public String getWordRibbon(String service) {
ServiceInstance instance = loadBalancer.choose("TEST_SERVICE");
return (new RestTemplate()).getForObject(instance.getUri(),String.class);
}
@RequestMapping("/getWordHystrix")
public String getWordHystrix() {
return "Hystrix get data:"+testService.getWordHystrix();
}
private String getWord(String service) {
List<String> tt = client.getServices();
List<ServiceInstance> list = client.getInstances(service);
if (list != null && list.size() > 0 ) {
URI uri = list.get(0).getUri();
if (uri !=null ) {
return (new RestTemplate()).getForObject(uri,String.class);
}
}
return null;
}
}