Ribbon作为后端负载均衡器,比Nginx更注重的是承担并发而不是请求分发,可以直接感知后台动态变化来指定分发策略。
一、第一步新建ribbon服务端
1、pom.xml配置如下:
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lovnx</groupId>
<artifactId>micro-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>ribbon</artifactId>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</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>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties内容如下:
spring.application.name=ribbon
server.port=7073
eureka.client.serviceUrl.defaultZone=http://localhost:7070/eureka/
service-B.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule
#ribbon.eureka.enabled=false
注意,这里我用的是RandomRule策略,如上面的
service-B.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule
即为service-B配置该策略。
至于Ribbon各策略的不同,可以参考该文章:https://blog.csdn.net/zhizhuodewo6/article/details/81905910
2、Application内容如下,需要添加俩@Bean
package com.lovnx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
@SpringBootApplication
@EnableDiscoveryClient
public class RibbonApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public IRule ribbonRule() {
return new RandomRule();
}
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
}
注意上面得到ribbonRule()方法返回的策略应与application.properties中配置的策略一样。
3、然后新建Conroller,用于统一作为访问/add接口的入口。
package com.lovnx.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private LoadBalancerClient loadBalancerClient;
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(@RequestParam Integer a,@RequestParam Integer b) {
this.loadBalancerClient.choose("service-B");//随机访问策略
return restTemplate.getForEntity("http://service-B/add?a="+a+"&b="+b, String.class).getBody();
}
}
二、第二步,新建俩id为service-B的服务,这样才能测试负载均衡。
三、第三步,新建第一个Service-B服务。
1、pom内容如下:
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.lovnx</groupId>
<artifactId>micro-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>service-B</artifactId>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- guava 是一个工具集 -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>14.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
<!--Spring cloud framework end-->
<!--MySQL start-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!--MySQL end-->
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
该服务,用到了mybatis、mysql、redis。
2、application.properties内容如下:
spring.application.name=service-B
server.port=7075
eureka.client.serviceUrl.defaultZone=http://localhost:7070/eureka/
mysqldb.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8&zeroDateTimeBehavior=convertToNull
mysqldb.datasource.username=root
mysqldb.datasource.password=root
mysqldb.datasource.driverClassName=com.mysql.jdbc.Driver
mysqldb.datasource.initialSize=1
mysqldb.datasource.minIdle=1
mysqldb.datasource.maxIdle=5
mysqldb.datasource.maxActive=50
mysqldb.datasource.maxWait=10000
mysqldb.datasource.timeBetweenEvictionRunsMillis=10000
mysqldb.datasource.minEvictableIdleTimeMillis=300000
mysqldb.datasource.validationQuery=select 'x'
mysqldb.datasource.testWhileIdle=true
mysqldb.datasource.testOnBorrow=false
mysqldb.datasource.testOnReturn=false
mysqldb.datasource.poolPreparedStatements=true
mysqldb.datasource.maxOpenPreparedStatements=20
mysqldb.datasource.filters=stat
mysqldb.datasource.mapperLocations=classpath:mapper/*.xml
mysqldb.datasource.typeAliasPackage=com.lovnx.entity
#pagehelper
pagehelper.helperDialect=mysql
pagehelper.reasonable=false
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
#when SpringBoot occurs 404 ,throw a Exception directly
spring.mvc.throw-exception-if-no-handler-found=true
#Whether to open the default resource processing, the default is true
spring.resources.add-mappings=false
注意这里的spring.application.name=service-B这个值与下一个Servic-B必须一样,这样才能让ribbon统一管理。
3、新建一个controller,定义访问/add的接口。该类内容如下:
package com.lovnx.web;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.lovnx.entity.InterfaceLimit;
import com.lovnx.service.InterfaceLimitService;
import redis.clients.jedis.Jedis;
@RestController
public class ComputeController {
private final Logger logger = Logger.getLogger(getClass());
@Autowired
private InterfaceLimitService service;
//单位时间内的调用次数
private int flag = 10;
//单位时间1000ms * 60 = 1min
private static int timeRound = 1000*60;
//用来标记调用次数
private static AtomicLong num = new AtomicLong(0);
@Autowired
private DiscoveryClient client;
// static{
// Timer timer = new Timer();
// timer.schedule(new TimerTask(){
// @Override
// public void run() {
// num.set(0);;
// }
// }, 0, timeRound);
// }
@RequestMapping(value = "/add" ,method = RequestMethod.GET)
public String add(@RequestParam Integer a, @RequestParam Integer b) {
// num.incrementAndGet();
//
// if (num.get() <= flag) {
// ServiceInstance instance = client.getLocalServiceInstance();
// Integer r = a + b;
// logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
// return "From Service-B, Result is " + r+"\nPort:"+instance.getPort();
// }
// return "调用次数超限,一分钟内最多只能调用10次!";
InterfaceLimit limit = service.getEntityByPri(1);
Jedis jedis = RedisUtils.getJedis();
//redis存的超时时间
String timeRound_1 = jedis.get("timeRound_1");
//如果不存在或者是不等于数据库设置值
if (timeRound_1 == null || !limit.getUnitTime().toString().equals(timeRound_1)) {
//重新设置超时时间
jedis.set("timeRound_1", limit.getUnitTime().toString());
jedis.expire("num_1", limit.getUnitTime());
}
String num_1 = jedis.get("num_1");
if (num_1 == null) {
jedis.set("num_1", String.valueOf(0));
jedis.expire("num_1", limit.getUnitTime());
}
jedis.incr("num_1");
if (Integer.parseInt(jedis.get("num_1")) <= limit.getUnitNum()) {
ServiceInstance instance = client.getLocalServiceInstance();
Integer r = a + b;
logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
return "From Service-B, Result is " + r+"\nPort:"+instance.getPort();
}
return "调用次数超限!";
}
}
四、第四步,新建service-B2,该model与上面个model基本一样,只不过没有上一个model复杂,但是application.name一样,并且也提供了/add接口。
五、新建完所有服务后。先启动eureka-server,然后启动ribbon,然后启动俩service-B。
六、然后通过浏览器访问http://localhost:7073/add?a=1&b=2
然后会看到,通过几次访问,可以随机得到两种结果:
第一种结果为:From Service-B, Result is 3 Port:7076
第二种结果为:From Service-B, Result is 3 Port:7075
这样可以看到ribbon起作用了。
项目代码下载地址:https://download.csdn.net/download/zhizhuodewo6/10617379