目的:

    微服务调用Ribbon

    Ribbon负载均衡

    Feign简介及应用


微服务调用Ribbon

  Ribbon简介

  1. 负载均衡框架,支持可插拔式的负载均衡规则

  2. 支持多种协议,如HTTP、UDP等

  3. 提供负载均衡客户端

Ribbon是Netflix发布的负载均衡器,它有助于控制HTTP和TCP的客户端的行为。为Ribbon配置服务提供者地址后,Ribbon就可基于某种负载均衡算法,自动地帮助服务消费者去请求。Ribbon默认为我们提供了很多负载均衡算法,例如轮询、随机等。当然,我们也可为Ribbon实现自定义的负载均衡算法。

在Spring Cloud中,当Ribbon与Eureka配合使用时,Ribbon可自动从Eureka Server获取服务提供者地址列表,并基于负载均衡算法,请求其中一个服务提供者实例。展示了Ribbon与Eureka配合使用时的架构。

初步应用

Ribbon是客户端负载均衡,所以肯定集成再消费端,也就是consumer端

我们修改microservice-student-consumer-80(工程我是在上一篇博客中玩集成建成https://www.cnblogs.com/huangting/p/11902121.html

首先,引入依赖,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配置

server:
port: 80
context-path: /
eureka:
client:
service-url:
defaultZone: http://eureka2001.ht.com:2001/eureka/,http://eureka2002.ht.com:2002/eureka/,http://eureka2003.ht.com:2003/eureka/
register-with-eureka: false

ribbon结合eureka来调用服务提供者;

SpringCloudConfig也改成 要加个负载均衡配置 @LoadBalanced

因为和eureka整合,所以启动类StudentConsumerApplication_80 加个注解 @EnableEurekaClient

在提供者microservice-student-provider-1001的yml文件中添加配置:

  application:
name: microservice-student

上面配置好后,我们可以测试下

先启动三个eureka,然后再启动服务提供者,再启动服务消费者;

访问http://localhost/student/list


Ribbon负载均衡

按照它microservice-student-provider-1001建立一个microservice-student-provider子项目,然后将microservice-student-provider-1001这个子项目干掉;

前面搭建了初步例子,但是还没实现真正负载均衡,我们这里要先搞三个服务提供者集群,然后才能演示负载均衡,以及负载均衡策略;

新建项目microservice-student-provider-1002,microservice-student-provider-1003

pom.xml,application.yml,以及java类都复制一份,启动类名称对应的改下;

yml配置文件有两处要对应的改下,port端口改下,以及服务实例名称改下;

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.ht</groupId>
<artifactId>htSpringCloud</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.ht</groupId>
<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>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</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>

配置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/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
appname: microservice-student
instance-id: microservice-student:1001
prefer-ip-address: true
client:
service-url:
defaultZone: http://eureka2001.ht.com:2001/eureka/,http://eureka2002.ht.com:2002/eureka/,http://eureka2003.ht.com:2003/eureka/ info:
groupId: com.ht.htSpringCloud
artifactId: microservice-student-provider-1001
version: 1.0-SNAPSHOT
userName: http://ht.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/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
appname: microservice-student
instance-id: microservice-student:1002
prefer-ip-address: true
client:
service-url:
defaultZone: http://eureka2001.ht.com:2001/eureka/,http://eureka2002.ht.com:2002/eureka/,http://eureka2003.ht.com:2003/eureka/ info:
groupId: com.ht.htSpringCloud
artifactId: microservice-student-provider-1002
version: 1.0-SNAPSHOT
userName: http://ht.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/test?useUnicode=true&characterEncoding=utf8
username: root
password: root
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.ht.com:2001/eureka/,http://eureka2002.ht.com:2002/eureka/,http://eureka2003.ht.com:2003/eureka/ info:
groupId: com.ht.htSpringCloud
artifactId: microservice-student-provider-1003
version: 1.0-SNAPSHOT
userName: http://ht.com
phone: 123456

启动类中添加注解

package com.ht.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.ht.*.*")
@EnableEurekaClient
@SpringBootApplication
public class MicroserviceStudentProviderApplication { public static void main(String[] args) {
SpringApplication.run(MicroserviceStudentProviderApplication.class, args);
} }

在消费者microservice-student-provider-80的controller中加:

    @RequestMapping("/ribbon")
public String ribbon(){
return restTemplate.getForObject(SERVER_IP_PORT+"/student/ribbon/", String.class);
}

生产者microservice-student-providerd controller中加:

  @Value("${server.port}")
private String port; @RequestMapping("/ribbon")
public String ribbon(){
return "工号【"+port+"】正在为您服务";
}

我们启动服务后在浏览器中刷新地址

每刷新一次后台就会更改一次服务工号

假如有3个服务提供者,突然挂了一个,那么就会产生1/3的概率访问失败; 所以ribbon给我们提供了一个很好的插件。

在microservicestudentconsumer80的

SpringCloudConfig中 加:

/**
* 自定义调用规则(服务提供者掉线后不再调用,解决轮询问题)
* @return
*/
@Bean
public IRule myRule(){
return new RetryRule();
// return new RandomRule();
}

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,后面再说。

  • 应用

  在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>

创建StudentClientService接口:

package com.ht.microservicecommon;

import com.ht.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();
}

  新建一个Feign消费者项目;

参考microservice-student-consumer-80建一个microservice-student-consumer-feign-80

代码都复制一份,包括pom.xml

新项目中需要添加新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> <!--引入Feign依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>

SpringCloudconig

package com.ht.microservicestudentconsumerfeign80.config;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
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: 80
context-path: /
eureka:
client:
service-url:
defaultZone: http://eureka2001.ht.com:2001/eureka/,http://eureka2002.ht.com:2002/eureka/,http://eureka2003.ht.com:2003/eureka/
register-with-eureka: false

