@EnableDiscoveryClient和@EnableEurekaClient的区别?

@EnableDiscoveryClient和@EnableEurekaClient的区别?马克-to-win@马克java社区:在前面的服务提供者的例子中我们是用@EnableEurekaClient,其实二者的功能是一样的。但是如果选用的是eureka服务器,那么就推荐@EnableEurekaClient,如果是其他的注册中心,那么推荐使用@EnableDiscoveryClient。


马克-to-win@马克java社区:下面的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社区:发现客户的工具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;
    }

}


运行结果:








 


 

更多请看下节:https://blog.csdn.net/qq_44639795/article/details/95860874

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mark_to_win

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值