1. HttpClient
(这个是apache下边的一个子项目)
在启动类同级目录创建CustomerController,注入RestTemplate进行调用服务接口
- package com.cnblogs.hellxz;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.client.RestTemplate;
- /**
- * @Author : Hellxz
- * @Description: 消费者应用
- * @Date : 2018/4/16 15:54
- */
- @RestController
- public class CustomerController {
- @Autowired
- //注入restTemplate
- private RestTemplate restTemplate;
- @RequestMapping(value="/ribbon-customer", method=RequestMethod.GET)
- public String helloCustomer(){
- //这里注释掉,因为之前想当然使用了直链访问服务提供者的接口,这样是不会返回结果的,而且会报错
- //return restTemplate.getForEntity("http://localhost:8080/hello",String.class).getBody();
- //使用restTemplate调用微服务接口
- return restTemplate.getForEntity("http://hello-service/hello", String.class).getBody();
- }
- }
2. Ribbon使用(是springCloud中的一个组件)(这个就是客户端实现负载均衡)
RibbonConsumerApplication应用启动
通过注解@EnableDiscoveryClient让应用注册未Eureka客户端应用,获取服务发现的能力。
创建RestTemplate应用实例,通过@LoadBalanced注解开启客户端负载均衡。
- package com.lanhuigu;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.boot.builder.SpringApplicationBuilder;
- import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
- import org.springframework.cloud.client.loadbalancer.LoadBalanced;
- import org.springframework.context.annotation.Bean;
- import org.springframework.web.client.RestTemplate;
- @EnableDiscoveryClient
- @SpringBootApplication
- public class RibbonConsumerApplication {
- @Bean
- @LoadBalanced
- RestTemplate restTemplate() {
- return new RestTemplate();
- }
- public static void main(String[] args) {
- new SpringApplicationBuilder(RibbonConsumerApplication.class).web(true).run(args);
- }
- }
3. Feign用法
是一个声明式的web声明客户端