开篇点题:
上篇讲到小商家(生产者)注册到某宝或者某东上(注册中心),那作为消费者的我们如何调用的呢?
很简单下载个app登陆账号,然后选购商品之后付款等待快递就ok了....
可是..可是,打断以下,那我程序怎么调用生产者的接口呢?
方案一:RestTemplate+Ribbon
方案二:Feign的方式,对就是这个spring-cloud-starter-openfeign
对于这两种方式有疑惑的可以在下面留言,有问必有答。编程之路期待你的参与
Tip:ribbon是一个负载均衡客户端,可以很好的控制htt和tcp的一些行为。Feign默认集成了ribbon。
Demo开始
案例还是采用springcloud-01-eureka-producer-consumer模块为例
主题:创建消费者模块,然后RestTemplate+Ribbon方式调用注册中心的生产者 IP/hello/name
1.启动注册中心 2.启动生产者
(注意启动顺序,此外代码已经详细解析参考 SpringCloud极简入门 |第一讲)
3.创建消费者
pom文件引入:(注意源代码种用到是spring-cloud-starter-openfeign)
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
</dependencies>
启动类
@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudConsumerApplication.class, args);
System.out.println("/*************spring cloud consumer 9001********************/");
}
/**
* ioc注入一个bean: restTemplate;
* 并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能
* @return
*/
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
写个Service:注意spring-cloud-provider是生产者的application.name的值(就是上篇说很重要的那个配置)
@Service
public class HelloServiceRibbon {
@Autowired
RestTemplate restTemplate;
public String hello( String name){
return restTemplate.getForObject("http://spring-cloud-provider/hello?name="+name,String.class);
};
}
Controller调用走起
@RestController
public class ConsumerController {
@Autowired
HelloServiceRibbon helloServiceRibbon;
@RequestMapping(value = "/hello1/{name}")
public String helloribbon(@PathVariable("name") String name){
System.out.println("/***********consumer-helloServiceRibbon*****/");
return helloServiceRibbon.hello(name);
}
}
写完了,开始测试了,启动消费者端口9001
配置文件:
spring.application.name=spring-cloud-consumer
server.port=9001
eureka.client.serviceUrl.defaultZone=http://localhost:7001/eureka/
测试开始(成功)
不要问是hello1为什么不是hello,因为那个controller被Feign方式调用占用了,不好意思
End:
上面代码只是一个基本入门,希望有所收获
其实负载包含多种策略,还支持自定义负载,基本入门完成后就开始高级架构篇欢迎转发关注