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

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈灬大灬海

万水千山总是情

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值