templates.service.ServiceApplication.ftl Maven / Gradle / Ivy
package ${packageName}.service;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
@EnableTransactionManagement
@MapperScan(basePackages = {"${packageName}.service.**.dao"})
@EnableFeignClients(basePackages = {"${packageName}","org.yes"})
@ComponentScan(basePackages = {"${packageName}","org.yes"})
@EnableDiscoveryClient
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class ServiceApplication implements WebServerFactoryCustomizer {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
@Value("${r'${server.ports}'}")
private String ports;
@Override
public void customize(NettyReactiveWebServerFactory factory) {
String[] split = ports.split(",");
int port = 8080;
for (String ports : split) {
int i = Integer.parseInt(ports);
if (!isLocalPortUsing(i)) {
port = i;
break;
}
}
// 设置端口
factory.setPort(port);
}
/**
* 测试本机端口是否被使用
*
* @param port 端口号
* @return 端口是否被占用
*/
private boolean isLocalPortUsing(int port) {
boolean flag = true;
try {
//如果该端口还在使用则返回true,否则返回false,127.0.0.1代表本机
flag = isPortUsing(port);
} catch (Exception ignored) {
}
return flag;
}
/***
* 测试主机Host的port端口是否被使用
* @param port 端口号
* @throws UnknownHostException
* @return 端口是否被占用
*/
private boolean isPortUsing(int port) throws UnknownHostException {
boolean flag = false;
InetAddress inetAddress = InetAddress.getLocalHost();
try {
//建立一个Socket连接
new Socket(inetAddress, port);
flag = true;
} catch (IOException ignored) {
}
return flag;
}
}