2016-11-29 25 views
1

我有一個Web項目,我正在使用Spring集成通過FTP在遠程目錄上進行文件上傳。但是,FTP屬性是動態加載的(來自數據庫),並且它們對於每個請求都可能不同。原始的方法:春季集成上傳與動態FTP屬性

最初創建DefaultFtpSessionFactory豆:

@Bean 
public DefaultFtpSessionFactory defaultFtpSessionFactory() { 
    return new DefaultFtpSessionFactory(); 
} 

IntegrationFlow豆:

@Bean 
public IntegrationFlow integrationFlow(DefaultFtpSessionFactory defaultFtpSessionFactory) { 
    // Flow config 
} 

注入這個bean到控制器和設置屬性:

@Autowired 
private DefaultFtpSessionFactory defaultFtpSessionFactory; 

@Autowired 
private FtpConfigService ftpConfigService; 

@RequestMapping(value = "upload", method = RequestMethod.GET) 
public RequestEntity<String> upload() { 
    defaultFtpSessionFactory.setHost(ftpConfigService.getHost()); 
    // Set other properties 
    // ... and upload file 

    return new RequestEntity<>(HttpStatus.OK); 
} 

當然,這由於存在競爭條件(兩個請求者),所以這是一個壞主意sts可以在同一時間訪問DefaultFtpSessionFactory單身人士)。那麼,我怎樣才能以安全的方式實現這一目標呢?

+0

您可以做的是創建一個消息,其中包含您的ftp負載和會話屬性,您可以使用它更新流中的sessionFactory。 – JEY

回答

1

動態註冊流程的最後一部分 - 請參閱the blog introducing the feature;也許將這些流保存在緩存中。

有關我們創建多個tcp客戶端適配器並緩存輸入通道的示例,請參見dynamic-tcp-client;對ftp使用類似的技術 - 還有一箇舊版本的dynamic-ftp,它預先記錄了DSL和動態流量註冊。

+0

自從我使用Spring 4以來,我看了一下動態FTP示例。據我所知,對於每個新的'MessageChannel',您都要創建一個新的'ApplicationContext'並緩存它。是否有可能避免創建上下文?另外,爲了使所有的工作都能正常工作,應用程序啓動時不應該自動佈線bean。這使得事情非常不方便,因爲配置類/ XML必須超出'@ ComponentScan'範圍。 –

+0

動態流方法(用在我引用的tcp示例中)不會創建子上下文。您還可以使用[委託會話工廠](http://docs.spring.io/spring-integration/reference/html/ftp.html#ftp-dsf),其中實際的連接/會話從「ThreadLocal」確定。 –