Spring Cloud 学习之旅 --- 随机端口启动多实例

本文探讨了在SpringCloud环境中使用随机端口启动多个服务实例的方法,对比了使用${random.int}

本文内容很简单,就是使用随机端口来启动多个实例。

还记得之前我们在 Spring Cloud 学习之旅 — 服务注册与发现(二) 学习创建服务提供者的时候,我们写了个配置文件吗?在配置文件中,我们指定了一个 2222 端口作为我们的监听端口,但是往往我们的服务提供者是多实例的,因此如果在单台机器中启动多个实例,不修改监听端口,势必会造成端口冲突,导致启动一个实例后,后续实例无法正常启动。

那么这里有两种解决方法:
(一)配置多个配置文件,通过不同的启动参数设置不同的端口进行实例的运行。
(二)采用随机端口的方式,每次启动时获取一个随机端口进行启动。

第一个方法其实很有效,但是在本文中,介绍的是第二种方法。

.properties / .yml 文件中,设置 server.port 属性的值为 ${random.int} 或者设置其值为 0 即可。

下面我们来做一个实验。


我们先启动我们的注册中心和服务消费者,以观察我们的最终结果。(由于注册中心会定时刷新可使用的服务提供者名单,所以修改了服务提供者后,无需等待服务提供者注册后再重启消费者)


实验(一)

采用 ${random.int} 的方式取随机值

修改配置文件,使 server.port 配置的值为 ${random.int} ,具体如下图:
这里写图片描述

随后将其启动,我们看看控制台的输出。

2017-06-19 19:33:57.321  INFO 10512 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 14572 (http)
2017-06-19 19:33:57.322  INFO 10512 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 14572

可以看到其中一条,我们的tomcat监听了14572端口。接着我们打开注册中心看看,具体如下图:
这里写图片描述

可以看到服务的确正常注册进来了。我们通过上一节的消费者调用一下该服务,看看效果。具体如下图:
这里写图片描述

但是好像有点事与愿违。我们为什么会调用不到呢?

我们查看一下注册中心中的simple-service的实例情况。我们通过访问注册中心的 /eureka/apps 查看所有注册到注册中心的实例的信息。

<applications>
    <versions__delta>1</versions__delta>
    <apps__hashcode>UP_5_</apps__hashcode>
    <application>
        <name>SIMPLE-SERVICE</name>
        <instance>
            <instanceId>simple-service:-87414967</instanceId>
            <hostName>localhost</hostName>
            <app>SIMPLE-SERVICE</app>
            <ipAddr>172.30.0.177</ipAddr>
            <status>UP</status>
            <overriddenstatus>UNKNOWN</overriddenstatus>
            <port enabled="true">14258</port>
            <securePort enabled="false">443</securePort>
            <countryId>1</countryId>
            <dataCenterInfo class="com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo">
                <name>MyOwn</name>
            </dataCenterInfo>
            <leaseInfo>
                <renewalIntervalInSecs>5</renewalIntervalInSecs>
                <durationInSecs>10</durationInSecs>
                <registrationTimestamp>1497872037342</registrationTimestamp>
                <lastRenewalTimestamp>1497872287304</lastRenewalTimestamp>
                <evictionTimestamp>0</evictionTimestamp>
                <serviceUpTimestamp>1497872037342</serviceUpTimestamp>
            </leaseInfo>
            <metadata class="java.util.Collections$EmptyMap"/>
            <homePageUrl>http://localhost:14258/</homePageUrl>
            <statusPageUrl>http://localhost:14258/info</statusPageUrl>
            <healthCheckUrl>http://localhost:14258/health</healthCheckUrl>
            <vipAddress>simple-service</vipAddress>
            <secureVipAddress>simple-service</secureVipAddress>
            <isCoordinatingDiscoveryServer>false</isCoordinatingDiscoveryServer>
            <lastUpdatedTimestamp>1497872037342</lastUpdatedTimestamp>
            <lastDirtyTimestamp>1497872037172</lastDirtyTimestamp>
            <actionType>ADDED</actionType>
        </instance>
    </application>
</applications>

从上方的 <applications> 节点中的 <application> 中,有一个 <port> 断点,看到端口是 14258,与我们启动时控制台的 14572 有点不符,那么到底是什么原因导致这样的情况呢?
其实是每次在读取 server.port 属性时,都会获取到 ${random.int} ,然后对其进行解析,即每次读取该属性时都会重新获取一次随机值。因此会出现服务成功注册,但是缺无法调用的情况,根本原因是端口不对。


实验(二)

修改配置文件,使 server.port 配置的值为 0 ,具体如下图:

这里写图片描述

跟上一个实验相同进行启动,看到控制台的输出,监听端口为 57239 (以本人本机启动为例)

2017-06-19 19:48:04.433  INFO 9380 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 57239 (http)
2017-06-19 19:48:04.434  INFO 9380 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 57239

