一、使用ribbon之前的准备工作
1.要有两个服务,一个是服务消费者(本文创建的service-ribbon是服务消费者),一个是服务提供者(上篇文章创建的service-hi是服务提供者),并且服务提供者要有两个实例,也就是service-hi有两个实例,分别运行在8762和8763端口。
idea同一个工程启动多个实例:https://blog.youkuaiyun.com/feifei_Tang/article/details/103340646
二、创建一个服务消费者
1.在使用Eureka创建服务注册中心的基础上,创建一个module工程,过程同创建Eureka Server类似。
在pom.xml文件分别引入起步依赖spring-cloud-starter-eureka、spring-cloud-starter-ribbon、spring-boot-starter-web,代码如下:
2.在springboot工程的启动类上加一个注解@EnableDiscoveryClient,表示向服务中心注册;并且向程序的ioc注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。
package com.example.serviceribbon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
3.在配置文件application.yml中配置与服务相关的一些基本信息,如服务名、注册中心地址(即上一篇中设置的注册中心地址http://localhost:8761/eureka)。
server:
port: 8764
# 设置注册中心地址
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
# 设置服务名
spring:
application:
name: service-ribbon
4.写一个测试类HelloService,通过之前注入ioc容器的restTemplate来消费service-hi服务的“/hi”接口,在这里我们直接用的程序名替代了具体的url地址,在ribbon中它会根据服务名来选择具体的服务实例,根据服务实例在请求的时候会用具体的url替换掉服务名,代码如下:
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
public String hiService(String name) {
return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
}
}
5.写一个controller,在controller中用调用HelloService 的方法,代码如下:
package com.example.controller;
import com.example.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloControler {
@Autowired
HelloService helloService;
@RequestMapping(value = "/hi")
public String hi(@RequestParam String name){
return helloService.hiService(name);
}
}
6.测试。
启动工程,在浏览器上多次访问http://localhost:8764/hi?name=thw,浏览器交替显示:
这说明当我们通过调用restTemplate.getForObject(“http://eurekaclient/hi?name=”+name,String.class)方法时,已经做了负载均衡,访问了不同的端口的服务实例。
三、此时的架构
- 一个服务注册中心,eureka server,端口为8761
- service-hi工程跑了两个实例,端口分别为8762,8763,分别向服务注册中心注册
- sercvice-ribbon端口为8764,向服务注册中心注册
- 当sercvice-ribbon通过restTemplate调用service-hi的hi接口时,因为用ribbon进行了负载均衡,会轮流的调用service-hi:8762和8763两个端口的hi接口;