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

本文介绍了一个使用Java编写的程序,通过加权轮询算法,实现10000条记录的文件数据在testA.txt和testB.txt之间的平滑分配,支持并发操作并包含日志跟踪。代码展示了如何创建文件、控制并发和使用计数器确保写入的均衡性。
摘要由CSDN通过智能技术生成

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<String, Integer> 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() {
       /**
        * 有两个writer,writer写的动作可以是独立的,现在是要写一个选择器,来选择对应的writer,8000writer、2000writer
        *
        */
       // 重建一个Map,避免服务器的上下线导致的并发问题

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

       Set<String> keySet = serverMap.keySet();

       Iterator<String> it = keySet.iterator();

       List<String> 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() {
       /**
        * 有两个writer,writer写的动作可以是独立的,现在是要写一个选择器,来选择对应的writer,8000writer、2000writer
        */
       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();
       }
   }


   /**
    * 1 、 全局对象    锁是在对象的生命周期内的
    * 2 、 static 静态代码块  lock 全局的
    * @param args
    * @throws InterruptedException
    */
   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、遗留问题

输出平滑性问题。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值