在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于 http restful 的。Spring cloud 有两种服务调用方式,一种是 ribbon + restTemplate,另一种是 feign。在这一篇文章首先讲解下基于 ribbon + rest。
Ribbon 是一个负载均衡客户端,可以很好的控制 http 和 tcp 的一些行为。
启动服务提供者
启动Eureka注册中心
创建测试的Controller
import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.client.RestTemplate;import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;@RestController@RequestMapping("/api")@Slf4jpublic class RibbonController { @Autowired private RestTemplate restTemplate; //loadbalanced客户端 @Autowired private LoadBalancerClient loadBalancerClient; @GetMapping("/ribbon/hello") public String hello() { String result = restTemplate.getForObject("http://eureka-provider/hello",String.class); return result; }}
点击 Run -> Edit Configurations...
选择需要启动多实例的项目并去掉 Single instance only 前面的勾
通过修改 application.yml 配置文件的 server.port 的端口,启动多个实例,需要多个端口,分别进行启动即可。
转载于:https://www.cnblogs.com/liuenyuan1996/p/10288060.html
