日交易,根据权重分配流量的算法,根据权重和交易笔数

交易系统,接入多个通道。确保每个通道按权重每日达到相应的交易笔数。

通过实时交易笔数/权重。然后进行升序排序,得到选择通道的次序,进行选择通道。

 1 //a=当前交易笔数/权重。  权重越大,如果交易笔数相等,a越小。权重不变,交易笔数变。a的值大小也在变。
 2 //相对公平的流量分配。
 3 public static void main(String[] args) {
 4     //定义三个通道的权重,按随机数选拔使用哪个通道。
 5     //模拟三个通道的权重A 10  B 70  C 30
 6     //模拟当前交易笔数 A:10  B:50 C:20
 7     //从数据库查询出list集合
 8     ChannelD A=new ChannelD("A",10,10);
 9     ChannelD B=new ChannelD("B",70,50);
10     ChannelD C=new ChannelD("C",30,20);
11     List<ChannelD> channels=new ArrayList<ChannelD>();
12     channels.add(A);
13     channels.add(B);
14     channels.add(C);
15     
16     Map<Double,String> map=new HashMap<Double, String>();
17     Double trade=0.0;
18     //遍历list集合,将交易笔数/权重的值作为key,通道对象为value 存储到map中
19     for (ChannelD channel : channels) {
20         trade=(double) (channel.getCount()/channel.getWeight());
21         map.put(trade,channel.getName());
22     }
23     
24     //将交易笔数/权重的值转化成数据,进行排序。
25     Set<Double> set=map.keySet();
26     Double[] d=set.toArray(new Double[set.size()]);
27     
28     //将数据中的值由小到大进行排序
29     boolean flag=true;
30     for(int i=0;i<d.length-1;i++){
31         flag=true;
32         for(int j=0;j<d.length-1-i;j++){
33             if(d[j]>d[j+1]){
34                 double temp=d[j];
35                 d[j]=d[j+1];
36                 d[j+1]=temp;
37                 flag=false;
38             }
39         }
40         if(flag){
41             break;
42         }
43     }
44     
45     //将排好序的通道名字由小到大的顺序,加入到链表集合中
46     LinkedList<String> chan=new LinkedList<String>();
47     for(int i=0;i<d.length;i++){
48         chan.add(map.get(d[i]));
49     }
50     Iterator<String> it=chan.iterator();
51     while (it.hasNext()) {
52         //最优到最次的通道选择
53         String channelName=it.next();
54         System.out.println("OrderChannelServiceImpl.main()"+channelName);
55         
56     }
57 }
58 
59 class ChannelD{
60     private String name;//通道名字
61     private Integer weight;//权重
62     private Integer count;//当前交易笔数
63     
64     public ChannelD(String name,Integer weight,Integer count){
65         this.name=name;
66         this.weight=weight;
67         this.count=count;
68     }
69 
70     public String getName() {
71         return name;
72     }
73 
74     public void setName(String name) {
75         this.name = name;
76     }
77 
78     public Integer getWeight() {
79         return weight;
80     }
81 
82     public void setWeight(Integer weight) {
83         this.weight = weight;
84     }
85 
86     public Integer getCount() {
87         return count;
88     }
89 
90     public void setCount(Integer count) {
91         this.count = count;
92     }
93     
94     
95     
96 }
View Code
原文地址:https://www.cnblogs.com/shangxiaofei/p/4402448.html