spring boot 不占用端口方式启动

随着微服务架构的流行,想要启动一个微服务架构项目就要开启好多端口,有时候一台机器上部署的项目多的时候,端口资源就比较紧张了,其实有的微服务组件仅仅只是提供RPC服务,可以不用占用web启动的端口,此时spring boot 不占用web端口的方式就派上用场了,但是spring boot 1.x与spring boot 2.x的配置是有区别的,在使用时一定要注意一下自己所使用的版本

spirngboot 2.x之前(代码方式实现):

1 @SpringBootApplication
2 public class Application {
3 
4 public static void main(String[] args) {
5      new SpringApplicationBuilder().sources(Application.class).web(false).run(args);
6   }
7 }

spinrboot 2.x之前(另外一种代码实现方式)

1 @Configuration
2 @EnableAutoConfiguration
3 public class MyClass{
4     public static void main(String[] args) throws JAXBException {
5           SpringApplication app = new SpringApplication(MyClass.class);
6           app.setWebEnvironment(false);
7           ConfigurableApplicationContext ctx = app.run(args);
8      }
9 }

spinrboot 2.x之前(配置方式)

spring.main.web-environment=false

springboot 2.x之后(代码方式)

1 @SpringBootApplication
2 public class MyApplication {
3 
4 public static void main(String[] args) {
5       new SpringApplicationBuilder(MyApplication.class)
6              .web(WebApplicationType.NONE) // .REACTIVE, .SERVLET
7              .run(args);
8        }
9 }

springboot 2.x之后(配置方式)

spring.main.web-application-type=none

  

不过这里有个点需要注意,如果配置成不占用端口的方式启动,若main方法执行完后,没其他的deamon线程在跑,应用就会自动关闭了,有些新同学最容易放这种错误,并且还不清楚错误在哪;

在使用阻塞线程时,这里也有个坑,有人使用System.in.read();进行阻塞,这种写法在window环境下是没问题的,但是在linux下会出现不阻塞的情况,具体可参考这篇文章:https://blog.csdn.net/zistrong/article/details/84758138

推荐写法:

/**
 * @Description: TODO
 * @Author Mr.huang
 * @Date 2019/10/28 0028
 * @Version V1.0
 **/
@SpringBootApplication
@EnableScheduling
public class GameDataServerApplication implements CommandLineRunner{
    private static final Logger logger = LoggerFactory.getLogger(GameDataServerApplication.class);
    public static void main(String[] args) {
       SpringApplication.run(GameDataServerApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
//这里也可以添加一些业务处理方法,比如一些初始化参数等
while(true){ try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { logger.error("oi进程意外结束",e); } } } }

 

posted @ 2019-10-29 10:26  愤怒的码农  阅读(6899)  评论(0编辑  收藏  举报