spring服务器启动配置文件,Spring启动服务器端口范围设置

该博客展示了如何在Java应用程序中实现自动检测并选择可用端口的方法。通过遍历预设的端口范围,并使用`ServerSocket`和`DatagramSocket`检查端口是否可用,确保找到未被占用的端口来启动服务。此外,还讨论了端口1024的特殊性以及如何从配置文件读取端口范围。
摘要由CSDN通过智能技术生成

当然你可以对下面的 public static boolean available(int port) 进行改进,检查端口的可用性,因为有些端口虽然可用,但有时会被拒绝,如端口1024,依赖于操作系统,也可以从某些属性文件读取范围但不能使用Spring读取,因为范围是在上下文之前设置的加载,但这不应该是一个问题,我把所有东西放在一个文件中,以显示方法,使其看起来不漂亮

@Configuration

@ComponentScan

@EnableAutoConfiguration

public class DemoApplication {

private static final int MIN_PORT = 1100; // to by set according to your

private static final int MAX_PORT = 9000; // needs or uploaded from

public static int myPort; // properties whatever suits you

public static void main(String[] args) {

int availablePort = MIN_PORT;

for (availablePort=MIN_PORT; availablePort < MAX_PORT; availablePort++) {

if (available(availablePort)) {

break;

}

}

if (availablePort == MIN_PORT && !available(availablePort)) {

throw new IllegalArgumentException("Cant start container for port: " + myPort);

}

DemoApplication.myPort = availablePort;

SpringApplication.run(DemoApplication.class, args);

}

public static boolean available(int port) {

System.out.println("TRY PORT " + port);

// if you have some range for denied ports you can also check it

// here just add proper checking and return

// false if port checked within that range

ServerSocket ss = null;

DatagramSocket ds = null;

try {

ss = new ServerSocket(port);

ss.setReuseAddress(true);

ds = new DatagramSocket(port);

ds.setReuseAddress(true);

return true;

} catch (IOException e) {

} finally {

if (ds != null) {

ds.close();

}

if (ss != null) {

try {

ss.close();

} catch (IOException e) {

/* should not be thrown */

}

}

}

return false;

}

}

这是最重要的部分:

@Component

class CustomizationBean implements EmbeddedServletContainerCustomizer {

@Override

public void customize(ConfigurableEmbeddedServletContainer container) {

container.setPort(DemoApplication.myPort);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值