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

关于负载均衡策略的demo实例,第1张

关于负载均衡策略的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、遗留问题

输出平滑性问题。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5680725.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存