常见的微服务的消费者

1. HttpClient

(这个是apache下边的一个子项目)

在启动类同级目录创建CustomerController,注入RestTemplate进行调用服务接口

  1. package com.cnblogs.hellxz;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestMethod;
  5. import org.springframework.web.bind.annotation.RestController;
  6. import org.springframework.web.client.RestTemplate;
  7. /**
  8. * @Author : Hellxz
  9. * @Description: 消费者应用
  10. * @Date : 2018/4/16 15:54
  11. */
  12. @RestController
  13. public class CustomerController {
  14. @Autowired
  15. //注入restTemplate
  16. private RestTemplate restTemplate;
  17. @RequestMapping(value="/ribbon-customer", method=RequestMethod.GET)
  18. public String helloCustomer(){
  19. //这里注释掉,因为之前想当然使用了直链访问服务提供者的接口,这样是不会返回结果的,而且会报错
  20. //return restTemplate.getForEntity("http://localhost:8080/hello",String.class).getBody();
  21. //使用restTemplate调用微服务接口
  22. return restTemplate.getForEntity("http://hello-service/hello", String.class).getBody();
  23. }
  24. }

2. Ribbon使用(是springCloud中的一个组件)(这个就是客户端实现负载均衡)

RibbonConsumerApplication应用启动

通过注解@EnableDiscoveryClient让应用注册未Eureka客户端应用,获取服务发现的能力。

创建RestTemplate应用实例,通过@LoadBalanced注解开启客户端负载均衡。

[java]  view plain  copy
  1. package com.lanhuigu;  
  2.   
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  4. import org.springframework.boot.builder.SpringApplicationBuilder;  
  5. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;  
  6. import org.springframework.cloud.client.loadbalancer.LoadBalanced;  
  7. import org.springframework.context.annotation.Bean;  
  8. import org.springframework.web.client.RestTemplate;  
  9.   
  10. @EnableDiscoveryClient  
  11. @SpringBootApplication  
  12. public class RibbonConsumerApplication {  
  13.       
  14.     @Bean  
  15.     @LoadBalanced  
  16.     RestTemplate restTemplate() {  
  17.         return new RestTemplate();  
  18.     }  
  19.       
  20.     public static void main(String[] args) {  
  21.         new SpringApplicationBuilder(RibbonConsumerApplication.class).web(true).run(args);  
  22.     }  
  23. }  

3. Feign用法

是一个声明式的web声明客户端

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值