Spring 中使用 Apache FtpServer 时出现“BindException:地址已在使用中”

Ren*_*ler 0 java spring spring-boot

我按如下方式配置了 Apache FtpServer:

@Component
public class FtpDummyServer {

private FtpServer server;

@PostConstruct
public void init() throws FtpException {
    ..some initialization
    this.server = serverFactory.createServer();
    this.server.start();
}

@PreDestroy
public void stop() {
    this.server.stop();
}
Run Code Online (Sandbox Code Playgroud)

请注意,服务器在@PostConstruct 中自动启动。我在 SpringBoot 中配置了不同的测试,如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MainApplication.class)
@WebIntegrationTest
public class ApplicationTestX {
...
}
Run Code Online (Sandbox Code Playgroud)

当我单独运行测试时,它们成功了。然而,当我一起运行它们时,我得到了一个java.net.BindException: Address already in use: bind. 我怎样才能避免这种情况?

Evg*_*eny 5

如果您查看异常堆栈跟踪,您将看到 ftp 服务器尝试使用的地址。有点像

引起原因:org.apache.ftpserver.FtpServerConfigurationException:无法绑定到地址0.0.0.0/0.0.0.0:21,请检查配置

发生这种情况可能是因为:

  1. 您的应用程序的另一个实例使用地址。如果是这样,您需要终止它们。
  2. 其他一些进程使用地址/端口。在这种情况下,您可以重新配置 ftp 服务器以绑定到另一个地址。

    FtpServerFactory serverFactory = new FtpServerFactory();
    
    ListenerFactory factory = new ListenerFactory();
    factory.setPort(2222); //use alternative port instead of default 21
    serverFactory.addListener("default", factory.createListener());
    
    server = serverFactory.createServer();
    server.start();
    
    Run Code Online (Sandbox Code Playgroud)

使用 netstat 找出保存地址的进程 ID。