在上章的知识中我们学了如何搭建一个注册中心集群,(ps:有三个注册中心的服务节点:eruka1001,eruka1002,eruka1003)
本次内容:如何搭建服务提供者集群和通过调用ribbon来负载均衡的调用这个集群
简介
前面讲了eureka服务注册与发现,但是结合eureka集群的服务调用没讲。
这里的话 就要用到Ribbon,结合eureka,来实现服务的调用;
Ribbon是Netflix发布的负载均衡器,它有助于控制HTTP和TCP的客户端的行为。为Ribbon配置服务提供者地址后,Ribbon就可基于某种负载均衡算法,自动地帮助服务消费者去请求。Ribbon默认为我们提供了很多负载均衡算法,例如轮询、随机等。当然,我们也可为Ribbon实现自定义的负载均衡算法。
在Spring Cloud中,当Ribbon与Eureka配合使用时,Ribbon可自动从Eureka Server获取服务提供者地址列表,并基于负载均衡算法,请求其中一个服务提供者实例。展示了Ribbon与Eureka配合使用时的架构。
Ribbon是客户端负载均衡,所以肯定集成再消费端,也就是consumer端
我们修改microservice-student-consumer-80
首先,引入依赖,pom.xml 加入 ribbon相关依赖
<!--ribbon相关依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.wxm</groupId>
<artifactId>springcloud</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>microservice-student-consumer-80</artifactId>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-autoconfigure</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>spring-boot-test</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>com.wxm</groupId>
<artifactId>microservice-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.2.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.2.RELEASE</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>spring-boot-autoconfigure</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>2.2.2.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-eureka-client</artifactId>
<version>1.4.5.RELEASE</version>
<scope>compile</scope>
</dependency>
<!--ribbon相关依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
server:
port: 80
context-path: /
eureka:
client:
service-url:
defaultZone: http://eureka2001.wxm.com:2001/eureka/,http://eureka2002.wxm.com:2002/eureka/,http://eureka2003.wxm.com:2003/eureka/
register-with-eureka: false
ribbon结合eureka来调用服务提供者;
SpringCloudConfig也改成 要加个负载均衡配置 @LoadBalanced
package com.wxm.microservicestudentconsumer80.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@EnableEurekaClient
@Configuration
public class SpringCloudConfig {
@LoadBalanced // 引入ribbon负载均衡
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
ribbon结合eureka来调用服务提供者;
SpringCloudConfig也改成 要加个负载均衡配置 @LoadBalanced
因为和eureka整合,所以启动类StudentConsumerApplication_80 加个注解 @EnableEurekaClient
package com.wxm.microservicestudentprovider.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class SpringCloudConfig {
@LoadBalanced // 引入ribbon负载均衡
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
这里还有一个,要修改下StudentConsumerController的PRE_HOST,改成指定的微服务应用名称;
package com.wxm.microservicestudentconsumer80.controller;
import com.wxm.microservicecommon.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
@RequestMapping("/student")
public class StudentConsumerController {
// private final static String SERVER_IP_PORT = "http://localhost:1001";
private final static String SERVER_IP_PORT = "http://MICROSERVICE-STUDENT";
@Autowired
private RestTemplate restTemplate;
@PostMapping(value="/save")
private boolean save(Student student){
return restTemplate.postForObject(SERVER_IP_PORT+"/student/save", student, Boolean.class);
}
@GetMapping(value="/list")
public List<Student> list(){
return restTemplate.getForObject(SERVER_IP_PORT+"/student/list", List.class);
}
@GetMapping(value="/get/{id}")
public Student get(@PathVariable("id") Integer id){
return restTemplate.getForObject(SERVER_IP_PORT+"/student/get/"+id, Student.class);
}
@GetMapping(value="/delete/{id}")
public boolean delete(@PathVariable("id") Integer id){
try{
restTemplate.getForObject(SERVER_IP_PORT+"/student/delete/"+id, Boolean.class);
return true;
}catch(Exception e){
return false;
}
}
}
当然这里要先在服务提供者microservice-student-provider的application.yml加下配置,指定下应用名称:
上面配置好后,我们可以测试下;
先启动三个eureka,然后再启动服务提供者,再启动服务消费者;
http://192.168.192.1:2001/
看到这个说明注册服务成功!!!!!(ps:内心崩溃啊啊啊啊啊,有坑啊,前面细节不要放过啊尤其是那里弄虚拟ip的时候hosts的路径,还有是否带#问题)
搭建一个服务集群并起了个应用名字(三合一)
服务器名字为:microservice-student-provider
pom.xml配置
在原先的基础上并没有做出很大的改变
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--保持使用版本的一致1.0-SNAPSHOT-->
<parent>
<groupId>com.wxm</groupId>
<artifactId>springcloud</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>microservice-student-provider</artifactId>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--相当于全局的一个依赖关系,这个导入能确保整个项目使用的包版本一致
比如全局中的: spring-cloud-dependencies
spring-boot-dependencies
druid-spring-boot-starter
-->
<dependency>
<groupId>com.wxm</groupId>
<artifactId>microservice-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--处理web请求-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--test测试的包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--使用的数据库关系映射框架是jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--使用的是mysql数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--使用tomcat-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<!-- 修改后立即生效,热部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!--需要引入公共模块的实体类等(在导入的时候出现)-->
<dependency>
<groupId>com.wxm</groupId>
<artifactId>microservice-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!--添加注册中心Eureka相关配置,就是说这个是消费者-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- actuator监控引入,点击后的追责 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
与原先的文件比多了
配置了三个
---
server:
port: 1001
context-path: /
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:2206/test?useUnicode=true&characterEncoding=utf8
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
application: # 设置应用的基本信息(名称
name: microservice-student
profiles: provider-1001
eureka:
instance:
hostname: localhost #eureka消费者主机实例名称
appname: microservice-student #消费者服务名
instance-id: microservice-student:1001 #消费者实例名称
prefer-ip-address: true #是否显示IP
client:
service-url:
#设置与Eureka注册中心交互的地址,是所有注册中心
defaultZone: http://eureka2001.wxm.com:2001/eureka/,http://eureka2002.wxm.com:2002/eureka/,http://eureka2003.wxm.com:2003/eureka/ #把服务注册到eureka注册中心
info:
groupId: com.wxm.springcloud
artifactId: microservice-student-provider-1001
version: 1.0-SNAPSHOT
userName: http://www.wxm.com
phone: 123456
---
server:
port: 1002
context-path: /
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:2206/test?useUnicode=true&characterEncoding=utf8
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
application: # 设置应用的基本信息(名称
name: microservice-student
profiles: provider-1002
eureka:
instance:
hostname: localhost #eureka消费者主机实例名称
appname: microservice-student #消费者服务名
instance-id: microservice-student:1002 #消费者实例名称
prefer-ip-address: true #是否显示IP
client:
service-url:
#设置与Eureka注册中心交互的地址,是所有注册中心
defaultZone: http://eureka2001.wxm.com:2001/eureka/,http://eureka2002.wxm.com:2002/eureka/,http://eureka2003.wxm.com:2003/eureka/ #把服务注册到eureka注册中心
info:
groupId: com.wxm.springcloud
artifactId: microservice-student-provider-1002
version: 1.0-SNAPSHOT
userName: http://www.wxm.com
phone: 123456
---
server:
port: 1003
context-path: /
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:2206/test?useUnicode=true&characterEncoding=utf8
username: root
password: root
jpa:
hibernate:
ddl-auto: update
show-sql: true
application: # 设置应用的基本信息(名称
name: microservice-student
profiles:
eureka:
instance:
hostname: localhost #eureka消费者主机实例名称
appname: microservice-student #消费者服务名
instance-id: microservice-student:1003 #消费者实例名称
prefer-ip-address: true #是否显示IP
client:
service-url:
#设置与Eureka注册中心交互的地址,是所有注册中心
defaultZone: http://eureka2001.wxm.com:2001/eureka/,http://eureka2002.wxm.com:2002/eureka/,http://eureka2003.wxm.com:2003/eureka/ #把服务注册到eureka注册中心
info:
groupId: com.wxm.springcloud
artifactId: microservice-student-provider-1003
version: 1.0-SNAPSHOT
userName: http://www.wxm.com
phone: 123456
处理消费者发过来的请求
package com.wxm.microservicestudentprovider.controller;
import com.wxm.microservicecommon.entity.Student;
import com.wxm.microservicestudentprovider.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/student")
public class StudentProviderController {
@Value("${server.port}")
private String port;
@Autowired
private StudentService studentService;
@PostMapping(value="/save")
public boolean save(Student student){
try{
studentService.save(student);
return true;
}catch(Exception e){
return false;
}
}
@GetMapping(value="/list")
public List<Student> list(){
return studentService.list();
}
@GetMapping(value="/get/{id}")
public Student get(@PathVariable("id") Integer id){
return studentService.findById(id);
}
@GetMapping(value="/delete/{id}")
public boolean delete(@PathVariable("id") Integer id){
try{
studentService.delete(id);
return true;
}catch(Exception e){
return false;
}
}
@RequestMapping("/ribbon")
public String ribbon(){
return "工号【"+port+"】正在为您服务";
}
}
package com.wxm.microservicestudentprovider.service;
import com.wxm.microservicecommon.entity.Student;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
/**
* @author wxm
* @site www.wxm.com
* @company xxx公司
* @create 2020-01-10 10:58
*/
public interface StudentService {
public boolean save(Student student);
public List<Student> list();
public Student get(@PathVariable("id") Integer id);
public boolean delete(@PathVariable("id") Integer id);
public String ribbon();
public Student findById(@PathVariable("id") Integer id);
}
package com.wxm.microservicestudentprovider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EntityScan("com.wxm.*.*")
@EnableEurekaClient
@SpringBootApplication
public class MicroserviceStudentProviderApplication {
public static void main(String[] args) {
SpringApplication.run(MicroserviceStudentProviderApplication.class, args);
}
}
启动三合一(集群)注册中心 ->三合一(集群)生产者
先测试服务提供者:
http://localhost:1001/student/list
http://localhost:1002/student/list
http://localhost:1003/student/list
看看是否有结果;
再测试下 eureka:
http://eureka2001.wxm.com:2001/
http://eureka2002.wxm.com:2002/
http://eureka2003.wxm.com:2003/
有这种的话,就说明没问题;
然后再启动服务消费者:
http://localhost/student/list 多刷新几次 看控制台,我们看到 有默认的轮询策略,访问对应的服务提供者;
但是这种默认的轮询策略肯定是不能满足实际需求的,比如有3个服务提供者,突然挂了一个,这样的话,默认轮询 ,总有1/3的概率访问失败;
服务消费端 SpringCloudConfig配置类
指定IRule实现;
这里我们演示用 RetryRule,大伙可以自行测试;
指定IRule实现;
这里我们演示用 RetryRule,大伙可以自行测试;
package com.wxm.microservicestudentconsumer80.config;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RetryRule;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
@EnableEurekaClient
public class SpringCloudConfig {
@LoadBalanced // 引入ribbon负载均衡
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
/**
* 自定义轮询算法
* @return
*/
@Bean
public IRule myRule(){
return new RetryRule();
}
}
重新创建一个消费者: microservice-student-consumer-feign-80
此pom.xml,和yml文件都不变。
controller改变成了这个,变成了从common项目里获取一个service,并注入里面
StudentConsumerController
common
package com.wxm.microservicecommon.service;
import com.wxm.microservicecommon.entity.Student;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
/**
* @author wxm
* @site www.wxm.com
* @company xxx公司
* @create 2020-01-12 20:52
*/
/**
* Student Feign接口消费者
* @author Administrator
*
*/
@FeignClient(value="MICROSERVICE-STUDENT")
public interface StudentClientService {
/**
* 根据id查询学生信息
* @param id
* @return
*/
@GetMapping(value="/student/get/{id}")
public Student get(@PathVariable("id") Integer id);
/**
* 查询学生信息
* @return
*/
@GetMapping(value="/student/list")
public List<Student> list();
/**
* 添加或者修改学生信息
* @param student
* @return
*/
@PostMapping(value="/student/save")
public boolean save(Student student);
/**
* 根据id删除学生信息
* @return
*/
@GetMapping(value="/student/delete/{id}")
public boolean delete(@PathVariable("id") Integer id);
@RequestMapping("/student/ribbon")
public String ribbon();
}
MicroserviceStudentConsumerFeign80Application
package com.wxm.microservicestudentconsumerfeign80;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import sun.awt.SunHints.Value;
@EnableFeignClients(value="com.wxm.*.*")
@EnableEurekaClient
@SpringBootApplication
public class MicroserviceStudentConsumerFeign80Application {
public static void main(String[] args) {
SpringApplication.run(MicroserviceStudentConsumerFeign80Application.class, args);
}
}
因为这里把消费者的control抽取到Common里去了
现在用Fiegn,所以把restTemplate去掉,改成注入service,调用service方法来实现服务的调用;调用的是 com.wxm.microservicecommon.service.StudentClientService1里的方法
package com.wxm.microservicestudentconsumerfeign80.controller;
import com.wxm.microservicecommon.entity.Student;
import com.wxm.microservicecommon.service.StudentClientService1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
@RequestMapping("/student")
public class StudentConsumerFeignController {
@Autowired
private StudentClientService1 studentClientService;
// private final static String SERVER_IP_PORT = "http://localhost:1001";
// private final static String SERVER_IP_PORT = "http://MICROSERVICE-STUDENT";
// @Autowired
// private RestTemplate restTemplate;
@PostMapping(value="/save")
private boolean save(Student student){
return studentClientService.save(student);
}
@GetMapping(value="/list")
public List<Student> list(){
return studentClientService.list();
}
@GetMapping(value="/get/{id}")
public Student get(@PathVariable("id") Integer id){
return studentClientService.get(id);
}
@GetMapping(value="/delete/{id}")
public boolean delete(@PathVariable("id") Integer id){
try{
studentClientService.delete(id);
return true;
}catch(Exception e){
return false;
}
}
@RequestMapping("/ribbon")
public String ribbon(){
return studentClientService.ribbon();
}
}
测试
使用了feign就不会调用宕机的服务啦!!!