获取本机ip地址和端口号

工具类交给Spring管理

package com.lezu.springboot.configuration;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
 
import java.net.InetAddress;
import java.net.UnknownHostException;
 
@Component
public class ServerConfig  implements ApplicationListener<WebServerInitializedEvent> {
    private int serverPort;
 
    public String getUrl() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "http://"+address.getHostAddress() +":"+this.serverPort;
    }
 
    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }
 
}

使用教程

@RestController
public class RedisController {

    @Autowired
    private ServerConfig serverConfig;

    @RequestMapping("/deductStock1")
    public String deductStock1() throws InterruptedException {
        System.out.println("---当前IP和端口号地址:" + serverConfig.getUrl());
        return "success";
    }

}

posted @ 2022-06-07 23:50  难忘是想起  阅读(0)  评论(0)    收藏  举报  来源