1. 程式人生 > 實用技巧 >【筆記】負載均衡Robbin之不同服務使用不同的策略

【筆記】負載均衡Robbin之不同服務使用不同的策略

裂開裂開,搞這麼久忘記匯入依賴 媽賣批
又不報錯 還能讓我玩 我以為全部匯入了。
話不多說,開始演示。

介紹

給不同的服務 配置 不同的 負載均衡策略
這裡使用 使用者模組 進行訪問其它兩個模組的controller資料
但是 在訪問時 要配置各自的 負載均衡策略

也就是訪問服務時 進入到 各自的 負載均衡策略 配置類裡面找到相對應的 IRule

一、建立專案 自己玩。。。。

二、匯入依賴

父依賴

子依賴

三、建立OrderController

package top.yangbuyi.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yangbuyi.utils.ResponseResult;

/**
 * @description: 楊不易網站:www.yangbuyi.top
 * @program: yangbuyispringcloudparent
 * @ClassName: OrderController
 * @create: 2020-07-31 21:36
 * @author: yangbuyi
 * @since: JDK1.8
 * @OrderController:
 **/

@RestController
@Slf4j
@RequestMapping("order")
public class OrderController {

	  @RequestMapping("getOrder")
	  public HashMap getOrder(){
             // 這裡等會修改的   

            HashMap map = new HashMap<>();
			map.put("msg","Spring Boot cloud getOrder22222222222222222 Hello World!");
	  	  return map;
	  }
}

四、建立application.yml

server:
  port: 9000
eureka:
  client:
    serviceUrl:
      #eureka服務端提供的註冊地址 參考服務端配置的這個路徑   也就是說 這裡的路徑為服務端配置的路徑 必須一致  表示註冊到哪個註冊中心
      defaultZone: http://eureka1:3000/eureka,http://eureka2:3001/eureka,http://eureka3:3002/eureka 
  instance:
    instance-id: order-2 #此例項註冊到eureka服務端的唯一的例項ID
    prefer-ip-address: true #是否顯示IP地址
    #eureka客戶需要多長時間傳送心跳給eureka伺服器,表明它仍然活著,預設為30 秒 (與下面配置的單位都是秒)
    leaseRenewalIntervalInSeconds: 10
    #Eureka伺服器在接收到例項的最後一次發出的心跳後,需要等待多久才可以將此例項刪除,預設為90秒
    leaseExpirationDurationInSeconds: 30
# 例項名稱 例項名稱 相同為 叢集
spring:
  application:
    name: provide-order #此例項註冊到eureka服務端的name

五、我們建立一個 使用者模組用於呼叫 負載均衡

上面相同的操作

建立一個配置資料夾

建立OrderConfigRibbon配置負載均衡策略

package top.yangbuyi.config;


import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description: 楊不易網站:www.yangbuyi.top
 * @program: yangbuyispringcloudparent
 * @ClassName: GoodsConfigRibbon
 * @create: 2020-08-05 14:58
 * @author: yangbuyi
 * @since: JDK1.8
 * @GoodsConfigRibbon:
 **/
@Configuration
public class OrderConfigRibbon {

	  /**
	   * @Description: 楊不易個人網址:http://yangbuyi.top
	   * 功能描述:
	   * @Param:
	   * @return: 輪詢
	   * @Author: TeouBle
	   * @Date: 2020/8/5 15:02
	   */
	  public IRule iRule(){
			System.out.println("觸發了  輪詢排程規則--------OrderConfigRibbon");
			return new RoundRobinRule();
	  }

}

建立GoodsConfigRibbon配置負載均衡策略

package top.yangbuyi.config;


import com.netflix.loadbalancer.IRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.yangbuyi.Rule.yangbuyiRule;

/**
 * @description: 楊不易網站:www.yangbuyi.top
 * @program: yangbuyispringcloudparent
 * @ClassName: GoodsConfigRibbon
 * @create: 2020-08-05 14:58
 * @author: yangbuyi
 * @since: JDK1.8
 * @GoodsConfigRibbon:
 **/
@Configuration
public class GoodsConfigRibbon {

	  /**
	  * @Description: 楊不易個人網址:http://yangbuyi.top
	  * 功能描述:
	  * @Param: 
	  * @return: 偽隨機
	  * @Author: TeouBle
	  * @Date: 2020/8/5 15:46
	  */
	  @Bean
	  public IRule iRule(){
			// 隨機演算法  偽隨機
			System.out.println("觸發了  偽隨機排程規則--------GoodsConfigRibbon");
			return new yangbuyiRule();
	  }
}

建立偽隨機演算法 用於替換負載均衡策略

package top.yangbuyi.Rule;


