springboot不占用端口啟動


非web工程

在服務架構中,有些springboot工程只是簡單的作為服務,並不提供web服務

這個時候不需要依賴

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

但是啟動springboot的話,啟動之后就會自動關閉,可以通過如下方式解決

實現CommandLineRunner,重寫run方法即可,這樣啟動后就不會關閉

@SpringBootApplication
@EnableDubbo
public class SeaProviderLogApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(SeaProviderLogApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("SeaProviderLogApplication正在啟動。。。");
        while(true) {
            Thread.sleep(600000000);
            System.out.println("sleep....");
        }
    }
}

有人可能會說,引入spring-boot-starter-web主要是為了方便測試,其實完全可以使用單元測試進行操作

使用@SpringBootTest@RunWith(SpringRunner.class)注解即可進行單元測試代碼如下

@SpringBootTest
@RunWith(SpringRunner.class)
public class IndexControllerTest {

    @Reference(version = "1.0.1")
    private ErrorLogService errorLogService;

    @Test
    public void bbb() {
        ErrorLog errorLog = new ErrorLog();
        errorLog.setName("error");
        System.out.println(errorLogService.sendMsg(errorLog));
    }
}

web工程

 但是有時候由於maven聚合工程,會依賴common或者parent,會自然的引入了

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

 這個時候啟動的話,默認端口是8080,當然是可以在application.properties中配置

server.port=8081 來進行修改,但是比較麻煩,因為本就不暴露http請求,沒必要添加spring-boot-starter-web依賴,服務多的話也端口設置也讓人頭疼,會產生端口占用問題

由於不提供web服務,屬實沒必要暴露端口,可以通過如下兩種方式進行啟動不設置端口號

第一種:

修改application配置文件

spring:
  main:
    allow-bean-definition-overriding: true
    web-application-type: none

 第二種:

修改啟動入口

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application .class)
                .web(WebApplicationType.NONE) // .REACTIVE, .SERVLET
                .run(args);
    }

OK,完美解決,再也不用考慮端口分配問題了

springboot整合dubbo可以參考 springboot2.x純注解整合dubbo

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM