使用ribbon之前的准备工作:

  1.你要有两个服务,一个是服务消费方(下图的xing-movie是消费方),一个是服务提供方(xing-user是服务提供者),并且服务提供方要有两个实例,也就是xing-user有两个实例,分别运行在8070和8071端口。

  2.所有服务注册到eureka server中。

    

接下来我们在movie服务使用ribbon实现负载均衡调用中调用user服务,spring cloud使用ribbon很简单

  1.引入依赖,因为user服务的pom.xml中引入了eureka的依赖,eureka的依赖包含了ribbon的依赖所以这一步省略

  2.在movie服务的启动类中加入标红的代码,加入是为了在之后调用的时候可以直接@Autowired  restTemplate,顺便提醒一下,@Autowired是 byType的,不是byName:

  

package com.xing.movie;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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; @SpringBootApplication
@EnableEurekaClient
public class SpringDemoApplication { @Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(SpringDemoApplication.class, args);
}
}

  启动类写好之后我们去controller类中写调用user服务的方法:

     @Autowired
    private RestTemplate restTemplate;

   @ApiOperation(value = "查询用户", notes = "查询用户")//方法说明
@ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = Movie.class)})//响应数据说明,可以有多个
@ApiImplicitParam(name = "name", value = "用户名", paramType = "path", required = true, dataType = "String")
@GetMapping(value = "/findUerByName/{name}",produces = { "application/json;charset=UTF-8" })
public User findUserByName(@PathVariable String name) {
return this.restTemplate.getForObject("http://xing-user/user/findByName/"+name, User.class);
}

  标红的地方要注意使用的是user服务的spring.application.name,这里使用到的user服务在上一篇博客中有具体的代码,最后一行代码中的User.class是返回类型,如果报错那就去user服务中把User类拷贝过来,到目前为止ribbon的简答的负载均衡就搞定了,查看结果

可以看到已经成功的调用到了user服务,并返回了数据,这个时候我们只能说服务调用成功并不能说负载均衡。这个网页我们多刷新几遍,多做几次请求,之后去查看后台数据会发现user1中的控制台打印了数据,user2的控制台也打印了数据,说明负载均衡成功。

简单提一下spring cloud中ribbon的负载均衡算法默认是轮询。那么我们不想使用轮询怎么自定义呢?

我们首先需要创建一个class,根据官方文档这个类必须在启动类能扫描的范围之外,所以这个class定义的位置如下:

RibbonConfig.java:

package com.xing.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule; /**
* Copyright: Copyright (c) 2018 LanRu-Caifu
* @ClassName: RibbonConfig.java
* @Description: 自定义ribbon配置类
* @version: v1.0.0
* @author: zjx
* @date: 2018年11月2日 上午10:08:36
*/ @Configuration
public class RibbonConfig { @Autowired
IClientConfig config; @Bean
@ConditionalOnMissingBean
public IRule ribbonRule(IClientConfig config) {
System.out.println("-------ribbon自定义随机------");
return new RandomRule();
}
}

RibbonConfig.java

movie服务的启动类修改之后如下:

package com.xing.movie;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate; import com.xing.config.RibbonConfig; @SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "xing-user" , configuration = RibbonConfig.class)
public class SpringDemoApplication { @Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(SpringDemoApplication.class, args);
}
}

SpringDemoApplication

最后启动类测试,做了4次请求,user1打印了3次,user2打印了1次

还有其他的很多种配置方式,这里只简单写出这种,以后有空还会补充配置文件的方式等等

源码地址:https://github.com/OnlyXingxing/SpringCloud

