转载请标明出处:https://blog.csdn.net/men_ma/article/details/106847165.
本文出自 不怕报错 就怕不报错的小猿猿 的博客
1、微服务调用Ribbon
2、Ribbon负载均衡
3、Feign简介及应用
前面讲了eureka服务注册与发现,但是结合eureka集群的服务调用没讲。
这里的话 就要用到Ribbon,结合eureka,来实现服务的调用;
Ribbon是Netflix发布的负载均衡器,它有助于控制HTTP和TCP的客户端的行为。为Ribbon配置服务提供者地址后,Ribbon就可基于某种负载均衡算法,自动地帮助服务消费者去请求。Ribbon默认为我们提供了很多负载均衡算法,例如轮询、随机等。当然,我们也可为Ribbon实现自定义的负载均衡算法。
在Spring Cloud中,当Ribbon与Eureka配合使用时,Ribbon可自动从Eureka Server获取服务提供者地址列表,并基于负载均衡算法,请求其中一个服务提供者实例。展示了Ribbon与Eureka配合使用时的架构。
ibbon是客户端负载均衡,所以肯定集成再消费端,也就是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>
application.yml加
ribbon结合eureka来调用服务提供者;
server:
port: 8080
context-path: /
eureka:
client:
service-url:
defaultZone: http://eureka2001.javaxl.com:2001/eureka/,http://eureka2002.javaxl.com:2002/eureka/,http://eureka2003.javaxl.com:2003/eureka/
register-with-eureka: false
因为和eureka整合,所以启动类StudentConsumerApplication_80 加个注解 @EnableEurekaClient
SpringCloudConfig也改成 要加个负载均衡配置 @LoadBalanced
package com.xiaoqing.microservicestudentconsumer80.config;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RetryRule;
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 {
/**
* 通过RestTemplate这个协议让消费者与生产者产生数据交互
* restful:操作网络协议的,关于http的增删改查
* @return
*/
@LoadBalanced // 引入ribbon负载均衡
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
这里还有一个,要修改下StudentConsumerController的PRE_HOST,改成指定的微服务应用名称,不能写死了;
当然这里要先在服务提供者microservice-student-provider-1001的application.yml加下配置,指定下应用名称:
application:
name: microservice-student
上面配置好后,我们可以测试下;
先启动eureka,然后再启动服务提供者,再启动服务消费者;
我们现在来看下单节点项目的有没有问题,先启动EurekaServer2001Application(注册中心)-------->Provider1001Application(提供者也是生产者)-------->Consumer80Application(消费者)
执行 http://localhost:8080/student/list
结果就出来了,说明配置OK;
按照它microservice-student-provider-1001建立一个microservice-student-provider(相当于三合一工程,1001,1002,1003)子项目,然后将microservice-student-provider-1001这个子项目干掉;
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>
<parent>
<groupId>com.xiaoqing</groupId>
<artifactId>t243microservice</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>microservice-student-provider</artifactId>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.xiaoqing</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>
前面搭建了初步例子,但是还没实现真正负载均衡,我们这里要先搞三个服务提供者集群,然后才能演示负载均衡,以及负载均衡策略;
新建项目microservice-student-provider-1002,microservice-student-provider-1003
pom.xml,application.yml,以及java类都复制一份,启动类名称对应的改下;
yml配置文件有两处要对应的改下,port端口改下,以及服务实例名称改下;
启动类MicroserviceStudentProviderApplication .java
package com.xiaoqing.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.xiaoqing.*.*"):让jpa去扫描
*/
@EntityScan("com.xiaoqing.*.*")
@EnableEurekaClient
@SpringBootApplication
public class MicroserviceStudentProviderApplication {
public static void main(String[] args) {
SpringApplication.run(MicroserviceStudentProviderApplication.class, args);
}
}
StudentService接口类省略
StudentServiceImpl.java:
package com.xiaoqing.microservicestudentprovider.service.impl;
import com.xiaoqing.microservicecommon.entity.Student;
import com.xiaoqing.microservicestudentprovider.repository.StudentRepository;
import com.xiaoqing.microservicestudentprovider.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author晴sister
* @site https://blog.csdn.net/men_ma
* @company xxx公司
* @create 2020-12-08 11:13
*/
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
@Override
public void save(Student student) {
studentRepository.save(student);
}
@Override
public Student findById(Integer id) {
return studentRepository.findOne(id);
}
@Override
public List<Student> list() {
return studentRepository.findAll();
}
@Override
public void delete(Integer id) {
studentRepository.delete(id);
}
}
StudentRepository接口类:
package com.xiaoqing.microservicestudentprovider.repository;
import com.xiaoqing.microservicecommon.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* jpa的增删改查
*/
public interface StudentRepository extends JpaRepository<Student, Integer>, JpaSpecificationExecutor<Student> {
}
StudentProviderController.java控制类
package com.xiaoqing.microservicestudentprovider.controller;
import com.xiaoqing.microservicecommon.entity.Student;
import com.xiaoqing.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 {
@Autowired
private StudentService studentService;
@Value("${server.port}")
private String port;
@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+"】正在为您服务";
}
}
消费者的StudentConsumerController.java加一个方法
@RequestMapping("/ribbon")
public String ribbon(){
return restTemplate.getForObject(SERVER_IP_PORT + "/student/ribbon", String.class);
}
application.yml
---
server:
port: 1001
context-path: /
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/t243?useUnicode=true&characterEncoding=utf8
username: root
password: 123
jpa:
hibernate:
ddl-auto: update
show-sql: true
application:
name: microservice-student
profiles: provider-1001
eureka:
instance:
hostname: localhost
appname: microservice-student
instance-id: microservice-student:1001
prefer-ip-address: true
client:
service-url:
defaultZone: http://eureka2001.javaxl.com:2001/eureka/,http://eureka2002.javaxl.com:2002/eureka/,http://eureka2003.javaxl.com:2003/eureka/
info:
groupId: com.javaxl.testSpringcloud
artifactId: microservice-student-provider-1001
version: 1.0-SNAPSHOT
userName: http://javaxl.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:3306/t243?useUnicode=true&characterEncoding=utf8
username: root
password: 123
jpa:
hibernate:
ddl-auto: update
show-sql: true
application:
name: microservice-student
profiles: provider-1002
eureka:
instance:
hostname: localhost
appname: microservice-student
instance-id: microservice-student:1002
prefer-ip-address: true
client:
service-url:
defaultZone: http://eureka2001.javaxl.com:2001/eureka/,http://eureka2002.javaxl.com:2002/eureka/,http://eureka2003.javaxl.com:2003/eureka/
info:
groupId: com.javaxl.testSpringcloud
artifactId: microservice-student-provider-1002
version: 1.0-SNAPSHOT
userName: http://javaxl.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:3306/t243?useUnicode=true&characterEncoding=utf8
username: root
password: 123
jpa:
hibernate:
ddl-auto: update
show-sql: true
application:
name: microservice-student
profiles: provider-1003
eureka:
instance:
hostname: localhost
appname: microservice-student
instance-id: microservice-student:1003
prefer-ip-address: true
client:
service-url:
defaultZone: http://eureka2001.javaxl.com:2001/eureka/,http://eureka2002.javaxl.com:2002/eureka/,http://eureka2003.javaxl.com:2003/eureka/
info:
groupId: com.javaxl.testSpringcloud
artifactId: microservice-student-provider-1003
version: 1.0-SNAPSHOT
userName: http://javaxl.com
phone: 123456
启动服务顺序:
先启动注册中心(2001)------->再启动提供者(生产者,1001,1002,1003)-------->再启动消费者(8080)
先测试服务提供者:
http://localhost:1001/student/list
http://localhost:1002/student/list
http://localhost:1003/student/list
看看是否有结果;
再测试下 eureka:
http://eureka2001.javaxl.com:2001/
http://eureka2002.javaxl.com:2002/
http://eureka2003.javaxl.com:2003/
有这种的话,就说明没问题;
然后再启动服务消费者:
http://localhost:8080/student/ribbon 多刷新几次 看控制台,我们看到 有默认的轮询策略,访问对应的服务提供者;
但是这种默认的轮询策略肯定是不能满足实际需求的,比如有3个服务提供者,突然挂了一个,这样的话,默认轮询 ,总有1/3的概率访问失败; 所以我们看下ribbon默认给我们提供的策略有哪些;
默认7个策略,根据具体产品需求,我们选用;
代码中如何假如呢;
服务消费端
SpringCloudConfig配置类
指定IRule实现;
这里我们演示用 RetryRule,大伙可以自行测试;
SpringCloudConfig.java
package com.xiaoqing.microservicestudentconsumer80.config;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RetryRule;
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 {
/**
* 通过RestTemplate这个协议让消费者与生产者产生数据交互
* restful:操作网络协议的,关于http的增删改查
* @return
*/
@LoadBalanced // 引入ribbon负载均衡
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
/**
* 自定义轮询算法
* @return
*/
@Bean
public IRule myRule(){
return new RetryRule();
}
}
用法很简单;
声明式服务调用Feign简单介绍下;
Feign是一个声明式的Web Service客户端,它使得编写Web Serivce客户端变得更加简单。我们只需要使用Feign来创建一个接口并用注解来配置它既可完成。它具备可插拔的注解支持,包括Feign注解和JAX-RS注解。Feign也支持可插拔的编码器和解码器。Spring Cloud为Feign增加了对Spring MVC注解的支持,还整合了Ribbon和Eureka来提供均衡负载的HTTP客户端实现。
这段话看起来比较懵逼,这里说下实际使用,前面Ribbon调用服务提供者,我们通过restTemplate调用,缺点是,多个地方调用,同一个请求要写多次,不方便统一维护,这时候Feign来了,就直接把请求统一搞一个service作为FeignClient,然后其他调用Controller需要用到的,直接注入service,直接调用service方法即可;同时Feign整合了Ribbon和Eureka,所以要配置负载均衡的话,直接配置Ribbon即可,无其他特殊地方;当然Fiegn也整合了服务容错保护,断路器Hystrix,后面再说。
<!--引入Feign依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
我们定义了 FeignClient,同时指定了调用的服务名称MICROSERVICE-STUDENT
common项目修改后,maven clean下 然后install下;
建StudentClientService接口;
package com.xiaoqing.microservicecommon.service;
import com.xiaoqing.microservicecommon.entity.Student;
import org.springframework.cloud.netflix.feign.FeignClient;
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;
/**
1. Student Feign接口客户端
2. @author Administrator
3. */
@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();
}
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.xiaoqing</groupId>
<artifactId>t243microservice</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>microservice-student-consumer-feign-80</artifactId>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.javaxl</groupId>
<artifactId>microservice-common</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-test</artifactId>
<scope>test</scope>
</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>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>com.xiaoqing</groupId>
<artifactId>microservice-common</artifactId>
<version>1.0-SNAPSHOT</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>
<!--引入Feign依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
SpringCloudConfig.java
package com.xiaoqing.microservicestudentconsumerfeign80.config;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RetryRule;
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();
}
/**
* 自定义调用规则(服务提供者掉线后不再调用,解决轮询问题)
* @return
*/
@Bean
public IRule myRule(){
return new RetryRule();
// return new RandomRule();
}
}
Yml文件
server:
port: 8080
context-path: /
eureka:
client:
service-url:
defaultZone: http://eureka2001.javaxl.com:2001/eureka/,http://eureka2002.javaxl.com:2002/eureka/,http://eureka2003.javaxl.com:2003/eureka/
register-with-eureka: false
修改启动类名称,和加注解
启动类名称改下,改成StudentConsumerFeignApplication_80,同时加个注解@EnableFeignClients
支持下Feign;
package com.xiaoqing.microservicestudentconsumerfeign80;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@EnableEurekaClient
@EnableFeignClients(value = "com.xiaoqing.*.*")
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MicroserviceStudentConsumerFeign80Application {
public static void main(String[] args) {
SpringApplication.run(MicroserviceStudentConsumerFeign80Application.class, args);
}
}
StudentConsumerController.java
package com.xiaoqing.microservicestudentconsumerfeign80.controller;
import com.xiaoqing.microservicecommon.entity.Student;
import com.xiaoqing.microservicecommon.service.StudentClientService;
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 {
@Autowired
private StudentClientService studentClientService;
@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();
}
}
因为现在用Fiegn,所以把restTemplate去掉,改成注入service,调用service方法来实现服务的调用;
5、测试负载均衡;
SpringCloudConfig类的myRule,大伙自行修改测试即可;
启动顺序:
测试结果:注册中心的结果与初步应用的结果一样
当我把1002的服务给挡掉时(停止运行),在没用Feign时,那么整个注册中心都会挡掉(1001,1002,1003都会停止服务),我再去刷新http://localhost:8080/student/ribbon这个访问地址时,只会出现1001,1003的工号在服务,用了Feign才会解决这个问题,这就是Feign的体现