Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-04-12) 阅读数 12 #VPS/云服务器
文章标签 springboot服务器

在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和端口号。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门