gpt4 book ai didi

performance - 使用 Spring 3.1、Hibernate 4.1、Dbunit 等提高数据库测试的性能

转载 作者:行者123 更新时间:2023-12-01 16:43:25 25 4
gpt4 key购买 nike

我目前正在开始一个新项目,我有大约 190 个存储库测试。我注意到的一件事 - 我不完全确定为什么会这样 - 是针对 HSQLDB (2.2.8) 的集成测试运行速度比我认为的要慢得多。

我想我已经在每次测试之前跟踪了数据插入的瓶颈。对于大多数测试,设置数据库所需的时间从 0.15 秒到 0.38 秒不等。这是无法接受的。我本以为内存数据库会快得多:(

这是我的所有存储库测试都从中扩展的数据库测试类:

@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(defaultRollback=true)
@Transactional
public abstract class DatabaseTest {

public static final String TEST_RESOURCES = "src/test/resources/";

@Autowired
protected SessionFactory sessionFactory;

@Autowired
protected UserRepository userRepository;

@Autowired
protected DataSource dataSource;

protected IDatabaseTester databaseTester;

protected Map<String, Object> jdbcMap;
protected JdbcTemplate jdbcTemplate;

@PostConstruct
public void initialize() throws SQLException, IOException, DataSetException {
jdbcTemplate = new JdbcTemplate(dataSource);

setupHsqlDb();

databaseTester = new DataSourceDatabaseTester(dataSource);
databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
databaseTester.setTearDownOperation(DatabaseOperation.NONE);
databaseTester.setDataSet(getDataSet());
}

@Before
public void insertDbUnitData() throws Exception {
long time = System.currentTimeMillis();

databaseTester.onSetup();

long elapsed = System.currentTimeMillis() - time;
System.out.println(getClass() + " Insert DB Unit Data took: " + elapsed);
}

@After
public void cleanDbUnitData() throws Exception {
databaseTester.onTearDown();
}

public IDataSet getDataSet() throws IOException, DataSetException {
Set<String> filenames = getDataSets().getFilenames();

IDataSet[] dataSets = new IDataSet[filenames.size()];
Iterator<String> iterator = filenames.iterator();
for(int i = 0; iterator.hasNext(); i++) {
dataSets[i] = new FlatXmlDataSet(
new FlatXmlProducer(
new InputSource(TEST_RESOURCES + iterator.next()), false, true
)
);
}

return new CompositeDataSet(dataSets);
}

public void setupHsqlDb() throws SQLException {
Connection sqlConnection = DataSourceUtils.getConnection(dataSource);
String databaseName = sqlConnection.getMetaData().getDatabaseProductName();
sqlConnection.close();

if("HSQL Database Engine".equals(databaseName)) {
jdbcTemplate.update("SET DATABASE REFERENTIAL INTEGRITY FALSE;");

// MD5
jdbcTemplate.update("DROP FUNCTION MD5 IF EXISTS;");
jdbcTemplate.update(
"CREATE FUNCTION MD5(VARCHAR(226)) " +
"RETURNS VARCHAR(226) " +
"LANGUAGE JAVA " +
"DETERMINISTIC " +
"NO SQL " +
"EXTERNAL NAME 'CLASSPATH:org.apache.commons.codec.digest.DigestUtils.md5Hex';"
);
} else {
jdbcTemplate.update("SET foreign_key_checks = 0;");
}
}

protected abstract DataSet getDataSets();

protected void flush() {
sessionFactory.getCurrentSession().flush();
}

protected void clear() {
sessionFactory.getCurrentSession().clear();
}

protected void setCurrentUser(User user) {
if(user != null) {
Authentication authentication = new UsernamePasswordAuthenticationToken(user,
user, user.getAuthorities());

SecurityContextHolder.getContext().setAuthentication(authentication);
}
}

protected void setNoCurrentUser() {
SecurityContextHolder.getContext().setAuthentication(null);
}

protected User setCurrentUser(long userId) {
User user = userRepository.find(userId);

if(user.getId() != userId) {
throw new IllegalArgumentException("There is no user with id: " + userId);
}

setCurrentUser(user);

return user;
}

protected User getCurrentUser() {
return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}

}

这是我的应用程序上下文中的相关 bean:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:applicationContext.properties"/>
</bean>

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${database.driver}"/>
<property name="jdbcUrl" value="${database.url}"/>
<property name="user" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="initialPoolSize" value="10"/>
<property name="minPoolSize" value="10"/>
<property name="maxPoolSize" value="50"/>
<property name="idleConnectionTestPeriod" value="100"/>
<property name="acquireIncrement" value="2"/>
<property name="maxStatements" value="0"/>
<property name="maxIdleTime" value="1800"/>
<property name="numHelperThreads" value="3"/>
<property name="acquireRetryAttempts" value="2"/>
<property name="acquireRetryDelay" value="1000"/>
<property name="checkoutTimeout" value="5000"/>
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>...</value>
</list>
</property>
<property name="namingStrategy">
<bean class="org.hibernate.cfg.ImprovedNamingStrategy"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="javax.persistence.validation.mode">none</prop>

<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}
</prop>
<prop key="hibernate.generate_statistics">false</prop>

