我正在一个项目中,我有不同的模式在不同的数据库中的两个表。因此,这意味着我有这两个表的两种不同的连接参数使用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