这篇文章主要介绍了SpringCloud Ribbon负载均衡实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
Spring Cloud集成了Ribbon,结合Eureka,可实现客户端的负载均衡。
下面实现一个例子,结构下图所示。
一、服务器端
1、创建项目
开发工具:IntelliJ IDEA 2019.2.3
IDEA中创建一个新的SpringBoot项目,名称为“cloud-server”,SpringBoot版本选择2.1.10,在选择Dependencies(依赖)的界面勾选Spring Cloud Discovert ->
Eureka Server,创建完成后的pom.xml配置文件自动添加SpringCloud最新稳定版本依赖,当前为Greenwich.SR3。
pom.xml完整内容如下:
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://.example.cloudinvoker;import org.springframework.cloud.client.loadbalancer.LoadBalanced;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.MediaType;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.client.RestTemplate;@RestController@Configurationpublic class InvokerController { @LoadBalanced @Bean public RestTemplate getRestTemplate(){ return new RestTemplate(); } @RequestMapping(value="/router", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE) public String router(){ RestTemplate restTemplate = getRestTemplate(); //根据名称调用服务 String json = restTemplate.getForObject("http://cloud-provider/", String.class); return json; }}四、测试
1、启动服务器端。
2、启动两个服务提供者,在控制台中分别输入8080和8081启动。
3、启动服务调用者。
4、浏览器访问http://localhost:9000/router,多次刷新页面,结果都是:
http://localhost:8081/
服务调用者项目IDEA控制台定时输出:
自定义服务器规则类,输出服务器信息: localhost:8081 localhost:8080自定义Ping类,服务器信息:localhost:8081,状态:true自定义Ping类,服务器信息:localhost:8080,状态:true以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。