启动类中添加注释

package com.ht.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.ht.*.*")
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MicroserviceStudentConsumerFeign80Application { public static void main(String[] args) {
SpringApplication.run(MicroserviceStudentConsumerFeign80Application.class, args);
} }

StudnetConsumerController

package com.javaxl.microservicestudentconsumerfeign80.controller;

import com.ht.microservicecommon.StudentClientService;
import com.ht.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 { @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方法来实现服务的调用;

谢谢观看!!

SpringCloud之Ribbon负载均衡及Feign消费者调用服务的更多相关文章

  1. Ribbon负载均衡及Feign消费者调用服务

    微服务调用Ribbon 简介 前面讲了eureka服务注册与发现,但是结合eureka集群的服务调用没讲. 这里的话 就要用到Ribbon,结合eureka,来实现服务的调用: Ribbon是Netf ...

  2. spring-cloud配置ribbon负载均衡

    spring-cloud配置ribbon负载均衡 ribbon提供的负载均衡就是开箱即用的,简单的不能再简单了 为了顺利演示此demo,你需要如下 需要提前配置eureka服务端,具体看 https: ...

  3. SpringCloud系列——Ribbon 负载均衡

    前言 Ribbon是一个客户端负载均衡器,它提供了对HTTP和TCP客户端的行为的大量控制.我们在上篇(猛戳:SpringCloud系列——Feign 服务调用)已经实现了多个服务之间的Feign调用 ...

  4. 浅谈SpringCloud (三) Ribbon负载均衡

    什么是负载均衡 当一台服务器的单位时间内的访问量越大时,服务器压力就越大,大到超过自身承受能力时,服务器就会崩溃.为了避免服务器崩溃,让用户有更好的体验,我们通过负载均衡的方式来分担服务器压力. 我们 ...

  5. SpringCloud:Ribbon负载均衡

    1.概述 Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端       负载均衡的工具. 简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客 ...

  6. 四(2)、springcloud之Ribbon负载均衡

    2.Ribbon负载均衡 ​ Ribbon在工作时分成两步第一步先选择 EurekaServer ,它优先选择在同一个区域内负载较少的server. 第二步再根据用户指定的策略,在从server取到的 ...

  7. Spring-cloud之Ribbon负载均衡的使用及负载均衡策略配置(与Eurka配合使用)

    什么是Ribbon,ribbon有什么用,个人先总结一下(不正确请提出讨论):Ribbon是基于客户端的负载均衡器,为我们提供了多样的负载均衡的方案,比如轮询,最小的并发请求的server,随机ser ...

  8. SpringCloud之Ribbon负载均衡配置

    一.负载均衡解决方案分类及特征 业界主流的负载均衡解决方案有: 1.1 集中式负载均衡 即在客户端和服务端之间使用独立的负载均衡设施(可以是硬件,如F5, 也可以是软件,如nginx), 由该设施负责 ...

  9. Spring-Cloud之Ribbon负载均衡-3

    一.负载均衡是指将负载分摊到多个执行单元上,常见的负载均衡有两种方式.一种是独立进程单元,通过负载均衡策略,将请求转发到不同的执行单元上,例如 Ngnix .另一种是将负载均衡逻辑以代码的形式封装到服 ...

随机推荐

  1. xmind 破解

    邮箱:x@iroader 序列号: XAka34A2rVRYJ4XBIU35UZMUEEF64CMMIYZCK2FZZUQNODEKUHGJLFMSLIQMQUCUBXRENLK6NZL37JXP4P ...

  2. Android中创建自定义控件

    1.创建一个TitleLayout继承LinearLayout: //创建自定义控件 public class TitleLayout extends LinearLayout { private f ...

  3. [web 前端] Npm package.json与package-lock.json文件的作用

    本文链接:https://blog.csdn.net/u013992330/article/details/81110018 最新版nodejs中,多了一个package-lock.json文件,刚开 ...

  4. postMan下使用xdebug

    增加 ?XDEBUG_SESSION_START=PHPSTORM 例: {{url}}/manage/getuserinfo?XDEBUG_SESSION_START=PHPSTORM

  5. cas 3.5.3服务器搭建+spring boot集成+shiro模拟登录(不修改现有shiro认证架构)

    因为现有系统外部接入需要,需要支持三方单点登录.由于系统本身已经是微服务架构,由多个业务独立的子系统组成,所以有自己的用户认证微服务(不是cas,我们基础设施已经够多了,现在能不增加就不增加).但是因 ...

  6. 运维笔记--ubuntu服务器安装telnet服务

    ubuntu 16.04 安装Telnet: Telnet协议是TCP/IP协议族中的一员,是Internet远程登陆服务的标准协议和主要方式.可以通过Telnet实现远程登录服务器,同时也可以用“t ...

  7. matlab学习笔记7-定时器

    一起来学matlab-matlab学习笔记7-定时器 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考书籍 <matlab 程序设计与综合应用>张德丰等著 感谢张老师的书籍,让 ...

  8. ios开发 需要注意的地方、注意事项

    /* 一.LaunchScreenLaunchScreen产生原因:代替之前的启动图片好处:1.可以展示更多的东西2.可以只需要出一个尺寸的图片. 启动图片的优先级启动图片 < LaunchSc ...

  9. 123456123456#6#---###6%%%----com.zzj.DinosourKnown235---前拼show后广--恐龙百科-66666666

    com.zzj.DinosourKnown235---前拼show后广--恐龙百科-

  10. 【翻译】Flink Table Api & SQL —Streaming 概念 —— 时态表

    本文翻译自官网: Temporal Tables https://ci.apache.org/projects/flink/flink-docs-release-1.9/dev/table/strea ...