undertow服务配置多端口监听

项目中,需要配置服务对外提供多个不同的端口,以保证访问不同的服务,进行不同业务的处理。使用的是Springboot+Undertow服务容器的方式。

1. undertow依赖的pom文件

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

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

2. 多端口配置

首先需要在配置文件中,增加一个多端口配置的字段,用于配置除过原有server.port之外的端口。我这里配的是additional-ports字段:

server:
  port: 8010
  ## 支持的多端口监听,中间用,隔开,连续端口使用-进行链接
  additional-ports: 8888,8889-8892

其次需要新增config类, 将配置的端口加入启动时的端口监听中。我这里创建的类名为MultiplePortListerConfig,代码如下:

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: 
 * @date: 2022-12-16 18:14
 * @description: 配置undertow监听多端口
 */
@Configuration
public class MultiplePortListerConfig {
    /**
     * 额外端口监听
     */
    @Value("${server.additional-ports}")
    private String additionalPorts;

    @Bean
    public ServletWebServerFactory undertowFactory() {
        UndertowServletWebServerFactory undertowFactory = new UndertowServletWebServerFactory();
        undertowFactory.addBuilderCustomizers(builder -> {
            if (StrUtil.isBlank(additionalPorts)) {
                return;
            }
            String[] ports = additionalPorts.split(",");
           for (String port : ports) {
                if (port.contains("-")){
                    String[] portArr = port.split("-");
                    int start = Integer.parseInt(StrUtil.trim(portArr[0]));
                    int end = Integer.parseInt(StrUtil.trim(portArr[1]));
                    for (int i = start; i<=end; i++){
                        builder.addHttpListener(i, "0.0.0.0");
                    }
                }else {
                    builder.addHttpListener(Integer.parseInt(StrUtil.trim(port)), "0.0.0.0");
                }
            }
        });
        return undertowFactory;
    }
}

启动后,可以看见控制台出现同时监听8010,8888,8889,8890,8891,8892的信息:
在这里插入图片描述

调用不同端口访问服务均可访问成功,证明配置成功。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值