使用ribbon实现负载均衡的更多相关文章

  1. Spring Cloud Ribbon——客户端负载均衡

    一.负载均衡负载均衡(Load Balance): 建立在现有网络结构之上,它提供了一种廉价有效透明的方法扩展网络设备和服务器的带宽.增加吞吐量.加强网络数据处理能力.提高网络的灵活性和可用性.其意思 ...

  2. Spring Cloud:使用Ribbon实现负载均衡详解(下)

    在上一篇文章(Spring Cloud:使用Ribbon实现负载均衡详解(上))中,我对 Ribbon 做了一个介绍,Ribbon 可以实现直接通过服务名称对服务进行访问.这一篇文章我详细分析一下如何 ...

  3. springcloud(十二):Ribbon客户端负载均衡介绍

    springcloud(十二):Ribbon客户端负载均衡介绍 Ribbon简介 使用分布式微服务脚骨的应用系统,在部署的时候通常会为部分或者全部微服务搭建集群环境,通过提供多个实例来提高系统的稳定型 ...

  4. spring cloud 系列第3篇 —— ribbon 客户端负载均衡 (F版本)

    源码仓库地址:https://github.com/heibaiying/spring-samples-for-all 一.ribbon 简介 ribbon是Netfix公司开源的负载均衡组件,采用服 ...

  5. Spring Cloud Ribbon客户端负载均衡(四)

    序言 Ribbon 是一个客户端负载均衡器(Nginx 为服务端负载均衡),它赋予了应用一些支配 HTTP 与 TCP 行为的能力,可以得知,这里的客户端负载均衡也是进程内负载均衡的一种.它在 Spr ...

  6. springcloud 之Ribbon客户端负载均衡配置使用

    pom.xml添加配置说明:这里服务注册与发现用的是Eureka,所以消费者端需要引入eureka,使用EurekaClient来调用服务 <dependency> <groupId ...

  7. Ribbon【负载均衡策略】

    ribbon有7种负载均衡策略可供选择: 策略类 命名 描述 RandomRule 随机策略 随机选择server RoundRobinRule 轮询策略 按照顺序选择server(ribbon默认策 ...

  8. 【一起学源码-微服务】Feign 源码三:Feign结合Ribbon实现负载均衡的原理分析

    前言 前情回顾 上一讲我们已经知道了Feign的工作原理其实是在项目启动的时候,通过JDK动态代理为每个FeignClinent生成一个动态代理. 动态代理的数据结构是:ReflectiveFeign ...

  9. SpringCloud微服务实战——搭建企业级开发框架(十二):OpenFeign+Ribbon实现负载均衡

      Ribbon是Netflix下的负载均衡项目,它主要实现中间层应用程序的负载均衡.为Ribbon配置服务提供者地址列表后,Ribbon就会基于某种负载均衡算法,自动帮助服务调用者去请求.Ribbo ...

随机推荐

  1. pytest_参数化3

    import pytesttest_user_data=[ {'user':'linda','password':'8888'}, {'user':'servenruby','password':'1 ...

  2. 用户界面样式(cursor,resize,vertical-align,outline,文字超出显示省略号)

    1. 鼠标样式 cursor default: 小白(箭头)默认 pointer:小手 move:移动 text:文本 not-allowed:禁止 2. 轮廓线(表单外发光)outline 给表单添 ...

  3. 2018-2-13-win10-uwp-资源字典

    title author date CreateTime categories win10 uwp 资源字典 lindexi 2018-2-13 17:23:3 +0800 2018-2-13 17: ...

  4. 关于KiCAD的一些插件

    关于KiCAD的一些插件 https://gitee.com/KiCAD-CN/KiCad-CN-Forum/blob/master/KiCad_help_zh_CN.md#swapit-%E5%B7 ...

  5. show line numbers

  6. 笔记68 Redis数据库

    一.Redis简介 REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统.Redis是一个开源的使用ANSI ...

  7. memcache常用操作

    Command Description Example get 读取键值 get mykey set 设置新键值 set mykey 0 60 5 add 新增键值 add newkey 0 60 5 ...

  8. hdu 5792 线段树+离散化+思维

    题目大意: Given a sequence A with length n,count how many quadruple (a,b,c,d) satisfies: a≠b≠c≠d,1≤a< ...

  9. C之输入输出函数(3) -- 请使用sscanf()

    #include <stdio.h> int fscanf(FILE *__restrict__stream, const char *__restrict__format-string, ...

  10. Delphi GDI+ 安装方法

    [转]Delphi GDI+ 安装方法转自:万一博客(http://www.cnblogs.com/del/)GDI+ 是 Windows 的一个函数库, 来自 Windows\System32\GD ...