117.info
人生若只如初见

springboot如何获取服务器ip和端口号

在Spring Boot中,可以通过注入ServerProperties来获取服务器的IP和端口号。具体步骤如下:

  1. application.propertiesapplication.yml配置文件中,设置服务器端口号(如果已经设置,可以跳过此步骤):
server.port=8080
  1. 创建一个类,并注入ServerProperties
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Component;
@Component
public class ServerInfo {
private final ServerProperties serverProperties;
@Autowired
public ServerInfo(ServerProperties serverProperties) {
this.serverProperties = serverProperties;
}
public String getServerAddress() {
return serverProperties.getAddress().getHostName();
}
public int getServerPort() {
return serverProperties.getPort();
}
}
  1. 在需要获取服务器IP和端口号的地方,注入ServerInfo类,并调用相应的方法:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
private final ServerInfo serverInfo;
@Autowired
public MyController(ServerInfo serverInfo) {
this.serverInfo = serverInfo;
}
@GetMapping("/info")
public String getInfo() {
String serverAddress = serverInfo.getServerAddress();
int serverPort = serverInfo.getServerPort();
return "Server IP: " + serverAddress + ", Server Port: " + serverPort;
}
}

这样,当访问/info接口时,将返回服务器的IP和端口号。

未经允许不得转载 » 本文链接:https://www.117.info/ask/febddAzsLBg5UDFc.html

推荐文章

  • springboot怎么上传文件到服务器

    在Spring Boot中上传文件到服务器可以通过以下步骤实现: 在pom.xml文件中添加以下依赖: org.springframework.boot
    spring-boot-starter-web org.springfr...

  • springboot怎么下载服务器上的文件

    要下载服务器上的文件,可以使用Spring Boot中的RestTemplate类来发送HTTP GET请求并获取文件内容。以下是一个示例代码:
    import org.springframework.core...

  • 怎么上传源码到云服务器

    上传源码到云服务器可以通过以下步骤进行: 获取云服务器的登录信息:包括IP地址、用户名和密码等。这些信息通常由云服务提供商提供。 使用SSH客户端连接到云服务...

  • 如何远程连接到自己的云服务器上

    要远程连接到您的云服务器,您可以按照以下步骤进行操作: 获取云服务器的IP地址和登录凭据,包括用户名和密码或者SSH密钥。 打开终端或命令提示符窗口(对于Win...

  • java异步接口怎么返回结果

    在Java中,异步接口可以通过回调函数、Future和CompletionStage等方式返回结果。 回调函数:定义一个接口,其中包含一个回调方法,异步操作完成后,通过回调函数...

  • springboot配置日志的方法是什么

    在Spring Boot中配置日志有以下几种方法: 使用application.properties或application.yml文件进行配置。可以在配置文件中使用logging.level.=来设置不同日志级别...