同样的,我们先不调用,直接看注册信息。访问注册中心IP端口的 /eureka/apps 查看信息。(此次截取的是部分信息)

<instance>
    <instanceId>simple-service:663939329</instanceId>
    <hostName>localhost</hostName>
    <app>SIMPLE-SERVICE</app>
    <ipAddr>172.30.0.177</ipAddr>
    <status>UP</status>
    <overriddenstatus>UNKNOWN</overriddenstatus>
    <port enabled="true">57239</port>
    <securePort enabled="false">443</securePort>
    <countryId>1</countryId>
    <dataCenterInfo class="com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo">
        <name>MyOwn</name>
    </dataCenterInfo>
    <leaseInfo>
        <renewalIntervalInSecs>5</renewalIntervalInSecs>
        <durationInSecs>10</durationInSecs>
        <registrationTimestamp>1497872885163</registrationTimestamp>
        <lastRenewalTimestamp>1497872915123</lastRenewalTimestamp>
        <evictionTimestamp>0</evictionTimestamp>
        <serviceUpTimestamp>1497872885163</serviceUpTimestamp>
    </leaseInfo>
    <metadata class="java.util.Collections$EmptyMap"/>
    <homePageUrl>http://localhost:57239/</homePageUrl>
    <statusPageUrl>http://localhost:57239/info</statusPageUrl>
    <healthCheckUrl>http://localhost:57239/health</healthCheckUrl>
    <vipAddress>simple-service</vipAddress>
    <secureVipAddress>simple-service</secureVipAddress>
    <isCoordinatingDiscoveryServer>false</isCoordinatingDiscoveryServer>
    <lastUpdatedTimestamp>1497872885163</lastUpdatedTimestamp>
    <lastDirtyTimestamp>1497872885130</lastDirtyTimestamp>
    <actionType>ADDED</actionType>
</instance>

此次实例的端口是57239 ,与控制台启动的端口相同。我们再调用一下消费者,看看效果。具体如下图:
这里写图片描述

我们可以看到消费者调用服务恢复正常,因此正确的随机多端口启动实例的方式应该是采用 server.port0 的方式。当然,如果读者能够重写配置文件的解析方法,将实验一中的问题排除掉,那么您当我没说这句话23333


### Spring Cloud集成spring-cloud-starter-bus-kafka的使用教程 #### 一、依赖引入 为了在Spring Cloud项目中集成`spring-cloud-starter-bus-kafka`,需要在项目的`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-stream-kafka</artifactId> <version>3.2.4</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-bus</artifactId> <version>3.1.2</version> <scope>compile</scope> </dependency> ``` 这些依赖分别用于支持Kafka消息流和Spring Cloud Bus功能[^4]。 --- #### 二、配置Kafka连接 在`application.yml`或`application.properties`文件中,需配置Kafka的相关参数。以下是YAML格式的示例配置: ```yaml spring: cloud: stream: bindings: input: destination: springCloudBus group: ${spring.application.name} output: destination: springCloudBus kafka: binder: brokers: localhost:9092 zkNodes: localhost:2181 autoCreateTopics: true ``` 以上配置指定了Kafka broker地址以及ZooKeeper节点地址,并启用了自动创建主题的功能[^1]。 --- #### 三、启用Spring Cloud Config Server 如果计划将Kafka与Spring Cloud Config结合使用,则需要在主类上添加`@EnableConfigServer`注解以启动配置服务器。例如: ```java package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; @EnableConfigServer // 开启配置中心服务 @SpringBootApplication // Spring Boot核心配置 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 该注解会激活Spring Cloud Config Server的核心功能[^3]。 --- #### 四、动态刷新配置 通过`spring-cloud-starter-bus-kafka`,可以在运行时发送广播事件以通知所有微服务实例重新加载其配置。具体操作如下: 1. **触发全局刷新** 发送HTTP POST请求至任意服务的`/bus/refresh`端点即可触发整个应用集群的配置更新: ```bash curl -X POST http://localhost:8001/bus/refresh ``` 2. **针对特定服务刷新** 如果仅希望刷新某一个服务的配置,可以通过`destination`参数指定目标服务名称及其端口号。例如: ```bash curl -X POST 'http://localhost:8001/bus/refresh?destination=user-service:application:7005' ``` 这允许更细粒度地控制哪些服务接收到配置变更的通知[^5]。 --- #### 五、安全性增强(可选) 对于生产环境中的高安全需求场景,建议为Kafka设置SSL/TLS加密通信或者SASL_SSL认证机制。相关步骤包括但不限于生成Keystore与Truststore证书文件,并将其路径配置到应用程序属性中[^4]。 --- #### 六、总结 综上所述,在Spring Cloud项目中集成了`spring-cloud-starter-bus-kafka`之后,不仅可以利用Kafka作为分布式消息中间件实现跨服务间高效通讯,还能够借助它完成远程配置管理下的动态调整工作流程优化。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值