在nGrinder中的Spring 應用

        目前 Spring v3.1 在 nGrinder 中被普遍的應用,從它的Ioc 到 Cache 都有涉及。  java

        Spring Data 在前文已經介紹,不在敘述。 spring

        Spring Cache 數據庫

             在nGrinder 2.X中已經引入cache機制,但在簡單性和效率方面還有必定的欠缺。 緩存

             在nGrinder 3.X 中引進SpringCache。它使用起來很是簡單,只要在方法上添加 app

@Cacheable  //從而讓方法很快返回數據,避免重複處理

         以下是nGrinder 3.0 中的Spring Cache 應用。 異步

  • /ngrinder-controller/src/main/resources/applicationContext-ehcache.xml

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"> <cache:annotation-driven /> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehcache" /> </bean> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml" /> <property name="shared" value="true" /> </bean> </beans>
  • /ngrinder-controller/src/main/resources/ehcache.xml

<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <defaultCache eternal="false" maxElementsInMemory="100" overflowToDisk="false" timeToIdleSeconds="900" timeToLiveSeconds="1800" /> <cache name="users" maxElementsInMemory="100" eternal="false" overflowToDisk="false" timeToIdleSeconds="900" timeToLiveSeconds="1800" /> <cache name="perftest" maxElementsInMemory="100" eternal="false" overflowToDisk="false" timeToIdleSeconds="900" timeToLiveSeconds="1800" /> <cache name="perftestlist" maxElementsInMemory="100" eternal="false" overflowToDisk="false" timeToIdleSeconds="900" timeToLiveSeconds="1800" /> <cache name="file_entry_search_cache" maxElementsInMemory="100" eternal="false" overflowToDisk="false" timeToIdleSeconds="60" timeToLiveSeconds="60" /> </ehcache>
applicationContext-ehcache.xml    爲Spring 配置文件,ehcache.xml  是 詳細的 Cache 配置文件

如下爲nGrinder的代碼  async

public class PerfTestService { /** * Save performance test with given status * * @param test * @param status * @return */ @CacheEvict(value = { "perftest", "perftestlist" }, allEntries = true) public PerfTest savePerfTest(PerfTest test, Status status) { checkNotNull(test); test.setStatus(status); return perfTestRepository.save(test); } @Cacheable(value = "perftest") public PerfTest getPerfTest(long testId) { return perfTestRepository.findOne(testId); } @Cacheable(value = "perftest") public PerfTest getPerfTestCandiate() { return perfTestRepository.findOneByStatusOrderByCreatedDateAsc(Status.READY); } .... }

在代碼中無論調用 getPerfTest(long testId) 仍是getPerfTestCandiate(),系統都會從cache中直接讀取數據。 svn

只有savePerfTest()被調用後,全部的cache數據都會無效,緩存將會從新創建。 spa

        Spring Task code

        在開發過程當中,有時會遇到須要調用比較耗時的方法,且又要很快的響應用戶。通常在這種狀況下,咱們會用 Quartz 或者 數據庫 程序實現異步調用。可是如今可使用 SpringTask。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-3.1.xsd">
 
    <task:annotation-driven executor="myExecutor" scheduler="myScheduler" />
    <task:executor id="myExecutor" pool-size="1" />
    <task:scheduler id="myScheduler" pool-size="1" />
</beans>
在代碼中的實現
@Service
public class FileEntryService {
    /**
     * Create user svn repo.
     *
     * This method is executed async way.
     *
     * @param user
     *            newly created user.
     */
    @Async
    public void prepare(User user) {
        File newUserDirectory = getUserRepoDirectory(user);
        try {
            if (!newUserDirectory.exists()) {
                svnClientManager.getAdminClient().doCreateRepository(newUserDirectory, user.getUserId(), true, true);
            }
        } catch (SVNException e) {
            LOG.error("Error while prepare user {}'s repo", user.getUserName(), e);
        }
    }
....
}
prepare(User user)方法會耗時1~2s,由於須要在nGrinder文件系統中建立基於SVN管理庫。這個方法一般會和新用戶一塊兒建立。咱們能夠加 @Async 註釋。這樣就可讓這個過程在後臺運行,沒必要讓使用者感受到。

SpringTask還能夠很方便的建立定時任務。

/**
 * perf test run scheduler.
 *
 * @author JunHo Yoon
 * @since 3.0
 */
@Component
public class PerfTestRunnable implements NGrinderConstants {
    /**
     * Scheduled method for test execution.
     */
    @Scheduled(fixedDelay = PERFTEST_RUN_FREQUENCY_MILLISECONDS)
    @Transactional
    public void startTest() {
        PerfTest runCandidate = perfTestService.getPerfTestCandiate();
        if (runCandidate == null) {
            return;
        }
        // If there are too many trials, cancel running.
        if (runCandidate.getTestTrialCount() > PERFTEST_MAXIMUM_TRIAL_COUNT) {
            perfTestService.savePerfTest(runCandidate, Status.CANCELED);
        }
        doTest(runCandidate);
    }
 
....
}
@Scheduled  還支持事物控制而且很是穩定。
相關文章
相關標籤/搜索