<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">true</prop>

<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.cache.provider_class">

</prop>
</props>
</property>
</bean>

<bean class="org.springframework.orm.hibernate4.HibernateExceptionTranslator"/>

<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>

为了尝试插入更少的数据,我允许每个测试类选择一个只加载它需要的数据的数据集枚举。它是这样指定的:

public enum DataSet {
NONE(create()),
CORE(create("core.xml")),
USERS(combine(create("users.xml"), CORE)),
TAGS(combine(create("tags.xml"), USERS)),

这会不会导致它运行得更慢而不是更快?这个想法是,如果我只想要核心 xml(语言、省份等),我只需要加载那些记录。我认为这会使测试套件更快,但它仍然太慢。

我可以通过创建专门为每个测试类设计的单独 xml 数据集来节省一些时间。这会删除一些插入语句。但是,即使我在单个 xml 数据集中有 20 个插入语句(因此,除了将数据集直接内联到 java 代码之外,I/O 损失最小),每个测试在初始化过程中仍然需要 0.1 到 0.15 秒数据库数据!我不敢相信将 20 条记录插入内存需要 0.15 秒。

在我使用 Spring 3.0 和 Hibernate 3.x 的另一个项目中,在每次测试之前插入所有内容需要 30 毫秒,但实际上每次测试插入 100 行或更多行。对于只有 20 个插入的测试,它们正在飞行,就好像根本没有延迟一样。这是我所期望的。我开始认为问题在于 Spring 的注释 - 或者我在 DatabaseTest 类中设置它们的方式。这基本上是现在唯一不同的地方。

此外,我的存储库使用 sessionFactory.getCurrentSession() 而不是 HibernateTemplate。这是我第一次开始使用 Spring 中基于注释的单元测试,因为 Spring 测试类已被弃用。这可能是他们进展缓慢的原因吗?

如果您需要了解任何其他信息以帮助解决问题,请告诉我。我有点难过。

编辑:我输入了答案。问题是 hsqldb 2.2.x。恢复到 2.0.0 可以解决问题。

最佳答案

恕我直言,这看起来相当快。我见过更慢的集成测试。也就是说,有多种方法可以使您的测试更快:

  • 减少插入的数据量
  • 如果数据集相同且前一个测试是只读测试(通常是这种情况,尤其是在每次测试结束时回滚时),请避免插入与前一个测试相同的数据。

我想用 DbUnit 应该可以做到。如果您准备使用其他框架,可以使用我自己的 DbSetup ,开箱即用。

关于performance - 使用 Spring 3.1、Hibernate 4.1、Dbunit 等提高数据库测试的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12876278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com