栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

关于负载均衡策略的demo实例

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于负载均衡策略的demo实例

1、问题描述
  • 写两个文件—— testA.txt,testB.txt,10000条记录,80%的记录写道testA文件里,20%的记录写道testB文件里。
  • 附加要求:
    1、写入要平滑,即避免集中写入,要分开
    2、支持并发,注意控制
    3、代码尽量优雅
    4、日志节点要明确,能通过日志清晰的了解程序运行动向
2、基于加权轮询算法的代码
import java.io.*;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class LoadBalanceOfWeightRoundRobin {
   private static int pos = 0;
   private static Map serviceWeightMap = new HashMap<>();
   private static String writer_A = "w_A";
   private static String writer_B = "w_B";
   static FileWriter fw_A;
   static BufferedWriter bw_A;
   static FileWriter fw_B;
   static BufferedWriter bw_B;

   private int inputNum;


  public LoadBalanceOfWeightRoundRobin(int inputNum ) {
       this.inputNum = inputNum;
   }

   private static int num = 10000;

   // 静态代码块
   static {
       // A文件, 权重为 4
       serviceWeightMap.put(writer_A, 80);
       // B文件, 权重为 1
       serviceWeightMap.put(writer_B, 20);

       String filepath = System.getProperty("user.dir");
       String filepath_A = filepath + "\data_A.txt";
       String filepath_B = filepath + "\data_B.txt";

       File file_A = new File(filepath_A);
       File file_B = new File(filepath_B);

       if (!file_A.exists()) {
           try {
               file_A.createNewFile();
           } catch (IOException e) {
               e.printStackTrace();
           }
           System.out.println("data_A.txt创建完成");
       }

       if (!file_B.exists()) {
           try {
               file_B.createNewFile();
           } catch (IOException e) {
               e.printStackTrace();
           }
           System.out.println("data_B.txt创建完成");
       }

       try {
           fw_A = new FileWriter(file_A);
           bw_A = new BufferedWriter(fw_A);
           fw_B = new FileWriter(file_B);
           bw_B = new BufferedWriter(fw_B);
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

   //对象方法   被对象引用
//    static final Object pos1=new Object();
   private synchronized String WeightRoundRobin() {
       
       // 重建一个Map,避免服务器的上下线导致的并发问题

       Map serverMap = new HashMap<>(LoadBalanceOfWeightRoundRobin.serviceWeightMap);

       Set keySet = serverMap.keySet();

       Iterator it = keySet.iterator();

       List addrList = new ArrayList<>();

       while (it.hasNext()) {
           String writer = it.next();
           int weight = serverMap.get(writer);
           for (int i = 0; i < weight; i++) {
               addrList.add(writer);
           }
       }
       String s=null;
//        synchronized(pos1){
           s = addrList.get(pos++ % addrList.size());
           System.out.println(s    );
//        }
       return s;
   }

   private void run() {
       
       try {
           String writer = WeightRoundRobin();
           String uuid = UUID.randomUUID().toString().replaceAll("-", "");
           if (writer.equals(writer_A)) {
//                System.out.println("当前线程:" + Thread.currentThread().getName() + "  编号:"+inputNum  );
               bw_A.write("当前线程:" + Thread.currentThread().getName() + "  编号:" +inputNum+ "n");
               bw_A.flush();
               fw_A.flush();
           } else {
//                System.out.println("当前线程:" + Thread.currentThread().getName() + "  编号:"+inputNum );
               bw_B.write("当前线程:" + Thread.currentThread().getName() + "  编号:" +inputNum+"n");
               bw_B.flush();
               fw_B.flush();
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
   }


   
   public static void main(String[] args) throws InterruptedException {
       ExecutorService executorService = Executors.newFixedThreadPool(20);
       CountDownLatch countDownLatch = new CountDownLatch(num);


       LoadBalanceOfWeightRoundRobin loadBalanceOfWeightRoundRobin = new LoadBalanceOfWeightRoundRobin(1);
       for (int i = 0; i < num; i++) {
           executorService.submit(()-> {
               loadBalanceOfWeightRoundRobin.run();
               countDownLatch.countDown();
           });
       }

       countDownLatch.await();
       executorService.shutdown();
   }
}
3、运行结果


4、遗留问题

输出平滑性问题。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/680144.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号