我正在一個項目中,我有不同的模式在不同的數據庫中的兩個表。因此,這意味着我有這兩個表的兩種不同的連接參數使用JDBC-通過生成隨機數隨機選擇表的基礎上有百分比
連接我們下面假設是config.property文件 - 其中table1.percentage
意味着時間table1
80%
將有所回升,並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%
它應該選擇的時候就應該選擇table2
table1
和20%
。
它選擇表的事實是無關緊要的。你想要做的是從一組元素中選擇一個隨機元素,但任何元素被選中的概率不是1/size-of-set,而是其他一些數字。現在,請解釋爲什麼您認爲'selectRandomConnection'應該這樣做,或許使用幹運行 – 2013-02-28 22:47:25
請參閱http://stackoverflow.com/questions/1761626/weighted-random-numbers以及側邊欄上的其他問題,搜索加權/偏向隨機數發生器。 – 2013-02-28 22:50:11
你有調試嗎?你有沒有驗證隨機數是你期望的? – 2013-02-28 22:54:47