上一节,我们已经把数据微服务注册好了,并且开放了两个端口可以访问到数据微服务,8001、8002:


下面我们就要访问前面注册好的这个数据微服务了!springcloud 提供了两种方式,一种是 Ribbon,一种是 Feign。
一、Ribbon
Ribbon 是使用 restTemplate 进行调用,并进行客户端负载均衡。 什么是客户端负载均衡呢? 在前面 注册数据微服务 里,注册了8001和8002两个微服务, Ribbon 会从注册中心获知这个信息,然后由 Ribbon 这个客户端自己决定是调用哪个,这个就叫做客户端负载均衡。
在上一节代码的基础上再创建子项目product-view-service-ribbon,我们要在这个子项目中调用上一节的数据微服务:

来看一下pom文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud</artifactId>
<groupId>com.topmap</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>product-view-service-ribbon</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>
实体类Product:
private int id;
private String name;
private int price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Product() {
}
public Product(int id, String name, int price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
Ribbon 客户端:
Ribbon 客户端, 通过 restTemplate 访问 http://PRODUCT-DATA-SERVICE/products , 而 product-data-service 既不是域名也不是ip地址,而是 数据服务在 eureka 注册中心的名称如下图:

注意看,这里访问的路径中只是指定了要访问的 微服务名称,但是并没有指定端口号到底是 8001, 还是 8002.
下面我们来写这个Ribbon客户端的代码:

这里我们通过 restTemplate 访问 http://PRODUCT-DATA-SERVICE/products
然后编写服务类,服务类数据从我们刚编写的 ProductClientRibbon 中获取:

然后我们再写一个controller将数据返回到web:

我们再写一个web界面来遍历并展示数据:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>products</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
table {
border-collapse:collapse;
width:400px;
margin:20px auto;
}
td,th{
border:1px solid gray;
}
</style>
</head>
<body>
<div class="workingArea">
<table>
<thead>
<tr>
<th>id</th>
<th>产品名称</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<tr th:each="p: ${ps}">
<td th:text="${p.id}"></td>
<td th:text="${p.name}"></td>
<td th:text="${p.price}"></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
我们再来编写这个Ribbon客户端子项目的启动类:
package com.topmap;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.NetUtil;
import cn.hutool.core.util.NumberUtil;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @Author: MaHuadong
* @Date: 2019/12/31 10:25
* @Version 1.0
*/
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class ProductViewServiceRibbonApplication {
public static void main(String[] args){
int port = 0;
int defaultPort = 8010;
Future<Integer> future = ThreadUtil.execAsync(() ->{
int p = 0;
System.out.println("请于5秒钟内输入端口号, 推荐 8010 超过5秒将默认使用 " + defaultPort);
Scanner scanner = new Scanner(System.in);
while(true) {
String strPort = scanner.nextLine();
if(!NumberUtil.isInteger(strPort)) {
System.err.println("只能是数字");
continue;
}
else {
p = Convert.toInt(strPort);
scanner.close();
break;
}
}
return p;
});
try{
port=future.get(5, TimeUnit.SECONDS);
}
catch (InterruptedException | ExecutionException | TimeoutException e){
port = defaultPort;
}
if(!NetUtil.isUsableLocalPort(port)) {
System.err.printf("端口%d被占用了,无法启动%n", port );
System.exit(1);
}
new SpringApplicationBuilder(ProductViewServiceRibbonApplication.class).properties("server.port=" + port).run(args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
启动类, 注解多了个 @EnableDiscoveryClient, 表示用于发现eureka 注册中心的微服务。
还多了个 RestTemplate,就表示用 restTemplate 这个工具来做负载均衡。
最后写一下我们的配置文件yml:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
spring:
application:
name: product-view-service-ribbon
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
encoding: UTF-8
content-type: text/html
mode: HTML5
配置类,指定了 eureka server 的地址,以及自己的名称。 另外是一些 thymeleaf 的默认配置。
最后我们来测试一下Ribbon客户端的作用:
先启动eurekserver服务:

再启动两次数据服务,分别选择端口8001和8002


最后再启动ribbon客户端:

这里多刷新几遍,会发现这个端口有时候是 8001,有时候是8002. 从而观察到访问 数据服务集群,客户端负载均衡的效果。

我们再来捋一下思路:
如图所示:
1. 首先数据微服务和视图微服务都被 eureka 管理起来了。
2. 数据服务是由两个实例的集群组成的,端口分别是 8001 , 8002
3. 视图微服务通过 注册中心调用微服务, 然后负载均衡到 8001 或者 8002 端口的应用上。

这就是通过Ribbon访问微服务的方法。Ribbon 是使用 restTemplate 进行调用,并进行客户端负载均衡。
二、Feign
前面我们学习了使用Ribbon进行微服务的访问,这里我们来看一下另外一种访问微服务的方法:Feign
Feign 是对 Ribbon的封装,使用注解的方式,调用起来更简单, 也是主流的方式。
首先从代码上来看一下这两种方法的不同之处:
Ribbon方式:
public List<Product> listProdcuts() {
return restTemplate.getForObject("http://PRODUCT-DATA-SERVICE/products",List.class);
}
这个product-data-service 既不是域名也不是ip地址,而是 数据服务在 eureka 注册中心的名称。
Feign方式:
@FeignClient(value = "PRODUCT-DATA-SERVICE")
public interface ProductClientFeign {
@GetMapping("/products")
public List<Product> listProdcuts();
}
这里可以看出Feign是使用注解的方式直接把数据微服务的注册名称传进去。
下面我们通过代码进行通过Feign访问数据微服务的过程实现!
1、新建子项目:product-view-service-feign

我们来看一下我们的pom文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud</artifactId>
<groupId>com.topmap</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>product-view-service-feign</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>
这里我们又引进来了一个新的jar包:spring-cloud-starter-openfeign,就是用来支持 Feign 方式的。
2、新建实体类Product
package com.topmap.pojo;
/**
* @Author: MaHuadong
* @Date: 2019/12/31 11:14
* @Version 1.0
*/
public class Product {
private int id;
private String name;
private int price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Product() {
}
public Product(int id, String name, int price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
}
3、Feign 客户端
Feign 客户端, 通过 注解方式 访问 访问PRODUCT-DATA-SERVICE服务的 products路径, product-data-service 既不是域名也不是ip地址,而是 数据服务在 eureka 注册中心的名称。
注意看,这里也只是通过注解指定了要访问的 微服务名称,但是并没有指定端口号到底是 8001, 还是 8002.

4、新建服务类ProductService:
服务类,数据从 productClientFeign 中获取

5、新建controller:控制器,把数据取出来放在 product.html 中

6、新建products.html遍历并展示数据微服务的数据:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>products</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
table {
border-collapse:collapse;
width:400px;
margin:20px auto;
}
td,th{
border:1px solid gray;
}
</style>
</head>
<body>
<div class="workingArea">
<table>
<thead>
<tr>
<th>id</th>
<th>产品名称</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<tr th:each="p: ${ps}">
<td th:text="${p.id}"></td>
<td th:text="${p.name}"></td>
<td th:text="${p.price}"></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
7、编写Feign启动类ProductViewServiceFeignApplication:
package com.topmap;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.NetUtil;
import cn.hutool.core.util.NumberUtil;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @Author: MaHuadong
* @Date: 2019/12/31 11:24
* @Version 1.0
*/
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class ProductViewServiceFeignApplication {
public static void main(String[] args){
int port = 0;
int defaultPort = 8012;
Future<Integer> future = ThreadUtil.execAsync(() ->{
int p = 0;
System.out.println("请于5秒钟内输入端口号, 推荐 8012 、 8013 或者 8014,超过5秒将默认使用"+defaultPort);
Scanner scanner = new Scanner(System.in);
while(true) {
String strPort = scanner.nextLine();
if(!NumberUtil.isInteger(strPort)) {
System.err.println("只能是数字");
continue;
}
else {
p = Convert.toInt(strPort);
scanner.close();
break;
}
}
return p;
});
try{
port=future.get(5, TimeUnit.SECONDS);
}
catch (InterruptedException | ExecutionException | TimeoutException e){
port = defaultPort;
}
if(!NetUtil.isUsableLocalPort(port)) {
System.err.printf("端口%d被占用了,无法启动%n", port );
System.exit(1);
}
new SpringApplicationBuilder(ProductViewServiceFeignApplication.class).properties("server.port=" + port).run(args);
}
}
启动类, 这里注解多了个 @EnableFeignClients, 表示用于使用 Feign 方式。
8、最后配置文件yml
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
spring:
application:
name: product-view-service-feign
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
encoding: UTF-8
content-type: text/html
mode: HTML5
配置类,指定了 eureka server 的地址,以及自己的名称。 另外是一些 thymeleaf 的默认配置。
最后我们启动Feign的启动类,然后访问地址:
http://127.0.0.1:8012/products

多刷新几遍,会发现这个端口有时候是 8001,有时候是8002. 从而观察到访问 数据服务集群,客户端负载均衡的效果。

Feign的微服务的调用过程和Ribbon是类似的如下图:

1. 首先数据微服务和视图微服务都被 eureka 管理起来了。
2. 数据服务是由两个实例的集群组成的,端口分别是 8001 , 8002
3. 视图微服务通过 注册中心调用微服务, 然后负载均衡到 8001 或者 8002 端口的应用上。
总结:因为 Feign 是对 Ribbon 的封装,而且也是主要方式,所以后续学习我们就会都使用 feign, 而不再使用 Ribbon了。
这一节就先到这儿,大家加油!
168万+



被折叠的 条评论
为什么被折叠?



