二.Spring Cloud服务消费者实践(Rest + Rib
开宗明义
在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于http restful的,Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign。
ribbon是一个负载均衡客户端,可以很好的控制htt和tcp的一些行为。Feign默认集成了ribbon。
1 创建第二个服务
1.1修改service-hi的端口,以此作为第二个服务

1.2 启动第二个服务

1.3 通过浏览器访问注册中心界面(此时可发现两个service-hi服务,端口分别为8766,8767)

2 建立一个服务消费者
2.1 创建springboot工程作为服务消费者,命名为service-ribbon

2.2 配置application.yml文件(定服务的注册中心地址为http://localhost:8765/eureka/,程序名称为 service-ribbon,程序端口为8768
)

2.3 启动类中,通过@EnableDiscoveryClient向服务中心注册;并且向程序的ioc注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能

2.4 写一个测试类HelloService,通过之前注入ioc容器的restTemplate来消费service-hi服务的“/hi”接口,在这里我们直接用的程序名替代了具体的url地址,在ribbon中它会根据服务名来选择具体的服务实例,根据服务实例在请求的时候会用具体的url替换掉服务名

2.5 写一个HelloController调用HelloService

2.6 启动service-ribbon


2.8 此时的架构
2.8.1 一个服务注册中心,eureka server,端口为8765
2.8.2 service-hi工程跑了两个实例,端口分别为8766,8767,分别向服务注册中心注册
2.8.3 sercvice-ribbon端口为8768,向服务注册中心注册
2.8.4 当sercvice-ribbon通过restTemplate调用service-hi的hi接口时,因为用ribbon进行了负载均衡,会轮流的调用service-hi:8762和8763 两个端口的hi接口
未完待续......