springboot使用随机端口暴露的问题解决方法

随机端口

我们知道为spring boot配置随机端口非常简单,有两种办法:

  1. 设置端口为0
server.port=0
eureka.instance.instance-id=${spring.application.name}-${spring.cloud.client.ipAddress}:${random.int}
  1. 设置端口为随机值
server.port=${random.int[1000,1999]}

问题

我们无论使用上述的哪种办法,都会存在一些问题,有且不限于如下:

  1. eureka界面上的Status无法显示真实的端口
  2. 点击Status列的链接会跳转到错误的端口
  3. 如果使用了LoadBalancerInterceptor会导致连接异常,原因也是导向了错误的端口
  4. ...

解决思路

不难发现问题的根本就是每个地方都会再调用一次random.int生成不同的随机数,如果新生成的随机数被赋予端口意义使用,那么会因为这个数和真实端口并不一致导致发生异常。

random.int 是springboot默认提供的,我想实现一个自己的random.int,只赋值一次即可,往后再调用便返回已生成的值。

解决方法

  1. random.int 是springboot默认提供的,Ctrl+Click 发现实现类是RandomValuePropertySource.

  2. 我尝试把server.port=${random.int[1000,2000]}改成server.port=${randomServerPort.value[1000,2000]}${randomServerPort.value[1000,2000]}是我们要自定义的),运行后得到异常的堆栈信息

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'randomServerPort.value[1000,2000]' in value "${randomServerPort.value[1000,2000]}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174) ~[spring-core-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:236) ~[spring-core-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.core.env.AbstractPropertyResolver.resolveNestedPlaceholders(AbstractPropertyResolver.java:227) ~[spring-core-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:84) ~[spring-core-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:66) ~[spring-core-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:537) ~[spring-core-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.boot.bind.RelaxedPropertyResolver.getProperty(RelaxedPropertyResolver.java:84) ~[spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.bind.RelaxedPropertyResolver.getProperty(RelaxedPropertyResolver.java:74) ~[spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ManagementServerPort.getPortProperty(EndpointWebMvcAutoConfiguration.java:409) ~[spring-boot-actuator-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ManagementServerPort.get(EndpointWebMvcAutoConfiguration.java:361) ~[spring-boot-actuator-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$OnManagementMvcCondition.getMatchOutcome(EndpointWebMvcAutoConfiguration.java:345) ~[spring-boot-actuator-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47) ~[spring-boot-autoconfigure-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    ... 16 more
  1. 从堆栈信息中找到解析的类PropertyPlaceholderHelper,打上断点

  2. 跳转到PropertySourcesPropertyResolver,找到了真正的解析器propertySources

  3. 我们只要自己写一个PropertySource,然后放进去就可以了。照着RandomValuePropertySource写一个自己的

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.PropertySource;
import org.springframework.util.StringUtils;

@Slf4j
public class RandomServerPortPropertySource extends PropertySource<RandomServerPort> {

    /**
     * Name of the random {@link PropertySource}.
     */
    public static final String RANDOM_SERVER_PORT_PROPERTY_SOURCE_NAME = "randomServerPort";

    private static final String PREFIX = "randomServerPort.";

    public RandomServerPortPropertySource(String name) {
        super(name, new RandomServerPort());
    }

    public RandomServerPortPropertySource() {
        this(RANDOM_SERVER_PORT_PROPERTY_SOURCE_NAME);
    }

    public RandomServerPortPropertySource(String name, RandomServerPort source) {
        super(name, source);
    }

    @Override
    public Object getProperty(String name) {
        if (!name.startsWith(PREFIX)) {
            return null;
        }
        if (log.isTraceEnabled()) {
            log.trace("Generating randomServerPort property for '" + name + "'");
        }
        return getRandomServerPortValue(name.substring(PREFIX.length()));
    }

    private Object getRandomServerPortValue(String type) {
        String range = getRange(type, "value");
        if (range != null) {
            return getNextValueInRange(range);
        }
        return null;
    }

    private String getRange(String type, String prefix) {
        if (type.startsWith(prefix)) {
            int startIndex = prefix.length() + 1;
            if (type.length() > startIndex) {
                return type.substring(startIndex, type.length() - 1);
            }
        }
        return null;
    }

    private int getNextValueInRange(String range) {
        String[] tokens = StringUtils.commaDelimitedListToStringArray(range);
        int start = Integer.parseInt(tokens[0]);
        if (tokens.length == 1) {
            return getSource().nextValue(start);
        }
        return getSource().nextValue(start, Integer.parseInt(tokens[1]));
    }
}
import org.apache.commons.lang3.RandomUtils;

/**
 * 随机生成一个端口,并只生成一次
 */
public class RandomServerPort {

    private int serverPort;

    private final int start = 0;
    private final int end = 65535;

    public int nextValue(int start) {
        return nextValue(start, end);
    }

    public int nextValue(int start, int end) {
        start = start < this.start? this.start: start;
        end = end > this.end? this.end: end;

        if (serverPort == 0){
            synchronized (this){
                if (serverPort == 0){
                    serverPort = RandomUtils.nextInt(start, end);
                }
            }
        }
        return serverPort;
    }
}

  1. 这种解析器是解析application.properties的,所以需要很早就加载上去,不难想到用ApplicationListener<ApplicationEnvironmentPreparedEvent>
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;

public class MyApplicationEnvironmentPreparedEventListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        event.getEnvironment().getPropertySources().addLast(new RandomServerPortPropertySource());
    }
}
  1. 添加监听器
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.addListeners(new MyApplicationEnvironmentPreparedEventListener());
        app.run(args);
    }
}
  1. 配置文件修改一下
server.port=${randomServerPort.value[1000,2000]}
eureka.instance.instance-id=${spring.application.name}-${spring.cloud.client.ipAddress}:${randomServerPort.value[1000,2000]}

# 省略...
  1. 结果如下


点击跳转


©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,566评论 18 139
  • 方法1 (数据类型)(最小值+Math.random()*(最大值-最小值+1)) 例: (int)(1+Math...
    GB_speak阅读 40,935评论 2 6
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,531评论 18 399
  • 一、這章大概講了什麼? 談到了什麼是python語言、python起源、與相關的特性 首先,python是一門編程...
    小慷阅读 209评论 0 0
  • 二话不说,先上思维导图。因为发现大家更愿意看图,一目了然,哈哈。上节课讲了救拖的2个方法----时间交替法(番茄工...
    熙沐2017阅读 255评论 0 0