@SpringBootApplication
public class L3Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(L3Application.class);
app.addListeners(new ApplicationListener<ApplicationEnvironmentPreparedEvent>() {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
//IncrServerPort见下一节内容
event.getEnvironment().getPropertySources().addLast(new IncrServerPort());
}
});
app.run(args);
}
}
4.3 IncrServerPort(PropertySource)实现
java复制代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.PropertySource;
@Slf4j
public class IncrServerPort extends PropertySource<RandomServerPort> {
//与配置文件一致即可
private final static String RANDOM_SERVER_PORT_PROPERTY_SOURCE_NAME = "randomServerPort";
//与配置文件一致即可,注意后面有个英文点
private static final String PREFIX = "randomServerPort.";
public IncrServerPort() {
super(RANDOM_SERVER_PORT_PROPERTY_SOURCE_NAME,new RandomServerPort());
}
@Override
public Object getProperty(String name) {
if (!name.startsWith(PREFIX)) {
return null;
}
return getRandomServerPortValue(name.substring(PREFIX.length()));
}
/**
* 本方法实际上即为,自增端口的一种逻辑:
* 通过轮询的方式检查本地端口是否可用,不可用则+1再试
* */
private int getRandomServerPortValue(String values){
values = values.replace("value:","");
String[] ports = values.split(",");
try{
if(ports.length == 0){
//详细逻辑实现代码:ports[0] 到 65535
return new RandomServerPort().value(Integer.parseInt(ports[0]));
}else{
//详细逻辑实现代码:ports[0] 到 ports[1]
return new RandomServerPort().value(Integer.parseInt(ports[0]),Integer.parseInt(ports[1]));
}
}catch (Exception e){
e.printStackTrace();
return 8080;
}
}
}
4.4 详细逻辑实现
java复制代码
@Slf4j
public class RandomServerPort {
public int value(int start) {
return value(start, 65535);
}
public int value(int start, int end) {
log.info("Now checking server port from {} to {}.",start,end);
for(int port = start;port < end;port ++){
//如果端口能连接上,则说明该端口已经被占用了,那就该尝试下一端口
if(!checkIpPort("127.0.0.1",port)){
return port;
}else{
log.error("Port {} is not available, now checking the next port.", port);
}
}
log.error("No available port for this project.");
return start;
}
/**
* 检测Ip和端口是否可用
*
* @param ip
* @param port
* @return
*/
private boolean checkIpPort(String ip, int port) {
Socket socket = new Socket();
try {
socket.connect(new InetSocketAddress(ip,port),10);
return true;
} catch (Exception e) {
return false;
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}