1、微服务调用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依赖
<!--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 文件
server:
port: 80
context-path: /
eureka:
client:
service-url:
defaultZone: http://eureka2001:2001/eureka/,http://eureka2002:2002/eureka/,http://eureka2003:2003/eureka/
register-with-eureka: false
ribbon结合eureka来调用服务提供者;
SpringCloudConfig需要加个负载均衡配置 @LoadBalanced
ribbon和eureka——进行整合
这里还有一个,要修改下StudentConsumerController的PRE_HOST,改成指定的微服务应用名称;
当然这里要先在服务提供者 microservice-student-provider-1001的application.yml加下配置,指定下应用名称:
application:
name: microservice-student
绿色线标记的就是我们设置微服务应用名称
运行:
http://localhost/student/list
2、Ribbon负载均衡
前面搭建了初步例子,但是还没实现真正负载均衡,我们这里要先搞三个服务提供者集群,然后才能演示负载均衡,以及负载均衡策略;
新建一个项目 microservice-student-provider 和我上一篇博客写的Eureka集群一样。三合一
导入pom依赖:
<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.hyf</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>
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/tb_student?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:2001/eureka/,http://eureka2002:2002/eureka/,http://eureka2003:2003/eureka/
info:
groupId: com.hyf.testSpringcloud
artifactId: microservice-student-provider-1001
version: 1.0-SNAPSHOT
userName: http://hyf.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/tb_student?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:2001/eureka/,http://eureka2002:2002/eureka/,http://eureka2003:2003/eureka/
info:
groupId: com.hyf.testSpringcloud
artifactId: microservice-student-provider-1002
version: 1.0-SNAPSHOT
userName: http://hyf.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/tb_student?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:2001/eureka/,http://eureka2002:2002/eureka/,http://eureka2003:2003/eureka/
info:
groupId: com.hyf.testSpringcloud
artifactId: microservice-student-provider-1003
version: 1.0-SNAPSHOT
userName: http://hyf.com
phone: 123456
复制上一篇博客(microservice-student-provider-1001)里的方法:
启动类加上所需的注解:
写一个方法测试消费者访问不同的服务者
服务者中加入:
StudentProviderController.java
@Value("${server.port}")
private String port;
@RequestMapping("/ribbon")
public String ribbon(){
return "工号【"+port+"】正在为您服务";
}
消费者中加入:
@RequestMapping("/ribbon")
public String ribbon(){
return restTemplate.getForObject(SERVER_IP_PORT + "/student/ribbon", String.class);
}
启动项目:
当我刷新页面时,【】里的值会发生变化 1001 1002 1003
注意:
这种默认的轮询策略肯定是不能满足实际需求的; 所以我们看下ribbon默认给我们提供的策略有哪些;
策略名 | 策略声明 | 策略描述 | 实现说明 |
---|---|---|---|
BestAvailableRule | public class BestAvailableRule extends ClientConfigEnabledRoundRobinRule | 选择一个最小的并发请求的server | 逐个考察Server,如果Server被tripped了,则忽略,在选择其中ActiveRequestsCount最小的server |
– | – | – | – |
AvailabilityFilteringRule | public class AvailabilityFilteringRule extends PredicateBasedRule | 过滤掉那些因为一直连接失败的被标记为circuit tripped的后端server,并过滤掉那些高并发的的后端server(active connections 超过配置的阈值) | 使用一个AvailabilityPredicate来包含过滤server的逻辑,其实就就是检查status里记录的各个server的运行状态 |
– | – | – | – |
WeightedResponseTimeRule | public class WeightedResponseTimeRule extends RoundRobinRule | 根据响应时间分配一个weight,响应时间越长,weight越小,被选中的可能性越低。 | 一个后台线程定期的从status里面读取评价响应时间,为每个server计算一个weight。Weight的计算也比较简单responsetime 减去每个server自己平均的responsetime是server的权重。当刚开始运行,没有形成status时,使用roubine策略选择server。 |
– | – | – | – |
RetryRule | public class RetryRule extends AbstractLoadBalancerRule | 对选定的负载均衡策略机上重试机制。 | 在一个配置时间段内当选择server不成功,则一直尝试使用subRule的方式选择一个可用的server |
– | – | – | – |
RoundRobinRule | public class RoundRobinRule extends AbstractLoadBalancerRule | roundRobin方式轮询选择server | 轮询index,选择index对应位置的server |
– | – | – | – |
RandomRule | public class RandomRule extends AbstractLoadBalancerRule | 随机选择一个server | 在index上随机,选择index对应位置的server |
– | – | – | – |
ZoneAvoidanceRule | public class ZoneAvoidanceRule extends PredicateBasedRule | 复合判断server所在区域的性能和server的可用性选择server | 使用ZoneAvoidancePredicate和AvailabilityPredicate来判断是否选择某个server,前一个判断判定一个zone的运行性能是否可用,剔除不可用的zone(的所有server),AvailabilityPredicate用于过滤掉连接数过多的Server。 |
默认7个策略,根据具体产品需求,我们选用;
代码中如何假如呢;
服务消费端 SpringCloudConfig配置类
指定IRule实现;
这里我们演示用 RetryRule,大伙可以自行测试;
package com.hyf.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 {
@LoadBalanced // 引入ribbon 负载均衡
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
/**
* 自定义轮询算法
* @return
*/
@Bean
public IRule myRule(){
return new RetryRule();
}
}
3、Feign简介及应用
简介
声明式服务调用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,后面再说。
应用
1、在common项目里建一个service(实际项目肯定是多个service)作为Feign客户端,用Feign客户端来调用服务器提供者,当然可以配置负载均衡;Feign客户端定义的目的,就是为了方便给其他项目调用;
修改 microservice-common
pom.xml引入Feign依赖:
<!--引入Feign依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
我们定义了 FeignClient,同时指定了调用的服务名称MICROSERVICE-STUDENT
common项目修改后,maven clean下 然后install下;
package com.hyf.microservicecommon.server;
import com.hyf.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;
/**
* 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();
}
2、新建一个Feign消费者项目;
参考microservice-student-consumer-80建一个microservice-student-consumer-feign-80
代码都复制一份,包括pom.xml
pom依赖
<parent>
<groupId>com.hyf</groupId>
<artifactId>microservice</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>
</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.hyf</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>
</dependencies>
SpringCloudConfig.java
package com.hyf.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 {
@LoadBalanced // 引入ribbon 负载均衡
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
/**
* 自定义轮询算法
* @return
*/
@Bean
public IRule myRule(){
return new RetryRule();
}
}
Yml文件
server:
port: 80
context-path: /
eureka:
client:
service-url:
defaultZone: http://eureka2001:2001/eureka/,http://eureka2002:2002/eureka/,http://eureka2003:2003/eureka/
register-with-eureka: false
3、修改启动类名称,和加注解
启动类名称改下,改成StudentConsumerFeignApplication_80,同时加个注解@EnableFeignClients
支持下Feign;
StudentConsumerController.java
因为现在用Fiegn,所以把restTemplate去掉,改成注入service,调用service方法来实现服务的调用;
package com.hyf.microservicestudentconsumerfeign80.controller;
import com.hyf.microservicecommon.entity.Student;
import com.hyf.microservicecommon.server.StudentClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/student")
public class StudentConsumerController {
@Autowired
private StudentClientService studentClientService;
@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();
}
}
5、测试
当我关掉一个服务者,刷新页面时,关掉的就不会在访问呢?