在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于http restful的。Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign。下面我们主要使用rest+ribbon实现
什么是ribbon
ribbon是一个负载均衡客户端,可以很好的控制htt和tcp的一些行为。Feign默认集成了ribbon。
模拟Eureka-client集群
首先在创建好Eureka-server和Eureka-client后,我们再建一个Eureka-client2以模拟一个集群
这里注意eureka-client2的端口号需要设置成与eureka-client不同
可以看到后台监控这里已经由2个SERVICE-HELLO
服务了
建一个服务消费者Service-ribbon
新建一个Spring Boot项目,并添加组件Eureka-discovery,Web和Ribbon
在启动类上添加@EnableDiscoveryClient
以向服务中心注册,并注入一个RestTemlate Bean,通过@LoadBalanced
注解表明这个RestTemplate开启负载均衡功能
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
写一个测试service和controller
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
public String hello(String name) {
return restTemplate.getForObject("http://SERVICE-HELLO/index?name=" + name, String.class);
}
}
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@GetMapping("/hello")
public String hello(String name){
return helloService.hello(name);
}
}
测试结果
在浏览器中输入 http://localhost:8764/hello?name=狗子
浏览器会交替显示来自不同的EurekaClient
这说明当我们通过调用restTemplate.getForObject(“http://SERVICE-HELLO/index?name=“+name,String.class)方法时,已经做了负载均衡,访问了不同的端口的服务实例。
此时的架构
-
一个服务注册中心,eureka server,端口为8761
-
service-hi工程跑了两个实例,端口分别为8762,8763,分别向服务注册中心注册
-
sercvice-ribbon端口为8764,向服务注册中心注册
-
当sercvice-ribbon通过restTemplate调用service-hello的index接口时,因为用ribbon进行了负载均衡,会轮流的调用service-hello:8762和8763 两个端口的index接口