import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @description: 楊不易網站:www.yangbuyi.top
 * @program: yangbuyispringcloudparent
 * @ClassName: yangbuyi_Rule
 * @create: 2020-08-02 23:30
 * @author: yangbuyi
 * @since: JDK1.8
 * @yangbuyi_Rule: 隨機 負載均衡
 **/
public class yangbuyiRule extends AbstractLoadBalancerRule {

	  /**
	   * 開始下標
	   */
	  private int nowIndex = -1;
	  /**
	   * 最後的下標
	   */
	  private int lastIndex = -1;
	  /**
	   * 記錄要跳過 的記錄數 (上一次的下標等於當前的下標 表示要跳過的下標)
	   */
	  private int skipIndex = -1;


	  /**
	   * Randomly choose from all living servers
	   */
	  public Server choose(ILoadBalancer lb, Object key) {
			if (lb == null) {
				  return null;
			}
			Server server = null;

			while (server == null) {
				  if (Thread.interrupted()) {
						return null;
				  }
				  // 獲取可用的服務
				  List upList = lb.getReachableServers();
				  // 獲取全部服務列表
				  List allList = lb.getAllServers();

				  // 獲取所有的數量
				  int serverCount = allList.size();
				  if (serverCount == 0) {
						/*
						 * No servers. End regardless of pass, because subsequent passes
						 * only get more restrictive.
						 */
						return null;
				  }

				  /*
				   * 偽隨機:思路 當重複隨機到一臺服務兩次時判斷第三次是否還是它  是的話  我們要進行 再次隨機 也就是第三次
				   * 當一個下標(偽服務)連線被呼叫兩次
				   * 第三次如果還是它,就讓再隨機一次
				   * */

				  // 隨機一次  獲取一個在serverCount範圍內的隨機數
				  int index = chooseRandomInt(serverCount);

				  // 要不要跳過 表示跳過的條件
				  if (index == skipIndex) { // 1,1,1
						System.out.println("要重新隨機");
						index = chooseRandomInt(serverCount);
						// 清空 跳過記錄值
						skipIndex = -1;
				  }

				  // 要進行記錄當前的下標
				  nowIndex = index;
				  if (lastIndex == nowIndex) {
						// 如果 上一次的角標 等於  當前角標 就要 跳過了
						skipIndex = nowIndex; // skipIndex = 1
				  }
				  // 記錄 上一次的下標
				  lastIndex = nowIndex;


				  // 從可用的微服務列表中,獲取隨機的微服務出來
				  server = upList.get(index);

				  if (server == null) {
						/*
						 * The only time this should happen is if the server list were
						 * somehow trimmed. This is a transient condition. Retry after
						 * yielding.
						 */
						Thread.yield();
						continue;
				  }

				  if (server.isAlive()) {
						return (server);
				  }

				  // Shouldn't actually happen.. but must be transient or a bug.
				  server = null;
				  Thread.yield();
			}

			return server;

	  }

	  protected int chooseRandomInt(int serverCount) {
			return ThreadLocalRandom.current().nextInt(serverCount);
	  }

	  @Override
	  public Server choose(Object key) {
			return choose(getLoadBalancer(), key);
	  }

	  @Override
	  public void initWithNiwsConfig(IClientConfig clientConfig) {
			// TODO Auto-generated method stub

	  }


}

最重要的一步 記得依賴要configuration

package top.yangbuyi;


import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import com.netflix.loadbalancer.Server;
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.cloud.netflix.ribbon.RibbonClientName;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.web.client.RestTemplate;
import top.yangbuyi.Rule.yangbuyiRule;
import top.yangbuyi.config.GoodsConfigRibbon;
import top.yangbuyi.config.OrderConfigRibbon;

/**
 * @description: 楊不易網站:www.yangbuyi.top
 * @program: yangbuyispringcloudparent
 * @ClassName: UserApplication
 * @create: 2020-07-31 20:24
 * @author: yangbuyi
 * @since: JDK1.8
 * @UserApplication: 手寫springBoot啟動
 * UserApplication
 **/
@SpringBootApplication
@EnableEurekaClient // 註冊中心

// 給不同的服務 配置 不同的 負載均衡策略  這裡最重要   表示訪問服務時 進入到 各自的 負載均衡策略 配置類裡面找到相對應的  IRule
@RibbonClients({
		@RibbonClient(name="provide-goods",configuration = GoodsConfigRibbon.class),
		@RibbonClient(name="provide-order",configuration = OrderConfigRibbon.class),
})
public class UserApplication {

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

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

}

看到這裡 可能 讀者會看不懂。。這是我的筆記嗯。。。

完。。。。。。





你的壓力來源於無法自律,只是假裝努力,現狀跟不上內心慾望,所以你焦慮又恐慌。——楊不易