您的位置:首页 > 编程语言 > Java开发

使用Ribbon实现客户端负载均衡

2018-01-05 11:07 567 查看


Ribbon的介绍

Ribbon 是 Netflix发布的负载均衡器,他有助于控制HTTP和TCP客户端的行为。Ribbon 基于某种负载均衡的算法。

Ribbon 为我们提供了负载均衡的算法,例如:轮询,随机,也可以自定义负载均衡算法。在spring  cloun中。和Eureka Server 一起使用的 可以自动获取Eureka Server 的服务者所提供的地址
Ribbon 与Eureka 配合使用的架构图



为服务消费者整合Ribbon 

复制microservice-simple-consumer-movie项目为microservice-consumer-movie-ribbon

之前的jpa,和数据库配置是不变的,修改zMovieController.java
package com.zjm.contoller;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.zjm.user.User;

import scala.sys.process.processInternal;

@RestController
@SpringBootApplication
public class MovieController {
private static final org.slf4j.Logger LOGGER=LoggerFactory.getLogger(MovieController.class);
@Autowired
public RestTemplate restTemplate;
@Autowired
private LoadBalancerClient loadBalancerclient;
@RequestMapping(value="/user/{id}",produces="application/json")
public User findById(@PathVariable Long id){

return this.restTemplate.getForObject("http://microservice-simple-provider-user/"+id, User.class);
}
@GetMapping("/log-instance")
public void logUser(){
ServiceInstance serviceInstance=loadBalancerclient.choose("microservice-simple-provider-user");
LOGGER.info("{}:{}:{}",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort());
}

}
修改ConsumerMovieApplication.java,加@loadBalanced注解实现负载均衡

package com.zjm;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class ConsumerMovieApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ConsumerMovieApplication.class, args);
}
}
1.启动miroservice-discovery-eureka微服务,2.启动microservice-simple-provider-user两次或者是多次(每启动的一个修改一个端口号),3.启动microservice-consumer-movie-ribbon;访问http://localhost:8761/

图下



看上图,两个服务消费者已经注册进来,starting说明负载均衡的是实时在跑动,所以一直处于运行状态,再次访问http://localhost:8081/user/1 访问结果 
{"id":1,"username":"account1","name":"zhangsan","age":20,"balance":100.00}


再次访问http://localhost:8081/log-instance 不停的刷新如图所示:



可以看出打印出来的8084,8085是我们访问的端口,这样我们已经实现了负载均衡的效果了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring cloud微服务
相关文章推荐