【springcloud研究 第三篇】Ribbon进程级负载均衡

一,概述

1,当前市面上进行负载均衡有三个层级

nginx软件级
f5硬件级
ribbon进程级

2,本文需要的资源下载地址

https://github.com/forezp/SpringCloudLearning/tree/master/sc-f-chapter2

3,本文涉及到的项目

eureka-server服务注册与发现
service-hi客户端访问
service-ribbon负载均衡器

二,开始研究

1 service-ribbon项目分析

pom

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

 properties

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8764
spring:
  application:
    name: service-ribbon

java代码

package com.forezp.serviceribbon;

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.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class ServiceRibbonApplication {

    public static void main(String[] args) {
        SpringApplication.run( ServiceRibbonApplication.class, args );
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

 负载均衡的关键注解

@LoadBalanced

 通过这个注解可以让restTemplate具有负载均衡的效果,栗子

restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);

如果此时调用如上的方法,将会自动轮询注册在节点上的多个(应用名为service-hi)

server:
  port: 8763

spring:
  application:
    name: service-hi

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

中的其中一个

效果

hi forezp,i am from port:8762

hi forezp,i am from port:8763

三,

1 架构图

æ­¤æ¶æ¶æå¾.png

四,总结

1 ribbon通过注册在eurka上的多个相同service-hi实例,现实论询

2 eurka是所有服务的注册点,连通eurka就能获得相应的资源,比如负载均衡

3 restTemplate是个好东西

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值