@EnableDiscoveryClient和@EnableEurekaClient的區(qū)別
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。
@EnableDiscoveryClient和@EnableEurekaClient的區(qū)別?馬克-to-win@馬克java社區(qū):在前面的服務提供者的例子中我們是用@EnableEurekaClient,其實二者的功能是一樣的。但是如果選用的是eureka服務器,那么就推薦@EnableEurekaClient,如果是其他的注冊中心,那么推薦使用@EnableDiscoveryClient。
馬克-to-win@馬克java社區(qū):下面的RestTemplate本身不具備調用分布式服務的能力,但被@LoadBalanced修飾后就具有訪問分布式服務的能力了(本helloworld例子不做探討)
package com;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate () {
return new RestTemplate ();
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
@RestController
class ConsumerCotroller {
@Autowired
private RestTemplate template;
@RequestMapping("/consumer")
public String consume() {
ResponseEntity<String> responseEntity = template.getForEntity("http://provider/acquire", String.class);
String body = responseEntity.getBody();//也能getStatusCode()等,都是Response實體的方法。
return body;
}
@Autowired
private DiscoveryClient discoveryClient;
/*http://192.168.0.101:9000/services/provider測的時候,這么測*/
@RequestMapping("/services/{appName}")
public String myGetIns(@PathVariable String appName) {
/*馬克-to-win@馬克java社區(qū):發(fā)現客戶的工具discoveryClient,可以通過getInstances,找到分布的一堆叫這個名字的service*/
// ServiceInstance si=this.discoveryClient.getLocalServiceInstance();
// return si.getHost();
List<ServiceInstance> list = this.discoveryClient.getInstances(appName);
if (list != null && list.size() > 0 )
{ return list.get(0).getHost()+list.get(0).getMetadata(); }
return null;
}
}
運行結果: