如何通过互联网访问本地Spring Boot程序

如何通过互联网访问本地Spring Boot程序

当你需要别人远程访问你本地的Spring Boot的程序的时候,你可以通过Ngrok来帮助你来实现。

什么是Ngrok

Ngrok可以创建一个http隧道,并为您提供一个公共URL,重定向到本地机器上的指定端口。它是一个很棒的开发或者测试目的使用的工具。

Ngrok的官网地址是:https://ngrok.com

image.png

Ngrok Spring Boot Starter

Spring Boot的Web端口可以通过Ngrok Spring Boot Starter暴露到互联网。

Ngrok Spring Boot Starter将会根据你的操作系统自动下载Ngrok的二进制文件并缓存到home_directory/.ngrok2 目录。

每次运行Spring Boot程序的时候,Ngrok会自动构建指向Spring Boot Web程序的http隧道。

该Starter的地址为:https://github.com/kilmajster/ngrok-spring-boot-starter

注册Ngrok

image.png

Spring Boot 代码演示

  • 新建演示项目

image.png

  • 简单的演示代码
@SpringBootApplication
@RestController
public class NgrokDemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(NgrokDemoApplication.class, args);
   }

   @GetMapping("/")
   public String index(){
      return "Hello Ngrok!";
   }

}
  • 添加ngrok-spring-boot-starter依赖

Gradle:

implementation 'io.github.kilmajster:ngrok-spring-boot-starter:0.6.0'

或Maven:

<dependency>
  <groupId>io.github.kilmajster</groupId>
  <artifactId>ngrok-spring-boot-starter</artifactId>
  <version>0.6.0</version>
</dependency>
  • 简单配置 在application.yaml 中:
ngrok:
  enabled: true # 开启ngrok
  auth-token:  ------# 复制上面获取的authtoken到此处
  • 启动程序

image.png

通过Spring Boot控制台,你可以发现:

  1. 启动时程序自动会自动下载ngrok并解压缓存到系统用户的.ngrok下。
  2. 启动ngrok,ngrok dashboard的地址是:http://127.0.0.1:4040
  • 访问ngrok dashboard

image.png

你会发现ngrok为我们提供了两个公网访问的地址,分别是http和https的。

  • 访问ngrok提供的公网地址

image.png

image.png

用手机访问:

image.png

ping 域名返回的也是公网的ip:

image.png

更多关于如何使用的,请参考Starter的项目地址。

感谢支持我的书:《从企业级开发到云原生微服务:Spring Boot实战》

头条文章地址:https://www.toutiao.com/article/7080505822463214093/

参考资料: github.com/kilmajster/ngrok-spring-boot-sta..