2013-02-28 107 views
0

我正在一個項目中,我有不同的模式在不同的數據庫中的兩個表。因此,這意味着我有這兩個表的兩種不同的連接參數使用JDBC-通過生成隨機數隨機選擇表的基礎上有百分比

連接

我們下面假設是config.property文件 - 其中table1.percentage意味着時間table180%將有所回升,並20%的時間table2會根據隨機數挑選。

TABLES: table1 table2 

#For Table1 
table1.percentage: 80  

#For Table2 
table2.percentage: 20 

下面方法將讀取上述config.property文件,並作出ReadTableConnectionInfo對象爲每個表。

private static HashMap<String, ReadTableConnectionInfo> tableList = new HashMap<String, ReadTableConnectionInfo>(); 

private static void readPropertyFile() throws IOException { 

    prop.load(Read.class.getClassLoader().getResourceAsStream("config.properties")); 

    tableNames = Arrays.asList(prop.getProperty("TABLES").split(" ")); 

    for (String arg : tableNames) { 

     ReadTableConnectionInfo ci = new ReadTableConnectionInfo(); 

     double percentage = Double.parseDouble(prop.getProperty(arg + ".percentage")); 

     ci.setPercentage(percentage); 

    tableList.put(arg, ci); 
    } 
} 

下面是ReadTableConnectionInfo類,將保存所有table connection info特定表。

public class ReadTableConnectionInfo { 

    public String percentage; 

    public double getPercentage() { 
     return percentage; 
    } 

    public void setPercentage(double percentage) { 
     this.percentage = percentage; 
    } 
} 

現在在我的run方法每個線程產生的隨機數,然後再決定我需要根據百分比爲每個表使用哪個表。

private static Random random = new SecureRandom(); 


@Override 
public run() { 
    ... 


    while (< 60 minutes) { 
    double randomNumber = random.nextDouble() * 100.0; 
    ReadTableConnectionInfo tableInfo = selectRandomConnection(randomNumber); 

    // do query... 
    } 
} 


//Any problem with the below method? 
private ReadTableConnectionInfo selectRandomConnection(double randomNumber) { 
    double limit = 0; 
    for (ReadTableConnectionInfo ci : tableLists.values()) { 
    limit += ci.getPercentage(); 
    if (randomNumber < limit) { 
     return ci; 
    } 
     } 
    throw new IllegalStateException(); 
    } 

問題陳述: -

有沒有在我的selectRandomConnection方法什麼問題?因爲每個線程都工作了60分鐘,並且在每60分鐘內它只能選擇table1

我所尋找的是時間80%它應該選擇的時候就應該選擇table2table120%

+0

它選擇表的事實是無關緊要的。你想要做的是從一組元素中選擇一個隨機元素,但任何元素被選中的概率不是1/size-of-set,而是其他一些數字。現在,請解釋爲什麼您認爲'selectRandomConnection'應該這樣做,或許使用幹運行 – 2013-02-28 22:47:25

+0

請參閱http://stackoverflow.com/questions/1761626/weighted-random-numbers以及側邊欄上的其他問題,搜索加權/偏向隨機數發生器。 – 2013-02-28 22:50:11

+0

你有調試嗎?你有沒有驗證隨機數是你期望的? – 2013-02-28 22:54:47

回答

1

如果您希望在80%的時間內選擇A,並在20%的時間內選擇B,平均而言,只需選取一個介於0(包含)和100(不包括)之間的隨機數。如果號碼是< 80,則選擇A,否則選擇B.

就這麼簡單。