应用间通讯协议
所谓服务消费者,就是它需要调用的服务不在本地,需要远程调用,而远程调用目前主流的协议就是HTTP和RPC.
dubbo远程通讯协议:RPC
springcloud远程通讯协议:HTTP (HTTP RESTful)
Service Conumer服务消费者
1:新建springcloud-service-conumer模块
2:继承父工程
3:修改application.properties配置文件
1 2 3 4 5 6 7 8 | #允许注册eureka注册中心,默认值就是true eureka.client.register-with-eureka=true #允许从eureka注册中心找服务,并调用,默认值就是true eureka.client.fetch-registry=true #eureka的server地址,如果eureka服务多个用逗号隔开 eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ #应用名 spring.application.name=spring-cloud-service-consumer |
4:主程序加上@EnableEurekaClient注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | package com.wendao.provider.consumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableEurekaClient public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication. class , args); } } |
5:启动该工程,访问http://localhost:8761/(注册中心ui界面地址)看到如下界面
6:使用resttemplate调用远程服务,而resttemplate的使用又有三种方式
方式一:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package com.wendao.provider.consumer.web; import com.wendao.provider.consumer.pojo.User; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class ConsumerController { private RestTemplate restTemplate = new RestTemplate(); @RequestMapping ( "/findOne" ) public User findOne(){ User user = restTemplate.getForObject( "http://localhost:8181/user/1" , User. class ); return user; } } |
RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求,可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。
第一种方式小结:第一种方式简单粗暴,但是这种方式有弊端,最直接的弊端是,如果服务提供者是一个集群,我们永远只能调用集群中的某一个。没法实现负载均衡。